Python开发Bagels逻辑游戏时while无限循环故障排查
Bagels游戏while循环逻辑故障修复
我在跟着《The Big Book of Small Python Projects》练习Python编程,完成首个项目——演绎逻辑小游戏「Bagels」开发时遇到运行故障:代码首次启动可正常执行,但用户输入错误猜测后程序无法按预期运行,存在while循环逻辑异常问题。
游戏规则
Bagels是一款数字演绎逻辑游戏,玩家需要根据系统提示猜出3位秘密数字,规则如下:
- 猜测包含正确数字但位置错误时,提示
Pico - 数字和位置均正确时,提示
Fermi - 没有任何正确数字时,提示
Bagels - 玩家共有10次猜测机会
按照设计预期:外层while循环负责控制剩余猜测次数,全程运行直到玩家用完机会或猜对数字为止;第二层while循环负责输入校验,拦截长度不等于3位的非法输入。
原有故障代码
import re import random #In Bagels, a deductive logic game, you #must guess a secret three-digit number #based on clues. The game offers one of #the following hints in response to your guess: #“Pico” when your guess has a correct digit in the #wrong place, “Fermi” when your guess has a correct #digit in the correct place, and “Bagels” if your guess #has no correct digits. You have 10 tries to guess the #secret number. choice_of_nums=['123','345','674','887','356','487','916'] random_three_num=random.choices(choice_of_nums) count_bagel=0 count_fermi=0 Chances=10 while Chances!=0: guess = input(f'Guess the three digit number! You have {Chances} to guess! ') while len(guess)!=3: guess=input('You must choose a three digit number! Try again! ') for i in range(0,len(random_three_num)): if guess==random_three_num: print('YOU WIN! Well done') break elif guess[i] not in random_three_num: count_bagel+=1 if count_bagel==len(random_three_num): print('Bagels') Chances=Chances-1 elif guess[i]==random_three_num[i]: count_fermi+=1 Chances=Chances-1 print('Fermi') elif guess in random_three_num: print('Pico')
核心错误点
代码共有4处直接导致循环异常的逻辑问题:
- 随机数接口用错:
random.choices()返回值是单元素列表(例如抽中123时实际得到['123']),不是预期的3位字符串,后续所有字符串比对、逐位遍历逻辑从根源上失效,取单个随机元素应该用random.choice() - 计数变量未重置:
count_bagel、count_fermi定义在循环最外层,每轮猜测结束后不会清零,计数会跨轮次累加,触发条件永远无法正确匹配 - 次数扣减位置错误:将剩余次数
Chances的扣减逻辑写在了逐位判断的分支内,会出现一次猜测扣多次次数、猜对数字仍扣次数的问题,次数扣减应该放在每轮有效猜测、提示输出完成后统一执行 - 循环跳出与提示逻辑混乱:猜对数字后的
break只能跳出内层for循环,无法终止外层游戏主循环;Pico/Fermi的判断顺序和条件写错,会出现提示重复、漏输出的问题;原有输入校验只判断长度,未校验输入是否为数字,字母等非法内容可以直接通过校验。
修复后可运行代码
import random # 游戏常量定义 MAX_CHANCES = 10 SECRET_NUM_POOL = ['123','345','674','887','356','487','916'] # 初始化游戏状态 secret_num = random.choice(SECRET_NUM_POOL) remaining_chances = MAX_CHANCES is_win = False print(f"已生成3位秘密数字,你共有{MAX_CHANCES}次猜测机会,游戏开始") while remaining_chances > 0: # 获取输入并做合法性校验 guess = input(f'\n剩余猜测次数:{remaining_chances},请输入3位数字:') while len(guess) != 3 or not guess.isdigit(): guess = input('输入非法,请输入恰好3位的数字:') # 猜对直接终止游戏 if guess == secret_num: is_win = True break # 逐位计算提示 clues = [] for idx in range(3): if guess[idx] == secret_num[idx]: clues.append('Fermi') elif guess[idx] in secret_num: clues.append('Pico') # 输出本轮结果提示 if len(clues) == 0: print('Bagels') else: clues.sort() print(' '.join(clues)) # 统一扣减剩余次数 remaining_chances -= 1 # 游戏结束结算 if is_win: print(f'恭喜猜对!正确答案就是{secret_num}') else: print(f'次数已用完,游戏结束,正确答案是{secret_num}')
内容的提问来源于stack exchange,提问作者Jos
相关产品推荐
相关产品推荐

