-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgame.go
86 lines (71 loc) · 1.24 KB
/
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
85
86
package typing
import (
"bufio"
"fmt"
"math/rand"
"os"
"time"
)
type InputReader interface {
Input() <-chan string
}
type Reader struct{}
func (r *Reader) Input() <-chan string {
ch := make(chan string)
go func() {
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
ch <- s.Text()
}
close(ch)
}()
return ch
}
type OutputWriter interface {
Output(string)
}
type Writer struct{}
func (w Writer) Output(outputText string) {
fmt.Println(outputText)
}
type Game struct {
Time time.Duration
Words []string
Reader InputReader
Writer OutputWriter
}
func SetGame(words []string) *Game {
return &Game{
Time: 5,
Words: words,
Reader: &Reader{},
Writer: Writer{},
}
}
func (g *Game) Do() (clearCount int) {
ch := g.Reader.Input()
timeUp := time.After(g.Time * time.Second)
t := time.Now().UnixNano()
rand.Seed(t)
L:
for {
i := rand.Intn(len(g.Words))
selectWord := g.Words[i]
g.Writer.Output(selectWord)
select {
case text := <-ch:
if selectWord == text {
clearCount++
g.Writer.Output("OK")
} else {
g.Writer.Output("NG")
}
case <-timeUp:
g.Writer.Output("========")
g.Writer.Output("time up")
g.Writer.Output(fmt.Sprintf("clear count %d", clearCount))
break L
}
}
return
}