运行石头剪刀布游戏代码后无结果,电脑无法生成响应求助
石头剪刀布游戏代码问题排查与修复
现存问题
- 未导入
random模块:调用random.randrange前未导入模块,导致无法生成电脑的随机选择。 - 缺失玩家输入逻辑:未定义
player_input变量,程序无法获取玩家的选择。 - 未定义
items映射列表:无法将数字转换为对应的石头/剪刀/布文本,直接调用会触发错误。 - 电脑随机数范围错误:
random.randrange(0,2)仅能生成0、1两个值,无法覆盖代码中用到的2,导致部分胜负判断逻辑永远不会触发。
修正后的代码
import random # 定义数字对应的游戏选项 items = ["rock", "scissors", "paper"] # 获取玩家输入 print("press 0 for rock, 1 for scissors, 2 for paper") player_input = int(input("Enter your choice: ")) # 生成电脑的随机选择 computer_input = random.randrange(0, 3) # 输出双方选择 print(items[player_input], "selected by player") print(items[computer_input], "selected by computer") # 判断胜负 if player_input == 0 and computer_input == 1: print("computer winner") elif player_input == 1 and computer_input == 0: print("player winner") elif player_input == 1 and computer_input == 2: print("computer winner") elif player_input == 2 and computer_input == 1: print("player winner") elif player_input == 0 and computer_input == 2: print("player winner") elif player_input == 2 and computer_input == 0: print("computer winner") else: print("both are winners")
内容的提问来源于stack exchange,提问作者Nafeez Ahamed
相关产品推荐
相关产品推荐

