Python guessing lantern riddles game code

import random

# 灯谜列表,包含了每个问题和答案的元组
riddles = [("猫头鹰在哪里睡觉?", "a"), ("别人笑我太疯癫,我笑他人看不穿。这是什么?", "a"), 
           ("脱了皮,有了虫,四条腿向前冲。这是什么?", "c"),
           ("白雪公主住在什么地方?", "a"), ("步步生莲,生命长,气息清。这是什么?", "b")]

# 游戏函数
def play_game():
    # 随机选择一道题目
    question, answer = random.choice(riddles)
    # 输出题目
    print(question)
    # 让玩家输入答案
    choice = input("请选择:a, b, 或 c:")
    # 判断答案是否正确
    if choice == answer:
        print("恭喜你,答对了!")
    else:
        print("很遗憾,答错了。正确答案是:", answer)

# 主函数
def main():
    print("欢迎来到猜灯谜游戏!")
    while True:
        # 让玩家选择是否要进入游戏
        choice = input("是否开始游戏?(输入 y 或 n):")
        if choice == "n":
            print("好的,欢迎下次再来!")
            break
        # 开始游戏
        play_game()

if __name__ == "__main__":
    main()

In the above code, we first define a list containing tuples of questions and answers, then  play_game randomly select a question in the function and output it, and let the player input the answer at the same time. Finally, judge whether the answer is correct by comparing the input answer with the correct answer.

In mainthe function, we keep asking the player in a loop if he wants to start the game, and if the answer is n, we exit the game. If the answer is y, call  play_game the function to start the game

Guess you like

Origin blog.csdn.net/m0_57790713/article/details/130490626