-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
84 lines (73 loc) · 1.62 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"bufio"
"flag"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
type problem struct {
value1 int
value2 int
answer int
}
func (p *problem) new() {
p.value1 = rand.Intn(10)
p.value2 = rand.Intn(10)
p.answer = p.value1 * p.value2
}
func makeAnswer(input []byte) int {
str := string(input)
retVal, err := strconv.Atoi(strings.Trim(str, "\n"))
if err != nil {
fmt.Println(err)
}
return retVal
}
func showResults(results map[string]int) {
answered := results["correct"] + results["incorrect"]
fmt.Println("You answered", answered, "Questions")
fmt.Println("you got", results["correct"], "answers right")
fmt.Println("you got", results["incorrect"], "answers wrong")
}
func main() {
rand.Seed(time.Now().UTC().UnixNano())
testLength := flag.Int("l", 60, "How long the test lasts in seconds")
// Once all flags are declared, call `flag.Parse()`
// to execute the command-line parsing.
flag.Parse()
// create channel for ending main game loop after timer
done := make(chan bool, 1)
// create and start timer
timer := time.NewTimer(time.Second * time.Duration(*testLength))
go func(done chan bool) {
<-timer.C
done <- true
}(done)
results := make(map[string]int)
// main game loop
loop:
for {
select {
case _ = <-done:
fmt.Println("Times up!")
showResults(results)
break loop
default:
p := problem{}
p.new()
buf := bufio.NewReader(os.Stdin)
fmt.Printf("%d %s %d %s", p.value1, "*", p.value2, "= ")
input, _ := buf.ReadBytes('\n')
if p.answer == makeAnswer(input) {
results["correct"]++
} else {
results["incorrect"]++
}
}
}
os.Exit(0)
}