|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "encoding/csv" |
| 6 | + "flag" |
| 7 | + "fmt" |
| 8 | + "math/rand" |
| 9 | + "os" |
| 10 | + "strings" |
| 11 | + "time" |
| 12 | +) |
| 13 | + |
| 14 | +func main() { |
| 15 | + csvFilename := flag.String("f", "problems.csv", "csv file with 2 columns, question & answer") |
| 16 | + timeLimit := flag.Int("t", 30, "the time limit for the quiz in seconds") |
| 17 | + hasShuffle := flag.Bool("s", false, "randomize question order") |
| 18 | + flag.Parse() |
| 19 | + |
| 20 | + correctCount := 0 |
| 21 | + reader := bufio.NewReader(os.Stdin) |
| 22 | + |
| 23 | + fmt.Println("Press enter to start the quiz") |
| 24 | + reader.ReadBytes('\n') |
| 25 | + |
| 26 | + b, fileErr := os.Open(*csvFilename) |
| 27 | + if fileErr != nil { |
| 28 | + fmt.Print(fileErr, "\nFailed to read the CSV file provided") |
| 29 | + os.Exit(1) |
| 30 | + } |
| 31 | + |
| 32 | + r := csv.NewReader(b) |
| 33 | + records, csvErr := r.ReadAll() |
| 34 | + |
| 35 | + if csvErr != nil { |
| 36 | + fmt.Print(csvErr, "\nFailed to parse the CSV file provided") |
| 37 | + os.Exit(1) |
| 38 | + } |
| 39 | + |
| 40 | + timeout := time.NewTimer(time.Duration(*timeLimit) * time.Second) |
| 41 | + |
| 42 | + ansCh := make(chan string) |
| 43 | + getUserInput := func() { |
| 44 | + userAns, _ := reader.ReadString('\n') |
| 45 | + ansCh <- strings.TrimSpace(strings.ToLower(userAns)) |
| 46 | + } |
| 47 | + |
| 48 | + if *hasShuffle { |
| 49 | + rand.Shuffle(len(records), func(i, j int) { |
| 50 | + records[i], records[j] = records[j], records[i] |
| 51 | + }) |
| 52 | + } |
| 53 | + |
| 54 | +qLoop: |
| 55 | + for i, record := range records { |
| 56 | + fmt.Printf("Question %d:\t%s\t", i+1, record[0]) |
| 57 | + go getUserInput() |
| 58 | + |
| 59 | + select { |
| 60 | + case <-timeout.C: |
| 61 | + fmt.Println("\nToo slow!") |
| 62 | + break qLoop |
| 63 | + case ans := <-ansCh: |
| 64 | + if ans == record[1] { |
| 65 | + correctCount++ |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + fmt.Printf("You scored %d out of %d!\n", correctCount, len(records)) |
| 71 | +} |
0 commit comments