Nim游戏Python代码计算机取石子数显示与实际扣除不一致如何修复
问题修复方案
核心问题你已经定位到了:draw_stones() 每次调用都会生成新的随机数,两次调用自然得到两个不同的取值,只需要将单次调用的返回值存入变量,再分别用于打印和扣减石子即可,完全不需要修改现有函数结构。
修改后完整可运行代码
import random # 函数统一定义,不要放在循环内重复声明 def player_announce(stones): print('There are', stones, 'stones. How many would you like?', end=' ') def invalid_entry(): print('Enter a number from 1-3.') def draw_stones(): return random.randint(1, 3) if __name__ == '__main__': stones = random.randint(15, 30) turn = 0 # 0代表玩家回合,1代表电脑回合 while stones > 0: if turn == 0: player_announce(stones) player_stones = int(input('')) if 1 <= player_stones <=3: stones -= player_stones turn = 1 else: invalid_entry() else: # 单次调用函数生成取子数,存入变量复用 computer_take = draw_stones() print('There are', stones, 'stones. The computer takes', computer_take) stones -= computer_take turn = 0 # 游戏结束判断胜负 print('The computer beats the player!' if turn == 0 else 'The player beats the computer!')
优化点说明
- 将所有函数声明移到循环外部,避免每次循环重复定义函数造成不必要的性能损耗
- 新增变量
computer_take存储draw_stones()的单次返回值,同时用于打印和石子扣减,保证两个场景取值完全一致 - 优化了玩家输入校验的判断逻辑,可读性更强
- 保持所有原有功能逻辑不变,符合必须使用函数实现的要求
内容的提问来源于stack exchange,提问作者Soda
相关产品推荐
相关产品推荐

