You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python乘法游戏开发问题:实现重复答题与随时退出功能

乘法游戏的break/continue语句问题解决

问题描述

我正在开发一款乘法游戏,目前遇到两个与break和continue语句使用相关的问题:

  • 实现同一题目重复出现,直至用户答对;
  • 添加随时退出游戏的选项。

原代码

from numpy import random
random.seed(2020)
def multiply_game():
    while True:
        #randomly choose an int
        int1=random.randint(1,10)
        int2=random.randint(1,10)
        answer=int(int1*int2)
        #feedback
        feedback=['good job', 'excellent', 'awesome', 'great', 'that is cool', 'wonderful',
                    'very good']
        #prompt user to multiple
        prompt=input(f"What is {int1} times {int2}? ")
        #check answer
        if int(prompt)==answer:
            #provide feedback randomly
            print (random.choice(feedback))
            #if right provide new question
            continue
        else:
            print (f'please try again')
            #if wrong provide same question-only works first time
            prompt_again=input(f"What is {int1} times {int2}? ")
    #provide option to quit at any time in the game
    # don't know where to put this
    # quit_prompt=input("would you like to quit the game? ")
    # if quit_prompt=='yes'or 'YES' or 'Y', or 'y':
    #     break

修改后的代码

from numpy import random
random.seed(2020)
def multiply_game():
    while True:
        # 随机生成两个1-9的整数
        int1 = random.randint(1, 10)
        int2 = random.randint(1, 10)
        answer = int1 * int2
        # 反馈语列表
        feedback = ['good job', 'excellent', 'awesome', 'great', 'that is cool', 'wonderful', 'very good']
        
        # 内层循环:重复当前题目直到答对或退出
        while True:
            prompt = input(f"What is {int1} times {int2}? (输入'quit'或'q'可退出游戏) ")
            
            # 处理退出逻辑
            if prompt.lower() in ['quit', 'q']:
                print("游戏结束!")
                return  # 直接退出函数,结束游戏
            
            # 验证输入是否为数字
            try:
                user_answer = int(prompt)
            except ValueError:
                print("请输入有效的数字或退出指令!")
                continue
            
            # 判断答案是否正确
            if user_answer == answer:
                print(random.choice(feedback))
                break  # 答对后跳出内层循环,生成新题目
            else:
                print("please try again")

multiply_game()

修改说明

  • 实现同一题目重复出现:新增内层while True循环,包裹当前题目的输入和判断逻辑,只有当用户答对时才用break跳出内层循环,生成新题目;答错则继续循环,重复当前题目。
  • 添加随时退出选项:在每次输入时先判断用户输入是否为退出指令(quit/q,不区分大小写),如果是则直接用return退出函数,结束整个游戏;同时增加了输入验证,防止用户输入非数字导致报错。
  • 优化了原代码的冗余部分,比如原代码中answer=int(int1*int2)简化为answer=int1*int2,因为两个整数相乘结果本身就是整数。

内容的提问来源于stack exchange,提问作者Tiffany J Munn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 12:43:20