Amazing-Python-Scripts

Форк
0
/
coding_language_learning_game.py 
72 строки · 2.6 Кб
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

22
def get_random_code_snippet(difficulty):
23
    """Return a random Python code snippet based on the selected difficulty."""
24
    return random.choice(difficulty_levels[difficulty])
25

26

27
def main():
28
    print("Welcome to the Coding Language Learning Game!")
29
    difficulty = input("Select difficulty (easy, medium, hard): ").lower()
30

31
    # Initialize game settings
32
    lives = 3
33
    score = 0
34
    time_limit = 45  # Time limit in seconds for each code snippet
35

36
    while True:
37
        code_snippet = get_random_code_snippet(difficulty)
38
        expected_output = code_snippets[code_snippet]
39

40
        print("\nCode Snippet:")
41
        print(code_snippet)
42

43
        start_time = time.time()
44
        user_guess = input("Your Guess: ")
45

46
        elapsed_time = time.time() - start_time
47
        if elapsed_time > time_limit:
48
            print(f"Time's up! The correct output was: {expected_output}")
49
            lives -= 1
50
        elif user_guess == expected_output:
51
            print("Correct! You earned 10 points.")
52
            score += 10
53
        else:
54
            print(f"Oops! The correct output was: {expected_output}")
55
            lives -= 1
56

57
        if lives == 0:
58
            print("Game Over! You've run out of lives.")
59
            break
60

61
        print(f"Lives remaining: {lives}")
62
        print(f"Your current score: {score}")
63

64
        play_again = input("Do you want to play again? (y/n): ")
65
        if play_again.lower() != "y":
66
            break
67

68
    print(f"Your final score: {score}")
69

70

71
if __name__ == "__main__":
72
    main()
73

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.