我正在 python 上开发石头剪刀布,但我被卡住了。
我做了一个在(石头、剪刀、布)之间循环的类(class),我希望计算机知道它是之前的游戏。
例如(第一轮计算机玩石头,下一轮它应该玩纸)
但我不知道如何调用学习函数使其工作
class Player:
def __init__(self):
self.score = 0
def move(self):
return 'rock'
def learn(self, my_move, their_move):
self.my_move = my_move
self.their_move = their_move
def beats(one, two):
return ((one == 'rock' and two == 'scissors') or
(one == 'scissors' and two == 'paper') or
(one == 'paper' and two == 'rock'))
class Game:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def play_round(self):
move1 = input("Pick something!\n")
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 ("You win")
print ("Human score = " + str(self.p1.score) + " " + "Computer score = " + str(self.p2.score) )
elif beats(move2,move1):
self.p2.score += 1
print ("Computer wins")
print ("Human score = " + str(self.p1.score) + " " + "Computer score = " + str(self.p2.score) )
else:
print ("Draw")
print ("Human score = " + str(self.p1.score) + " " + "Computer score = " + str(self.p2.score) )
def play_game(self):
print("Game start!")
for round in range(3):
print(f"Round {round}:")
self.play_round()
print("Game over!")
class human_player(Player):
def move(self):
return input("Pick something!\n")
class randomplayer(Player):
def move(self):
return random.choice(moves)
class repeat(Player):
def move(self):
return 'rock'
class cycleplayer(Player):
def move(self):
# calling my_move from the Player class
if self.learn.my_move == "rock" or "paper" or "scissors" :
return 'rock'
elif self.their_move == 'rock':
return "paper"
elif self.their_move == 'paper':
return "scissors"
elif self.their_move == 'scissors':
return "rock"
if HumanPlayer_choice == "cycle" :
game = Game(Player(), cycleplayer())
game.play_game()
这是我收到的错误。
Exception has occurred: AttributeError 'function' object has no attribute 'my_move'
我知道我需要将 init 函数与 learn 函数结合使用才能使其工作,但我不确定如何操作。
最佳答案
问题出在这一行:
if self.learn.my_move == "rock" or "paper" or "scissors" :
learn
函数没有名为 my_move
的属性。你想做的可能是
if self.my_move == "rock" or self.my_move == "paper" or self.my_move == "scissors" :
请注意,您必须在“paper”
和“scissors”
之前添加self.my_move ==
;否则它的评估如下:
if (self.my_move == "rock") or ("paper") or ("scissors"):
并且由于非空字符串始终被评估为 True
,因此此 if
情况变得毫无用处。
正如 @DmitryErohin 提到的,有一种更好的方法可以实现这一目标,而无需重复自己:
if (self.my_move in ("rock", "paper", "scissors")):
这更加简洁并且更具可读性
关于Python 无法调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53580471/