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 sminamot #42

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
7 changes: 7 additions & 0 deletions kadai3-1/sminamot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# タイピングゲームの作成

## Usage
```
$ go build -o main
$ ./main
```
72 changes: 72 additions & 0 deletions kadai3-1/sminamot/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package main

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

var qs = []string{
"hoge",
"fuga",
"foo",
"bar",
"piyo",
}

func main() {
tCh := limit(10 * time.Second)
iCh := input(os.Stdin)
rand.Seed(time.Now().UnixNano())
aNum := 0
Copy link

Choose a reason for hiding this comment

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

zero valueがそのまま利用できるようであれば、 var aNum, qNum int などで宣言しても良いと思います

qNum := 0
loop:
for {
q := getQuestion()
fmt.Printf("[q: %s]\n", q)
fmt.Print("> ")
select {
case m := <-iCh:
qNum++
if m == q {
aNum++
fmt.Print("matched!")
} else {
fmt.Print("unmatched!")
}
fmt.Printf(" (%d/%d)\n", aNum, qNum)
case <-tCh:
break loop
}
}
fmt.Println()
fmt.Printf("your score: %d\n", aNum)
}

func getQuestion() string {
return qs[rand.Intn(len(qs))]
}

func input(r io.Reader) <-chan string {
ch := make(chan string)
go func() {
s := bufio.NewScanner(r)
for s.Scan() {
ch <- s.Text()
}
close(ch)
}()
return ch
}

func limit(d time.Duration) <-chan struct{} {
Copy link

Choose a reason for hiding this comment

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

time.After を直接利用するだけでも十分かと思いました

ch := make(chan struct{})
go func() {
defer close(ch)
<-time.After(d)
}()
return ch
}