generated from gopherdojo/template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
105 lines (91 loc) · 1.8 KB
/
main.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"bufio"
"fmt"
"io"
"math/rand"
"os"
"time"
)
const (
ExitCodeOK = 0
ExitCodeError = 1
timelimit = 10
filePath = "words.txt"
)
func main() {
rand.Seed(time.Now().UnixNano())
exitCode := run()
os.Exit(exitCode)
}
func run() int {
in, errc := input(os.Stdin)
timelimit := time.After(timelimit * time.Second)
words, err := importWords(filePath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return ExitCodeError
}
typing := newTyping(words)
for {
fmt.Println(typing.word)
fmt.Print(">")
select {
case word := <-in:
if typing.check(word) {
fmt.Println("Good!")
fmt.Println()
} else {
fmt.Println("Bad..")
fmt.Println()
}
typing.shuffle()
case err := <-errc:
fmt.Println()
fmt.Fprintln(os.Stderr, err)
return ExitCodeError
case <-timelimit:
fmt.Println()
fmt.Println("------")
fmt.Println("Finish!!")
fmt.Printf("Result: %d points\n", typing.getPoint())
return ExitCodeOK
}
}
}
func input(r io.Reader) (<-chan string, <-chan error) {
// チャネルを作る
result := make(chan string)
errc := make(chan error)
go func() {
s := bufio.NewScanner(r)
for s.Scan() {
// チャネルに読み込んだ文字列を送る
result <- s.Text()
}
if err := s.Err(); err != nil {
errc <- err
}
// チャネルを閉じる
close(result)
}()
// チャネルを返す
return result, errc
}
// cf. https://qiita.com/jpshadowapps/items/ae7274ec0d40882d76b5
func importWords(filePath string) ([]string, error) {
f, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer f.Close()
lines := make([]string, 0, 10)
scanner := bufio.NewScanner(f)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
if serr := scanner.Err(); serr != nil {
return nil, err
}
return lines, nil
}