【问题标题】:AttributeError: 'int' object has no attribute 'move'AttributeError:“int”对象没有属性“move”
【发布时间】:2019-06-14 03:16:32
【问题描述】:

我正在为我的班级创建一个石头、纸、剪刀游戏。用过 'Int(输入对象选择CPU策略,但现在不允许 一旦我们进入回合,CPU 在我投掷我的之后通过一个动作。 请帮忙。

GitBash 中的错误: 回溯(最近一次通话最后): 文件“rps.py”,第 171 行,在 Game.play_single() 文件“rps.py”,第 123 行,在 play_single self.play_round() 文件“rps.py”,第 86 行,在 play_round move2 = self.p2.move()

如何纠正这个回溯错误?

这是我的代码:

def __init__(self, p2):
    self.p1 = HumanPlayer()
    self.p2 = p2

def play_round(self):
    move1 = self.p1.move()
    move2 = self.p2.move()
    print(f"Player 1: {move1} <> Player 2: {move2}")
    self.p1.learn(move1, move2)
    self.p2.learn(move2, move1)
    if beats(move1, move2):
        self.p1_score += 1
        print('* Player 1 wins! *')
    else:
        if move1 == move2:
            print('* Tie *')
        else:
            self.p2_score += 1
            print('* Player 2 wins! *')

    print(f"Player:{self.p1.__class__.__name__}, Score:{self.p1_score}")
    print(f"Player:{self.p2.__class__.__name__}, Score:{self.p2_score}")

# This will call a tourney
def play_game(self):
    print("Game Start!")
    for round in range(3):
        print(f"Round {round}:")
        self.play_round()
    if self.p1_score > self.p2_score:
        print('** Congrats! Player 1 WINS! **')
    elif self.p2_score > self.p1_score:
        print('** Sadly Player 2 WINS! **')
    else:
        print('** The match was a tie! **')
    print('The final score is: ' + str(self.p1_score) + ' TO ' +
          str(self.p2_score))
    print("Game over!")

# This will call a singe game.
def play_single(self):
    print("Single Game Start!")
    print(f"Round 1 of 1:")
    self.play_round()
    if self.p1_score > self.p2_score:
        print('** Congrats! Player 1 WINS! **')
    elif self.p1_score < self.p2_score:
        print('** Sadly Player 2 WINS! **')
    else:
        print('** The game was a tie! **')
    print('The final score: ' + str(self.p1_score) + ' TO ' +
          str(self.p2_score))


if __name__ == '__main__':
    p2 = {
        "1": Player(),
        "2": RandomPlayer(),
        "3": CyclePlayer(),
        "4": ReflectPlayer()
        }

# Selecting Opponent
while True:
    try:
        p2 = int(input("Select the strategy "
                       "you want to play against:  "
                       "1 - Rock Player "
                       "2 - Random Player "
                       "3 - Cycle Player "
                       "4 - Reflect Player: "))


  #"Select strategy:
    except ValueError:
        print("Sorry, I didn't understand that.")
        continue

    if p2 > 4:
        print("Sorry, you must select [1-4]: ")
        continue
    else:
        break


# Slecting 1 or 3 games
rounds = input('Enter for [s]ingle game or [f]ull game: ')
Game = Game(p2)
while True:
    if rounds == 's':
        Game.play_single()
        break
    elif rounds == 'f':
        Game.play_game()
        break
    else:
        print('Please select again')
        rounds = input('Enter [s] for a single'
                       'game and [f] for a full game: ')

【问题讨论】:

    标签: python-3.x


    【解决方案1】:
    Game = Game(p2)
    

    这条线有几个问题。

    1. Game(p2) 创建的对象分配给Game 变量shadows Game 类。这是不幸的,因为稍后您将无法方便地创建Game 对象。更好的命名会给出game = Game(p2)
    2. 在那一行,p2 是一个整数,因为您的代码之前运行的是p2 = int(input(...))。执行Game(p2) 会使用整数实例化您的Game 对象:
      def __init__(self, p2):
      self.p1 = HumanPlayer()
      self.p2 = p2                # now self.p2 is also an int 
      

    def play_round(self): move1 = self.p1.move() move2 = self.p2.move() # 调用 some_int.move() ``` 该错误正确地通知您您正在尝试在整数上调用.move。类似于1.move42.move。不过整数没有.move

    要解决此问题,请使用其他变量而不是 p2,例如...choice。这样,p2 可以保持为 dict,而另一个变量 choice 可以存储输入的值。

    # Selecting Opponent
    while True:
        try:
            choice = int(input("Select the strategy "
                               "you want to play against:  "
                               "1 - Rock Player "
                               "2 - Random Player "
                               "3 - Cycle Player "
                               "4 - Reflect Player: "))
    
      #"Select strategy:
        except ValueError:
            print("Sorry, I didn't understand that.")
            continue
    
        if choice > 4:
            print("Sorry, you must select [1-4]: ")
            continue
        else:
            break
    
    ...
    
    game = Game(p2[choice])  # since p2 is a dictionary with int keys and Player values
    

    【讨论】:

    • 感谢您的回复!现在它给了我一个 p2 的 nameError? game = Game(p2[choice]) NameError: name 'p2' is not defined
    • @Marcus 我会在这里做一些猜测:1) 检查你的文件名是main.py,否则p2 = {...} 字典不会在 if 块下运行。或者 2) 将 p2 = {...} 移到 if 块之外。完全删除if __name__ == '__main__': 行。
    • 1.由于课程要求,我的文件名为 rps.py。 2. 我删除了 if name == 'main': line to a nameError: Traceback (most recent call last): File "rps.py", line 77,在 类游戏中:文件“rps.py”,第 168 行,在游戏中 game = game(p2[choice]) NameError: name 'game' is not defined 我玩过 def Game(),但它没有似乎没那么容易。
    • @Marcus Python 区分大小写。 game = Game(p2[choice]) 代替(事实证明这就是我在回答中的内容:P)。
    猜你喜欢
    • 2020-05-31
    • 2021-11-30
    • 2020-03-26
    • 2013-04-15
    • 2021-01-18
    • 2019-05-30
    • 2021-02-24
    • 2021-08-01
    • 2015-07-06
    相关资源
    最近更新 更多