|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "os" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/gopherdojo/dojo6/kadai3/en-ken/typing" |
| 11 | +) |
| 12 | + |
| 13 | +func main() { |
| 14 | + const timeoutSec = 10 |
| 15 | + textDict := []string{"foo", "bar", "baz", "qux"} |
| 16 | + t := typing.NewTyping(textDict) |
| 17 | + |
| 18 | + chInput := inputRoutine(os.Stdin) |
| 19 | + chFinish := time.After(time.Duration(timeoutSec) * time.Second) |
| 20 | + |
| 21 | + execute(chInput, chFinish, os.Stdout, t) |
| 22 | +} |
| 23 | + |
| 24 | +// Typing is interface to typing.Typing |
| 25 | +type Typing interface { |
| 26 | + GetNextText() string |
| 27 | + IsCorrect(input string) bool |
| 28 | +} |
| 29 | + |
| 30 | +func execute(chInput <-chan string, chFinish <-chan time.Time, stdout *os.File, t Typing) { |
| 31 | + |
| 32 | + score := 0 |
| 33 | + for i := 1; ; i++ { |
| 34 | + fmt.Fprintf(stdout, "[%03d]: %v\n", i, t.GetNextText()) |
| 35 | + fmt.Fprint(stdout, "type>>") |
| 36 | + select { |
| 37 | + case text := <-chInput: |
| 38 | + if t.IsCorrect(text) { |
| 39 | + score++ |
| 40 | + fmt.Fprintln(stdout, "Correct!") |
| 41 | + } else { |
| 42 | + fmt.Fprintln(stdout, "Correct!") |
| 43 | + } |
| 44 | + case <-chFinish: |
| 45 | + fmt.Fprintln(stdout, "\nTime's up!!") |
| 46 | + fmt.Fprintf(stdout, "You Scored: %v\n", score) |
| 47 | + return |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +func inputRoutine(r io.Reader) <-chan string { |
| 53 | + ch := make(chan string) |
| 54 | + |
| 55 | + go func() { |
| 56 | + s := bufio.NewScanner(r) |
| 57 | + for s.Scan() { |
| 58 | + ch <- s.Text() |
| 59 | + } |
| 60 | + }() |
| 61 | + |
| 62 | + return ch |
| 63 | +} |
0 commit comments