-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathtyping_game.go
84 lines (69 loc) · 1.32 KB
/
typing_game.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package typing_game
import (
"bufio"
"fmt"
"math/rand"
"os"
"time"
)
type TypingGameInterface interface {
Execute() error
}
type TypingGame struct {
Words []string
TimeLimit time.Duration
}
// result
type resultList struct {
total int
corrects int
}
func NewTypingGame(ws []string, t time.Duration) TypingGame {
tg := TypingGame{
Words: ws,
TimeLimit: t,
}
return tg
}
func (t *TypingGame) shuffle() {
rand.Seed(time.Now().UnixNano())
for i := len(t.Words) - 1; i > 0; i-- {
j := rand.Intn(i + 1)
t.Words[i], t.Words[j] = t.Words[j], t.Words[i]
}
}
func (t TypingGame) Execute() error {
r := &resultList{}
t.shuffle()
keyin := make(chan string)
go func() {
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
keyin <- s.Text()
}
}()
fmt.Print("TYPING start\n")
time.Sleep(500)
timeup := time.After(t.TimeLimit)
LOOP:
for _, word := range t.Words {
fmt.Printf("-> %s\n", word)
select {
case input := <-keyin:
r.total++
if input == word {
fmt.Print("Correct!\n\n")
r.corrects++
} else {
fmt.Print("Missed!\n\n")
}
case <-timeup:
fmt.Print("Time UP!\n\n")
break LOOP
}
}
fmt.Print("Typing Result\n\n")
fmt.Printf("- SCORE: %d points (total %d words)\n", r.corrects, r.total)
fmt.Printf("- Second : %d\n", t.TimeLimit/time.Second)
return nil
}