Skip to content

Commit 7ffa85e

Browse files
committed
add main.go
1 parent ae9505d commit 7ffa85e

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

kadai3-1/main.go

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package main
2+
3+
import (
4+
"os"
5+
"fmt"
6+
"io"
7+
"bufio"
8+
"context"
9+
"time"
10+
"math/rand"
11+
)
12+
13+
var gameString = []string{"apple","banana","peach","strawberry","cherry","watermelon","pineapple","grape"}
14+
var totalGame = 0
15+
var totalScore = 0
16+
17+
func main(){
18+
bc := context.Background()
19+
t := 30*time.Second
20+
ctx,cancel := context.WithTimeout(bc,t)
21+
defer cancel()
22+
23+
ch := input(os.Stdin,ctx)
24+
LOOP:
25+
for{
26+
fmt.Println(">")
27+
n := rand.Intn(len(gameString))
28+
randString := gameString[n]
29+
totalGame ++
30+
fmt.Println(randString)
31+
select {
32+
case <-ctx.Done():
33+
fmt.Println("time up")
34+
break LOOP
35+
default:
36+
typedString := <-ch
37+
if randString == typedString{
38+
fmt.Println("ok")
39+
totalScore ++
40+
}
41+
}
42+
}
43+
fmt.Printf("total score %d/%d",totalScore,totalGame)
44+
45+
}
46+
47+
func input(r io.Reader,ctx context.Context) <-chan string{
48+
ch := make(chan string)
49+
go func() {
50+
s := bufio.NewScanner(r)
51+
for s.Scan(){
52+
select{
53+
case <- ctx.Done():
54+
close(ch)
55+
return
56+
case ch <- s.Text():
57+
}
58+
}
59+
}()
60+
return ch
61+
}

0 commit comments

Comments
 (0)