电脑猜数字游戏代码故障:猜测13时始终卡在14
问题修复:猜数字游戏卡在特定值的bug
问题根源
你的代码中goSmall方法的边界更新逻辑完全错误:当程序猜测的数字太大时,应该将上限(upperBound)设置为当前猜测值减1,但你错误地写成了加1,导致边界范围无法正确缩小,最终出现猜测值卡住的情况。
比如目标数字是13时的错误流程:
- 当程序猜14,你点击“Too large”
- 错误地将
upperBound设为14+1=15 - 下次计算
myNumber = (lowerBound + upperBound) // 2,如果此时lowerBound是13,结果就是(13+15)//2=14,循环往复永远猜不到13
修复后的代码
只需要修改goSmall方法中的边界更新代码:
import random from breezypythongui import EasyFrame class GuessingGame(EasyFrame): """Plays a guessing game with the user.""" def __init__(self): """Sets up the window,widgets, and data.""" EasyFrame.__init__(self, title = "Guessing Game") self.lowerBound = 1 self.upperBound = 100 self.count = 0 self.myNumber = (self.lowerBound + self.upperBound) // 2 guess = "Is the number " + str(self.myNumber) + "?" self.myLabel = self.addLabel(text = guess, row = 0, column = 0, sticky = "NSEW", columnspan = 4) self.small = self.addButton(text = "Too small", row = 1, column = 0, command = self.goLarge) self.large = self.addButton(text = "Too large", row = 1, column = 1, command = self.goSmall) self.correct = self.addButton(text = "Correct", row = 1, column = 2, command = self.goCorrect) self.newButton = self.addButton(text = "New game", row = 1, column = 3, command = self.newGame) def goLarge(self): """Guess was too small, so move guess to the right of the number.""" self.count += 1 self.lowerBound = self.myNumber + 1 self.myNumber = (self.lowerBound + self.upperBound) // 2 self.myLabel["text"] = "Is the number " + str(self.myNumber) + "?" def goSmall(self): """Guess was too large, so move guess to the left of the number.""" self.count += 1 # 修复:将upperBound设为当前猜测值减1,而不是加1 self.upperBound = self.myNumber - 1 self.myNumber = (self.lowerBound + self.upperBound) // 2 self.myLabel["text"] = "Is the number " + str(self.myNumber) + "?" def goCorrect(self): """Guess was correct, so disable buttons.""" self.large["state"] = "disabled" self.small["state"] = "disabled" self.correct["state"] = "disabled" def newGame(self): """Resets the GUI to its original state.""" self.large["state"] = "normal" self.small["state"] = "normal" self.correct["state"] = "normal" self.lowerBound = 1 self.upperBound = 100 self.count = 0 self.myNumber = (self.lowerBound + self.upperBound) // 2 self.myLabel["text"] = "Is the number " + str(self.myNumber) + "?" def main(): """Instantiate and pop up the window.""" GuessingGame().mainloop() if __name__ == "__main__": main()
额外优化建议
- 可以在
goCorrect方法中添加弹窗或更新标签文本,显示猜测次数,提升用户体验 - 原代码中
if __name__ == "__main__"里的while True是多余的,mainloop()本身就是阻塞循环,重复调用会打开多个窗口,已移除
内容的提问来源于stack exchange,提问作者Ian Schaak
相关产品推荐
相关产品推荐

