You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RPSLS游戏Bug排查:无论玩家1选什么,玩家2始终获胜

RPSLS游戏胜负判断错误修复

问题根源

你定义的winningPairs列表存在语法错误:每个元素写成了("scissors,paper")这种形式,这是单个字符串,而非预期的(胜者, 败者)二元元组。正确的二元元组需要用逗号分隔两个独立字符串,比如("scissors", "paper")。

由于代码中判断的是(playerOneOption, playerTwoOption)这个二元元组是否在winningPairs中,但原列表里全是单个字符串,这个判断永远不成立,所以逻辑直接进入else分支,导致无论玩家1选什么,都判定玩家2获胜。

修正后的代码

# 10 winning pairs, defined as (winner,loser)
winningPairs = [("scissors", "paper"),
                ("scissors", "lizard"),
                ("spock", "scissors"),
                ("spock", "rock"),
                ("lizard", "spock"),
                ("lizard", "paper"),
                ("rock", "lizard"),
                ("rock", "scissors"),
                ("paper", "rock"),
                ("paper", "spock")]

# ask players for their name
print()
namePlayerOne = input("Player 1, enter your name: ")
namePlayerTwo = input("Player 2, enter your name: ")
print()

# Options that can be selected by any user
options = ["Rock","Paper","Scissors","Lizard","Spock"]

# set two variables for keeping score
playerOneScore = 0
playerTwoScore = 0

while True:
    # asking players for their choice
    playerOneOption = input(f"{namePlayerOne} select your option (scissors, Spock, lizard, rock, paper): ").lower()
    playerTwoOption = input(f"{namePlayerTwo} select your option (scissors, Spock, lizard, rock, paper): ").lower() 
    if playerOneOption == playerTwoOption: # if both players select the same option, it's always a draw
        results = "Draw"
    elif (playerOneOption, playerTwoOption) in winningPairs: # check if the order of the input is the same as an element in the winningPairs list, if it is Player one wins (who selects first)
        results = f"{namePlayerOne} wins" # print their win
        playerOneScore += 1 # add 1 score to their name
    else: # if the elif is not true, it means player two wins
        results = f"{namePlayerTwo} wins" # print their win
        playerTwoScore += 1 # add 1 score to their name

    print("-"*20)
    print(f"{namePlayerOne} chose {playerOneOption}\n{namePlayerTwo} chose {playerTwoOption}") # print each player's pick
    print(results) # print results
    print()
    print(f"{namePlayerOne} score: {playerOneScore}\n{namePlayerTwo} score: {playerTwoScore}") # print player scores
    print("-"*20)

    playAgain = input("Play again? (y/n): ") # ask if players want to play again
    if playAgain.lower() != "y":
        break

额外说明:将winningPairs里的Spock改为小写spock,因为玩家输入后会被转为小写,避免大小写不匹配导致的判断失效。

验证修正效果

当玩家1选择rock、玩家2选择scissors时,("rock", "scissors")会匹配winningPairs中的对应项,逻辑会进入elif分支,正确判定玩家1获胜。

内容的提问来源于stack exchange,提问作者wiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 23:40:38