-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.go
69 lines (57 loc) · 1.07 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
package main
import (
"bufio"
"context"
"flag"
"fmt"
"io"
"math/rand"
"os"
"time"
)
func main() {
fmt.Println("TYPE THE WORD!")
questions := []string{"osaka", "tokyo", "mie", "aichi", "fukuoka", "nagano", "chiba", "shizuoka", "yamanashi"}
var score = 0
t := flag.Int("t", 10, "time limit")
flag.Parse()
bc := context.Background()
limit := time.Duration(*t) * time.Second
ctx, cancel := context.WithTimeout(bc, limit)
defer cancel()
ch := input(ctx, os.Stdout)
LOOP:
for {
question := questions[rand.Intn(len(questions))]
fmt.Println(question)
select {
case <-ctx.Done():
fmt.Println("finish!!!")
break LOOP
default:
answer := <-ch
if answer == question {
fmt.Println("correct!!")
score++
} else {
fmt.Println("wrong!!")
}
}
}
fmt.Printf("your score is %v\n", score)
}
func input(ctx context.Context, r io.Reader) <-chan string {
ch := make(chan string)
go func() {
s := bufio.NewScanner(r)
for s.Scan() {
select {
case <-ctx.Done():
close(ch)
return
case ch <- s.Text():
}
}
}()
return ch
}