Amazing-Python-Scripts
72 строки · 2.6 Кб
1import random
2import time
3
4# Dictionary containing Python code snippets and their expected outputs
5code_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
15difficulty_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
22def get_random_code_snippet(difficulty):
23"""Return a random Python code snippet based on the selected difficulty."""
24return random.choice(difficulty_levels[difficulty])
25
26
27def main():
28print("Welcome to the Coding Language Learning Game!")
29difficulty = input("Select difficulty (easy, medium, hard): ").lower()
30
31# Initialize game settings
32lives = 3
33score = 0
34time_limit = 45 # Time limit in seconds for each code snippet
35
36while True:
37code_snippet = get_random_code_snippet(difficulty)
38expected_output = code_snippets[code_snippet]
39
40print("\nCode Snippet:")
41print(code_snippet)
42
43start_time = time.time()
44user_guess = input("Your Guess: ")
45
46elapsed_time = time.time() - start_time
47if elapsed_time > time_limit:
48print(f"Time's up! The correct output was: {expected_output}")
49lives -= 1
50elif user_guess == expected_output:
51print("Correct! You earned 10 points.")
52score += 10
53else:
54print(f"Oops! The correct output was: {expected_output}")
55lives -= 1
56
57if lives == 0:
58print("Game Over! You've run out of lives.")
59break
60
61print(f"Lives remaining: {lives}")
62print(f"Your current score: {score}")
63
64play_again = input("Do you want to play again? (y/n): ")
65if play_again.lower() != "y":
66break
67
68print(f"Your final score: {score}")
69
70
71if __name__ == "__main__":
72main()
73