Skip to content

Commit b385b35

Browse files
committed
Enable to play the game
1 parent 8039b12 commit b385b35

File tree

2 files changed

+50
-3
lines changed

2 files changed

+50
-3
lines changed

kadai3-1/lfcd85/typinggame/typinggame.go

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
package typinggame
22

33
import (
4+
"bufio"
5+
"context"
46
"fmt"
7+
"io"
8+
"math/rand"
9+
"os"
510
"time"
611
)
712

@@ -13,7 +18,49 @@ type Game struct {
1318
}
1419

1520
func Execute(g Game) error {
16-
fmt.Println(g.Words)
17-
fmt.Println(g.TimeLimit)
21+
g.run(os.Stdin, os.Stdout)
1822
return nil
1923
}
24+
25+
func (g *Game) run(r io.Reader, w io.Writer) {
26+
ch := input(r)
27+
bc := context.Background()
28+
ctx, cancel := context.WithTimeout(bc, g.TimeLimit)
29+
defer cancel()
30+
31+
fmt.Fprintln(w, "Let's type the standard package names! (Time limit:", g.TimeLimit, ")")
32+
33+
var score int
34+
rand.Seed(time.Now().UnixNano())
35+
word := g.Words[rand.Intn(len(g.Words))]
36+
LOOP:
37+
for {
38+
fmt.Fprintln(w, ">", word)
39+
select {
40+
case input := <-ch:
41+
if input == word {
42+
score++
43+
fmt.Fprintln(w, "ok! current score:", score)
44+
word = g.Words[rand.Intn(len(g.Words))]
45+
} else {
46+
fmt.Fprintln(w, "ng")
47+
}
48+
case <-ctx.Done():
49+
fmt.Fprintln(w)
50+
fmt.Fprintln(w, g.TimeLimit, "has passed: you correctly typed", score, "packages!")
51+
break LOOP
52+
}
53+
}
54+
}
55+
56+
func input(r io.Reader) <-chan string {
57+
ch := make(chan string)
58+
59+
go func() {
60+
s := bufio.NewScanner(r)
61+
for s.Scan() {
62+
ch <- s.Text()
63+
}
64+
}()
65+
return ch
66+
}

kadai3-1/lfcd85/typinggame/typinggame_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010
func TestExecute(t *testing.T) {
1111
g := typinggame.Game{
1212
typinggame.Words{"hoge", "fuga", "piyo"},
13-
30 * time.Second,
13+
1 * time.Second,
1414
}
1515

1616
if err := typinggame.Execute(g); err != nil {

0 commit comments

Comments
 (0)