|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/csv" |
| 5 | + "flag" |
| 6 | + "fmt" |
| 7 | + "log" |
| 8 | + "os" |
| 9 | + "time" |
| 10 | +) |
| 11 | + |
| 12 | +type question struct { |
| 13 | + problem string |
| 14 | + result string |
| 15 | +} |
| 16 | + |
| 17 | +type quiz struct { |
| 18 | + questions []question |
| 19 | + score int |
| 20 | +} |
| 21 | + |
| 22 | +func (q *quiz) ask() { |
| 23 | + q.score = 0 |
| 24 | + for _, question := range q.questions { |
| 25 | + fmt.Println(question.problem) |
| 26 | + var answer string |
| 27 | + fmt.Scanln(&answer) |
| 28 | + if answer == question.result { |
| 29 | + q.score++ |
| 30 | + } |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +func readCSV(p string) []question { |
| 35 | + qfile, err := os.Open(p) |
| 36 | + if err != nil { |
| 37 | + log.Fatalf("could not open file: %v\n", err) |
| 38 | + } |
| 39 | + defer qfile.Close() |
| 40 | + csvrd := csv.NewReader(qfile) |
| 41 | + records, err := csvrd.ReadAll() |
| 42 | + if err != nil { |
| 43 | + log.Fatalf("could not parse .csv: %v\n", err) |
| 44 | + } |
| 45 | + var questions []question |
| 46 | + for _, record := range records { |
| 47 | + q := question{problem: record[0], result: record[1]} |
| 48 | + questions = append(questions, q) |
| 49 | + } |
| 50 | + return questions |
| 51 | +} |
| 52 | + |
| 53 | +var ( |
| 54 | + qCSV string |
| 55 | + timeout int |
| 56 | +) |
| 57 | + |
| 58 | +func init() { |
| 59 | + flag.StringVar(&qCSV, "quiz", "", "A .csv file with questions and answers.") |
| 60 | + flag.IntVar(&timeout, "timeout", 30, "The time limit for answering questions.") |
| 61 | + flag.Parse() |
| 62 | +} |
| 63 | + |
| 64 | +func main() { |
| 65 | + if qCSV == "" { |
| 66 | + log.Fatalln("a .csv file must be provided through the -quiz flag") |
| 67 | + } |
| 68 | + questions := readCSV(qCSV) |
| 69 | + qz := quiz{questions: questions, score: 0} |
| 70 | + timeoutCh := time.After(time.Duration(timeout) * time.Second) |
| 71 | + resultCh := make(chan quiz) |
| 72 | + go func() { |
| 73 | + qz.ask() |
| 74 | + resultCh <- qz |
| 75 | + }() |
| 76 | + select { |
| 77 | + case <-resultCh: |
| 78 | + case <-timeoutCh: |
| 79 | + fmt.Println("Timeout!") |
| 80 | + } |
| 81 | + fmt.Println("Score: ", qz.score) |
| 82 | +} |
0 commit comments