|
| 1 | +import random |
| 2 | +import time |
| 3 | + |
| 4 | +# Dictionary containing Python code snippets and their expected outputs |
| 5 | +code_snippets = { |
| 6 | + "print('Hello, world!')": "Hello, world!", |
| 7 | + "print(2 + 3)": "5", |
| 8 | + "print('Python' + ' is ' + 'fun')": "Python is fun", |
| 9 | + "numbers = [1, 2, 3, 4, 5]\nprint(numbers)": "[1, 2, 3, 4, 5]", |
| 10 | + "num1 = 10\nnum2 = 5\nprint(num1 * num2)": "50", |
| 11 | + "def fibonacci(n):\n if n <= 0:\n return 'Invalid input'\n elif n == 1:\n return 0\n elif n == 2:\n return 1\n else:\n return fibonacci(n-1) + fibonacci(n-2)\nprint(fibonacci(6))": "5", |
| 12 | +} |
| 13 | + |
| 14 | +# Difficulty levels with corresponding sets of code snippets |
| 15 | +difficulty_levels = { |
| 16 | + "easy": ["print('Hello, world!')", "print(2 + 3)"], |
| 17 | + "medium": ["print('Python' + ' is ' + 'fun')", "numbers = [1, 2, 3, 4, 5]\nprint(numbers)"], |
| 18 | + "hard": ["num1 = 10\nnum2 = 5\nprint(num1 * num2)", "def fibonacci(n):\n if n <= 0:\n return 'Invalid input'\n elif n == 1:\n return 0\n elif n == 2:\n return 1\n else:\n return fibonacci(n-1) + fibonacci(n-2)\nprint(fibonacci(6))"] |
| 19 | +} |
| 20 | + |
| 21 | +def get_random_code_snippet(difficulty): |
| 22 | + """Return a random Python code snippet based on the selected difficulty.""" |
| 23 | + return random.choice(difficulty_levels[difficulty]) |
| 24 | + |
| 25 | +def main(): |
| 26 | + print("Welcome to the Coding Language Learning Game!") |
| 27 | + difficulty = input("Select difficulty (easy, medium, hard): ").lower() |
| 28 | + |
| 29 | + # Initialize game settings |
| 30 | + lives = 3 |
| 31 | + score = 0 |
| 32 | + time_limit = 45 # Time limit in seconds for each code snippet |
| 33 | + |
| 34 | + while True: |
| 35 | + code_snippet = get_random_code_snippet(difficulty) |
| 36 | + expected_output = code_snippets[code_snippet] |
| 37 | + |
| 38 | + print("\nCode Snippet:") |
| 39 | + print(code_snippet) |
| 40 | + |
| 41 | + start_time = time.time() |
| 42 | + user_guess = input("Your Guess: ") |
| 43 | + |
| 44 | + elapsed_time = time.time() - start_time |
| 45 | + if elapsed_time > time_limit: |
| 46 | + print(f"Time's up! The correct output was: {expected_output}") |
| 47 | + lives -= 1 |
| 48 | + elif user_guess == expected_output: |
| 49 | + print("Correct! You earned 10 points.") |
| 50 | + score += 10 |
| 51 | + else: |
| 52 | + print(f"Oops! The correct output was: {expected_output}") |
| 53 | + lives -= 1 |
| 54 | + |
| 55 | + if lives == 0: |
| 56 | + print("Game Over! You've run out of lives.") |
| 57 | + break |
| 58 | + |
| 59 | + print(f"Lives remaining: {lives}") |
| 60 | + print(f"Your current score: {score}") |
| 61 | + |
| 62 | + play_again = input("Do you want to play again? (y/n): ") |
| 63 | + if play_again.lower() != "y": |
| 64 | + break |
| 65 | + |
| 66 | + print(f"Your final score: {score}") |
| 67 | + |
| 68 | +if __name__ == "__main__": |
| 69 | + main() |
0 commit comments