Add Question.multiline and associated handling
[quizzer.git] / quizzer / ui / cli.py
1 try:
2     import readline as _readline
3 except ImportError as _readline_import_error:
4     _readline = None
5
6 from . import UserInterface
7
8
9 class CommandLineInterface (UserInterface):
10     def run(self):
11         while True:
12             question = self.get_question()
13             if not question:
14                 break
15             print(question.prompt)
16             if question.multiline:
17                 answers = []
18             while True:
19                 try:
20                     answer = input('? ')
21                 except EOFError:
22                     answer = 'quit'
23                 a = answer.strip().lower()
24                 if a in ['q', 'quit']:
25                     print()
26                     return
27                 if a in ['?', 'help']:
28                     print()
29                     print(question.prompt)
30                     print(question.help)
31                     continue
32                 if question.multiline:
33                     answers.append(answer)
34                     if not a:
35                         break
36                 else:
37                     break
38             if question.multiline:
39                 answer = answers
40             correct = self.process_answer(question=question, answer=answer)
41             if correct:
42                 print('correct\n')
43             else:
44                 print('incorrect\n')
45
46     def display_results(self):
47         print('results:')
48         for question in self.quiz:
49             if question.id in self.answers:
50                 self.display_result(question=question)
51                 print()
52         self.display_totals()
53
54     def display_result(self, question):
55         answers = self.answers.get(question.id, [])
56         print('question:     {}'.format(question.prompt))
57         la = len(answers)
58         lc = len([a for a in answers if a['correct']])
59         print('answers: {}/{} ({:.2f})'.format(lc, la, float(lc)/la))
60         for answer in answers:
61             if answer['correct']:
62                 correct = 'correct'
63             else:
64                 correct = 'incorrect'
65             print('  you answered: {}'.format(answer['answer']))
66             print('     which was: {}'.format(correct))
67
68     def display_totals(self):
69         answered = self.answers.get_answered(questions=self.quiz)
70         correctly_answered = self.answers.get_correctly_answered(
71             questions=self.quiz)
72         la = len(answered)
73         lc = len(correctly_answered)
74         print('answered {} of {} questions'.format(la, len(self.quiz)))
75         print(('of the answered questions, {} ({:.2f}) were answered correctly'
76                ).format(lc, float(lc)/la))