Skip to content
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

Kadai3-1 waytkheming #39

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
16 changes: 16 additions & 0 deletions kadai3-1/waytkheming/.gitignore
Original file line number Diff line number Diff line change
@@ -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


25 changes: 25 additions & 0 deletions kadai3-1/waytkheming/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

# 【TRY】タイピングゲームを作ろう
## ルール
* 標準出力に英単語を出す(出すものは自由)
* 標準入力から1行受け取る
* 制限時間内に何問解けたか表示する

## ヒント
* 制限時間にはtime.After関数を用いる
* context.WithTimeoutでもよい
* select構文を用いる
* 制限時間と入力を同時に待つ

## 使い方
```bash
go run main.go
```


## オプション
制限時間(秒)を指定可能
```bash
go run main.go -t 20
```

69 changes: 69 additions & 0 deletions kadai3-1/waytkheming/main.go
Original file line number Diff line number Diff line change
@@ -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
}