Skip to content

Kadai3-1 miyahara #51

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions kadai3-1/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.idea/
.DS_Store
61 changes: 61 additions & 0 deletions kadai3-1/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package main

import (
"os"
"fmt"
"io"
"bufio"
"context"
"time"
"math/rand"
)

var gameString = []string{"apple","banana","peach","strawberry","cherry","watermelon","pineapple","grape"}
var totalGame = 0
var totalScore = 0

func main(){
bc := context.Background()
t := 30*time.Second
ctx,cancel := context.WithTimeout(bc,t)
defer cancel()

ch := input(os.Stdin,ctx)
LOOP:
for{
fmt.Println(">")
n := rand.Intn(len(gameString))
randString := gameString[n]
totalGame ++
fmt.Println(randString)
select {
case <-ctx.Done():
fmt.Println("time up")
break LOOP
default:
typedString := <-ch
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

defaultの中にこの処理を書いてしまうと、ユーザの入力があるまでここでブロックしてしまいます
その場合、 ctx.Done() を待つことができないため、制限時間を超えてもユーザが入力を終えるまではゲームが終わらず、制限時間後の最後の入力も成否を判定する対象になってしまうため、同時に待てるようにしたほうが良いと思います

if randString == typedString{
fmt.Println("ok")
totalScore ++
}
}
}
fmt.Printf("total score %d/%d",totalScore,totalGame)

}

func input(r io.Reader,ctx context.Context) <-chan string{
ch := make(chan string)
go func() {
s := bufio.NewScanner(r)
for s.Scan(){
select{
case <- ctx.Done():
close(ch)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

これではcontextがcancelされなかった場合にcloseされないことになりますので(問題はないと思いますが)、閉じるのであれば、このfuncの最初に defer close(ch) しておいたほうが良いと思います

return
case ch <- s.Text():
}
}
}()
return ch
}