基于二维列表的石头剪刀布游戏胜负查询与循环问题求助
石头剪刀布游戏代码问题解决
需求与问题
- 作业要求:使用二维列表存储胜负结果,实现玩家与电脑的胜负判定、统计双方获胜次数,支持玩家选择是否继续游戏
- 当前问题:代码陷入无限循环,胜负判定逻辑完全失效
原代码
compchoice = " " humwin = 0 compwin = 0 again = 'Y' playing = True outcomes = [[1, 2], [2, 3], [3, 1], [2, 1], [3, 2], [1, 3], [1, 1], [2, 2], [3, 3]] #thelist = [] #thelist.append("Player 1 = {playerchoice}, Player 2 = {compchoice}") while playing: playerpic = int(input("Pick 1 for Rock, 2 for Paper, or 3 for Scissors: ")) comppic = random.randint(1, 3) pick = [playerpic, comppic] for x in range(len(outcomes)): for i in range(len(outcomes[x])): if pick == outcomes[x][i]: print("You chose Rock.") print("Computer choose Paper") print("You lost") compwin += 1 print("Human: ", humwin, " Computer: ", compwin) break #will not break, seems to ignore if? missing something!
问题分析
- 判定条件完全错误:
outcomes[x][i]取出的是单个数字(比如1、2),但pick是长度为2的列表,两者永远无法相等,导致判定逻辑根本不会触发,循环一直执行。 - 缺少模块导入:代码使用
random.randint但未导入random模块,运行会直接报错。 - 无退出游戏逻辑:
playing变量始终为True,没有任何修改它的代码,必然无限循环。 - 选择提示硬编码:不管玩家选的是什么,都固定打印"You chose Rock",不符合实际选择。
修正后的代码
import random humwin = 0 compwin = 0 playing = True # 二维列表分组:索引0-2是电脑赢,3-5是玩家赢,6-8是平局 outcomes = [[1, 2], [2, 3], [3, 1], [2, 1], [3, 2], [1, 3], [1, 1], [2, 2], [3, 3]] # 数字对应文字映射 choice_text = {1: "Rock", 2: "Paper", 3: "Scissors"} while playing: # 获取玩家输入并验证合法性 while True: try: playerpic = int(input("Pick 1 for Rock, 2 for Paper, or 3 for Scissors: ")) if playerpic in [1,2,3]: break else: print("请输入1、2、3中的一个数字!") except ValueError: print("请输入有效的数字!") comppic = random.randint(1, 3) pick = [playerpic, comppic] # 判定胜负 if pick in outcomes[:3]: # 电脑赢的情况 print(f"You chose {choice_text[playerpic]}.") print(f"Computer chose {choice_text[comppic]}") print("You lost") compwin += 1 elif pick in outcomes[3:6]: # 玩家赢的情况 print(f"You chose {choice_text[playerpic]}.") print(f"Computer chose {choice_text[comppic]}") print("You won!") humwin += 1 else: # 平局 print(f"You chose {choice_text[playerpic]}.") print(f"Computer chose {choice_text[comppic]}") print("It's a tie!") # 打印当前比分 print(f"Human: {humwin} Computer: {compwin}") # 询问是否继续游戏 while True: again = input("Do you want to play again? (Y/N): ").strip().upper() if again in ['Y', 'N']: break print("请输入Y或N!") if again == 'N': playing = False print("游戏结束!")
关键修改说明
- 导入
random模块,解决随机数生成报错问题 - 重构胜负判定逻辑:直接判断
pick在outcomes的对应分组中,无需冗余的嵌套循环 - 添加输入合法性验证,避免玩家输入无效内容导致程序崩溃
- 用字典映射数字到对应文字,避免硬编码选择提示的错误
- 添加继续游戏的询问逻辑,让玩家可以主动退出游戏,彻底解决无限循环问题
内容的提问来源于stack exchange,提问作者Andrew
相关产品推荐
相关产品推荐

