Add a simple command line interface
authorW. Trevor King <wking@tremily.us>
Tue, 5 Feb 2013 14:06:44 +0000 (09:06 -0500)
committerW. Trevor King <wking@tremily.us>
Tue, 5 Feb 2013 14:06:44 +0000 (09:06 -0500)
quizzer/cli.py
quizzer/ui/__init__.py [new file with mode: 0644]
quizzer/ui/cli.py [new file with mode: 0644]

index 8648e25b2c1a9c354944558c7ed2a978e82e80bc..9eab5d0af3c5128ae03df3fe09fd2c7152c4e5a0 100644 (file)
@@ -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 (file)
index 0000000..afb0726
--- /dev/null
@@ -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 (file)
index 0000000..ed40862
--- /dev/null
@@ -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')