Project 1 ยท Week 1

Interactive Terminal Game / Quiz Engine

~45 min ยท Learn + build + verify

1. Project Overview & Architecture

Welcome to Major Project 1: Interactive Terminal Game / Quiz Engine! You have reached your first major milestone in Python. Up to this point, you have mastered variables, input/output, conditional logic, loops, custom functions, data structures, and input validation. Now, it's time to pull all these concepts together into a cohesive, production-grade terminal application.

Project Core Objectives

  • State Management: Track total score, high score, and consecutive correct answer streaks.
  • Modular Functions: Organize application responsibilities into dedicated functions (menu display, question prompt, score calculation).
  • Input Validation Loop: Ensure the user cannot crash the program by typing invalid options or empty strings.
  • Control Flow: Implement interactive menu loops using while loops and structural pattern matching (match-case) or if-elif-else branches.

2. Functional Requirements & Feature Specifications

Your Quiz Engine must implement the following four mandatory feature modules:

Feature Module Functional Specification Python Mechanism
Question Bank Stores questions, options (A-D), and correct answers. List of Dictionaries containing key-value pairs.
Robust Validation Re-prompts user until a valid choice (A, B, C, D) is supplied. while True loop with .strip().upper().
Streak Multiplier Consecutive correct answers increase point yields (e.g., +10, +20, +30). Streak counter integer tracking correct answers.
Persistent High Score Maintains the top score achieved during the session across replays. Main outer loop with high-score state tracking.

3. Complete Reference Implementation

Review the full Python reference implementation below to understand how the components fit together into a modular architecture:

import random

# Question Bank Data Structure
QUESTION_BANK = [
    {
        "question": "What is the correct file extension for Python scripts?",
        "options": ["A) .pyt", "B) .pt", "C) .py", "D) .python"],
        "answer": "C"
    },
    {
        "question": "Which keyword is used to define a custom function in Python?",
        "options": ["A) function", "B) def", "C) fun", "D) create"],
        "answer": "B"
    },
    {
        "question": "What data type is returned by the standard input() function?",
        "options": ["A) Integer", "B) Float", "C) String", "D) Boolean"],
        "answer": "C"
    },
    {
        "question": "Which operator is used for integer floor division?",
        "options": ["A) /", "B) //", "C) %", "D) **"],
        "answer": "B"
    }
]

def display_banner():
    print("=" * 45)
    print("      ๐ŸŽฎ PYTHON TERMINAL QUIZ ENGINE ๐ŸŽฎ     ")
    print("=" * 45)

def get_validated_choice():
    """Loops until the user enters a valid choice: A, B, C, or D."""
    valid_answers = {"A", "B", "C", "D"}
    while True:
        user_choice = input("\nYour answer (A/B/C/D): ").strip().upper()
        if user_choice in valid_answers:
            return user_choice
        print("โš ๏ธ Invalid input! Please enter A, B, C, or D.")

def run_quiz_round():
    """Executes a single round of the quiz and returns total points earned."""
    print("\nStarting a new round! Answer correctly to build your point streak.\n")
    score = 0
    streak = 0
    
    # Shuffle questions to keep replay value high
    questions = QUESTION_BANK.copy()
    random.shuffle(questions)

    for idx, q in enumerate(questions, start=1):
        print(f"--- Question {idx} of {len(questions)} ---")
        print(q["question"])
        for option in q["options"]:
            print(f"  {option}")
        
        user_answer = get_validated_choice()
        
        if user_answer == q["answer"]:
            streak += 1
            points = 10 * streak
            score += points
            print(f"โœ… Correct! Streak: {streak}x | Earned +{points} pts")
        else:
            streak = 0
            print(f"โŒ Incorrect. The correct answer was {q['answer']}. Streak reset!")
        print()

    print("=" * 45)
    print(f"๐ŸŽ‰ Round Completed! Final Score: {score} pts")
    print("=" * 45)
    return score

def main():
    """Main CLI driver and state controller."""
    display_banner()
    high_score = 0

    while True:
        print("\nMAIN MENU:")
        print("1) Start Quiz Game")
        print("2) View Session High Score")
        print("3) Exit Game")

        choice = input("\nSelect an option (1-3): ").strip()

        match choice:
            case "1":
                current_score = run_quiz_round()
                if current_score > high_score:
                    high_score = current_score
                    print(f"๐Ÿ† NEW HIGH SCORE RECORD: {high_score} pts!")
            case "2":
                print(f"\n๐Ÿ† Current Session High Score: {high_score} pts")
            case "3":
                print("\nThanks for playing! Keep practicing Python!")
                break
            case _:
                print("โš ๏ธ Invalid selection. Please choose 1, 2, or 3.")

if __name__ == "__main__":
    main()

4. Common Project Pitfalls

โš ๏ธ Project Watchlist:

  • Mutating the Original Question List: Using random.shuffle(QUESTION_BANK) directly modifies the global list permanently. Always copy it first using QUESTION_BANK.copy().
  • Unbounded Input Loops: Ensure that every validation loop has a clear exit pathway when valid input is supplied.
  • Global Variable Scope Contamination: Avoid modifying global state variables inside nested functions without passing them explicitly as return values or parameters.

5. Interactive Project Workspace

Project Workspace

Build & Test: Quiz Engine

Use the code editor below to customize or build your own quiz engine. Try adding a custom difficulty system or additional questions to the question bank!

0% complete
Project Feature Checklist

6. Key Takeaways & Milestone Achievement

  • Structuring code into modular functions keeps applications maintainable and readable.
  • Input validation loops protect programs against crashing due to unexpected user interaction.
  • In-memory state management enables rich user features like high scores and streak multipliers.

๐Ÿ† Milestone 1 Complete

Congratulations on completing Major Project 1! Up next: **Major Project 2: File-Backed Expense & Task Tracker** where you will learn to add permanent disk storage to your programs!