From c18db2f236d3a636ac0141d3b19803689f2408ce Mon Sep 17 00:00:00 2001 From: "W. Trevor King" Date: Tue, 5 Feb 2013 09:06:44 -0500 Subject: [PATCH] Add a simple command line interface --- quizzer/cli.py | 5 +++-- quizzer/ui/__init__.py | 23 +++++++++++++++++++++++ quizzer/ui/cli.py | 26 ++++++++++++++++++++++++++ 3 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 quizzer/ui/__init__.py create mode 100644 quizzer/ui/cli.py diff --git a/quizzer/cli.py b/quizzer/cli.py index 8648e25..9eab5d0 100644 --- a/quizzer/cli.py +++ b/quizzer/cli.py @@ -4,6 +4,7 @@ import locale as _locale from . import __doc__ as _module_doc from . import __version__ from . import quiz as _quiz +from .ui import cli as _cli def main(): @@ -21,5 +22,5 @@ def main(): quiz = _quiz.Quiz(path=args.quiz, encoding=encoding) quiz.load() - for question in quiz: - print(question) + ui = _cli.CommandLineInterface(quiz=quiz) + ui.run() diff --git a/quizzer/ui/__init__.py b/quizzer/ui/__init__.py new file mode 100644 index 0000000..afb0726 --- /dev/null +++ b/quizzer/ui/__init__.py @@ -0,0 +1,23 @@ +class UserInterface (object): + "Give a quiz over a generic user interface" + def __init__(self, quiz=None, answers=None): + self.quiz = quiz + if answers is None: + answers = {} + self.answers = answers + + def run(self): + raise NotImplementedError() + + def get_question(self): + return self.quiz[0] + + def process_answer(self, question, answer): + if question not in self.answers: + self.answers[question] = [] + correct = question.check(answer) + self.answers[question].append({ + 'answer': answer, + 'correct': correct, + }) + return correct diff --git a/quizzer/ui/cli.py b/quizzer/ui/cli.py new file mode 100644 index 0000000..ed40862 --- /dev/null +++ b/quizzer/ui/cli.py @@ -0,0 +1,26 @@ +from . import UserInterface + + +class CommandLineInterface (UserInterface): + def run(self): + while True: + question = self.get_question() + if not question: + break + print(question.prompt) + while True: + answer = input('? ') + a = answer.strip().lower() + if a in ['q', 'quit']: + return + if a in ['?', 'help']: + print() + print(question.prompt) + print(question.hint) + continue + break + correct = self.process_answer(question=question, answer=answer) + if correct: + print('correct\n') + else: + print('incorrect\n') -- 2.26.2