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

Python石头剪刀布蜥蜴史波克游戏递归调用出现self未定义错误求助

问题根源排查
  • Python 类的实例方法第一个参数必须是指向实例本身的 self,你的 play 方法第一个参数写的是 results,导致方法执行时根本接收不到实例上下文,调用 self.play() 时自然报 self not defined。
  • 你在类定义的作用域内直接调用 play(results),此时类还未完成实例化,没有实例对象存在,也不存在 self 变量。
修复后的可运行基础代码
from random import choice
# 类名遵循Python大驼峰命名规范
class RockPaperScissorsGame:
    # 初始化实例属性,公共配置、对局结果都存在实例上,不用当参数传递
    def __init__(self):
        self.results = []
        self.options = ["Rock", "Paper", "Scissors", "Lizard", "Spok"]
        # 胜负映射规则:key为选项,value为该选项可以击败的所有选项
        self.win_mapping = {
            "Rock": ["Scissors", "Lizard"],
            "Paper": ["Rock", "Spok"],
            "Scissors": ["Paper", "Lizard"],
            "Lizard": ["Paper", "Spok"],
            "Spok": ["Rock", "Scissors"]
        }

    def play(self):
        users_choice = input(f"请输入你的选择(可选值:{','.join(self.options)}):")
        # 输入合法性校验,避免无效输入导致逻辑错误
        if users_choice not in self.options:
            print("输入无效,请输入正确的选项")
            return self.play()
        
        computers_choice = choice(self.options)
        
        # 替代原来的多层if嵌套,判断逻辑更简洁
        if users_choice == computers_choice:
            res = "draw"
        elif computers_choice in self.win_mapping[users_choice]:
            res = "win"
        else:
            res = "lose"
        
        self.results.append(res)
        print(f"User: {users_choice}")
        print(f"Computer: {computers_choice}")
        print(f"本局结果:{res}")
        
        print("是否再玩一局?输入yes继续,输入其他内容退出")
        if input().strip() == "yes":
            self.play()
        else:
            print("所有对局结果:", self.results)

# 类实例化之后再调用方法
if __name__ == "__main__":
    game = RockPaperScissorsGame()
    game.play()
额外优化建议
  • 不要用递归实现多局游戏逻辑:Python默认递归深度限制为1000,连续玩超过1000局会直接触发栈溢出报错,建议改用while循环实现重玩逻辑,稳定性更高。
  • 规则配置抽离:把可选选项、胜负规则都抽离成实例属性,后续要修改规则、增减选项只需要改配置部分,不需要修改核心逻辑代码。
  • 可以新增胜负统计逻辑,比如最终输出总胜率、胜场/负场/平局数,提升游戏体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:54:04