石头剪刀布Python程序调用比较方法报错,请求技术排查
石头剪刀布程序错误修复方案
核心错误点及修复
构造方法参数拼写错误
Player类__init__方法里的参数写了choise,但赋值时用的是choice,直接导致未定义变量报错。把参数名改成choice即可。类变量与枚举值的逗号问题
Player类里name = '',、choice = ''后面的逗号会让变量变成元组类型;Variants枚举里ROCK = 1,这类写法同理,会把枚举值变成(1,)而非整数1,后续比较全错。把这些逗号全部删掉。whoWins方法设计与逻辑错误
作为实例方法,没必要传入bot和alex两个参数,改成接收另一个玩家实例更合理。另外原有的大小比较逻辑完全不符合石头剪刀布规则(比如石头应该赢剪刀,但1<3会判断成输),得重新写胜负判断逻辑。参数类型不匹配
Player构造方法默认choice是字符串'ROCK',但main里传的是Variants枚举实例,类型不统一。改成默认用Variants.ROCK枚举即可。
修正后的完整代码
Player.py
from variants import Variants class Player: def __init__(self, choice=None, name='bot'): self.name = name # 默认选择ROCK枚举,避免类型不一致 self.choice = choice if choice is not None else Variants.ROCK def who_wins(self, other_player): # 严格遵循石头剪刀布胜负规则 if self.choice == other_player.choice: print(f"{self.name} 和 {other_player.name} 平局") elif (self.choice == Variants.ROCK and other_player.choice == Variants.SCISSORS) or \ (self.choice == Variants.SCISSORS and other_player.choice == Variants.PAPER) or \ (self.choice == Variants.PAPER and other_player.choice == Variants.ROCK): print(f"{self.name} 获胜") else: print(f"{other_player.name} 获胜")
variants.py
from enum import Enum class Variants(Enum): ROCK = 1 PAPER = 2 SCISSORS = 3
main.py
from variants import Variants from player import Player bot = Player() alex = Player(Variants.ROCK, "Alex") # 直接传入另一个玩家实例即可 bot.who_wins(alex) # 测试其他场景 alex_paper = Player(Variants.PAPER, "Alex") bot.who_wins(alex_paper)
内容的提问来源于stack exchange,提问作者9RoxXx
相关产品推荐
相关产品推荐

