diff --git a/kadai3-1/waytkheming/.gitignore b/kadai3-1/waytkheming/.gitignore new file mode 100644 index 0000000..8943a9a --- /dev/null +++ b/kadai3-1/waytkheming/.gitignore @@ -0,0 +1,16 @@ +### https://raw.github.com/github/gitignore/d2c1bb2b9c72ead618c9f6a48280ebc7a8e0dff6/Go.gitignore + +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + + diff --git a/kadai3-1/waytkheming/README.md b/kadai3-1/waytkheming/README.md new file mode 100644 index 0000000..5b2aade --- /dev/null +++ b/kadai3-1/waytkheming/README.md @@ -0,0 +1,25 @@ + +# 【TRY】タイピングゲームを作ろう +## ルール +* 標準出力に英単語を出す(出すものは自由) +* 標準入力から1行受け取る +* 制限時間内に何問解けたか表示する + +## ヒント +* 制限時間にはtime.After関数を用いる + * context.WithTimeoutでもよい +* select構文を用いる + * 制限時間と入力を同時に待つ + +## 使い方 +```bash +go run main.go +``` + + +## オプション +制限時間(秒)を指定可能 +```bash +go run main.go -t 20 +``` + diff --git a/kadai3-1/waytkheming/main.go b/kadai3-1/waytkheming/main.go new file mode 100644 index 0000000..df3a373 --- /dev/null +++ b/kadai3-1/waytkheming/main.go @@ -0,0 +1,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 +}