|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "encoding/csv" |
| 6 | + "flag" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "io/ioutil" |
| 10 | + "log" |
| 11 | + "os" |
| 12 | + "strings" |
| 13 | + "time" |
| 14 | +) |
| 15 | + |
| 16 | +var ( |
| 17 | + file = flag.String("csv", "problems.csv", "a csv file in the format 'question,answer'") |
| 18 | + limit = flag.Int("limit", 30, "the time limit for the quiz in seconds") |
| 19 | +) |
| 20 | + |
| 21 | +func main() { |
| 22 | + flag.Parse() |
| 23 | + |
| 24 | + if *limit < 0 { |
| 25 | + fmt.Println("Error: enter positive time limit") |
| 26 | + os.Exit(1) |
| 27 | + } |
| 28 | + |
| 29 | + records, err := read(*file) |
| 30 | + if err != nil { |
| 31 | + fmt.Println("Error: ", err) |
| 32 | + os.Exit(1) |
| 33 | + } |
| 34 | + |
| 35 | + fmt.Println("Press enter to start. Time limit is", *limit, "seconds") |
| 36 | + in := bufio.NewReader(os.Stdin) |
| 37 | + in.ReadString('\n') |
| 38 | + |
| 39 | + input := make(chan string) |
| 40 | + |
| 41 | + quizdone := make(chan bool) |
| 42 | + timeout := time.NewTicker(time.Duration(*limit) * time.Second) |
| 43 | + |
| 44 | + go getInput(input) |
| 45 | + |
| 46 | + var score int |
| 47 | + var maxscore int |
| 48 | + |
| 49 | + go func() { |
| 50 | + maxscore = len(records) |
| 51 | + for i, v := range records { |
| 52 | + fmt.Print("Problem #", i+1, ": ", v[0], " = ") |
| 53 | + text := <-input |
| 54 | + if text == v[1] { |
| 55 | + score++ |
| 56 | + } |
| 57 | + } |
| 58 | + quizdone <- true |
| 59 | + }() |
| 60 | + |
| 61 | + select { |
| 62 | + case <-quizdone: |
| 63 | + case <-timeout.C: |
| 64 | + fmt.Println("\nThe time is up! Game over!") |
| 65 | + |
| 66 | + } |
| 67 | + |
| 68 | + fmt.Println("You scored", score, "out of", maxscore) |
| 69 | +} |
| 70 | + |
| 71 | +func read(filename string) ([][]string, error) { |
| 72 | + dat, err := ioutil.ReadFile(filename) |
| 73 | + r := csv.NewReader(strings.NewReader(string(dat))) |
| 74 | + if err == nil { |
| 75 | + var records [][]string |
| 76 | + for { |
| 77 | + record, err := r.Read() |
| 78 | + if err == io.EOF { |
| 79 | + break |
| 80 | + } |
| 81 | + if err != nil { |
| 82 | + log.Fatal(err) |
| 83 | + } |
| 84 | + records = append(records, record) |
| 85 | + } |
| 86 | + return records, nil |
| 87 | + } |
| 88 | + return nil, err |
| 89 | +} |
| 90 | + |
| 91 | +func trim(s string) string { |
| 92 | + t := strings.Trim(s, "\n") |
| 93 | + t = strings.Trim(t, " ") |
| 94 | + return t |
| 95 | +} |
| 96 | + |
| 97 | +func getInput(input chan<- string) { |
| 98 | + for { |
| 99 | + in := bufio.NewReader(os.Stdin) |
| 100 | + result, err := in.ReadString('\n') |
| 101 | + if err != nil { |
| 102 | + log.Fatal(err) |
| 103 | + } |
| 104 | + |
| 105 | + result = trim(result) |
| 106 | + input <- result |
| 107 | + } |
| 108 | +} |
0 commit comments