这是 Rock剪刀纸 的游戏代码,它是humanplayer
与reflectplayer
的对比。 Reflectplayer
位使用者复制了上一次humanplayer
的动作并显示了动作。我试图从move2
到play_round
访问ReflectPlayer
。但是如何? game1.play_round.move2
不起作用吗?
import random
moves = ['rock', 'paper', 'scissors']
class Player:
def move(self):
return 'rock'
def learn(self, my_move, their_move):
pass
class RandomPlayer:
def move(self):
all = ["rock","scissors","paper"]
ranint = random.randint(0,2)
return all[ranint]
def learn(self, my_move, their_move):
pass
class HumanPlayer:
def move(self):
ans = input("Rock Paper or Scissors?").lower()
return ans
def learn(self,my_move,their_move):
pass
class ReflectPlayer:
def move(self):
i = 1
RSP = ["rock","paper","scissors"]
print(self.move2)
if i == 1:
i += 1
return RSP[random.randint(0,2)]
elif game1.play_round.move2 == RSP[0]:
return RSP[0]
elif game1.play_round.move2 == RSP[1]:
return RSP[1]
elif game1.play_round.move2 == RSP[2]:
return RSP[2]
else:
print("Wrong input !")
pass
def learn(self,my_move,their_move):
pass
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 = self.p1.move()
move2 = self.p2.move()
print(f"Player 1: {move1} Player 2: {move2}")
if beats(move1 , move2) == True:
print(f"This Round : Player 1 WIN")
elif beats(move2 , move1) == True:
print(f"This Round : Player 2 WIN")
elif move1 == move2:
print("This Round : TIE")
else:
print("Wrong Input !")
self.p1.learn(move1, move2)
self.p2.learn(move2, move1)
def play_game(self):
print("Game start!")
for round in range(3):
print(f"Round {round}:")
self.play_round()
print("Game over!")
if __name__ == '__main__':
game1 = Game(ReflectPlayer(),HumanPlayer())
game1.play_game()
答案 0 :(得分:0)
考虑更改您的实现,以将最后播放的动作传递给move()方法。如果您的播放器需要使用之前的动作,则可以轻松访问它们。如果不是,那就丢掉它们。我假设您还会有其他类型的玩家可以从中受益。
rsp = ['rock', 'paper', 'scissors']
class ReflectPlayer:
def move(self, lastOpponentMove):
if lastOpponentMove == None:
return rsp[random.randint(0,2)]
elif lastOpponentMove == rsp[0]:
return rsp[0]
elif lastOpponentMove == rsp[1]:
return rsp[1]
elif lastOpponentMove == rsp[2]:
return rsp[2]
else:
print("Wrong input !")
pass
def learn(self,my_move,their_move):
pass
可能在Game类中进行调整:
class Game:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
self.lastP1Move = None
self.lastP2Move = None
def play_round(self):
move1 = self.p1.move(lastP2Move)
move2 = self.p2.move(lastP1Move)
lastP1Move = move1
lastP2Move = move2
print(f"Player 1: {move1} Player 2: {move2}")
if beats(move1 , move2) == True:
print(f"This Round : Player 1 WIN")
elif beats(move2 , move1) == True:
print(f"This Round : Player 2 WIN")
elif move1 == move2:
print("This Round : TIE")
else:
print("Wrong Input !")
self.p1.learn(move1, move2)
self.p2.learn(move2, move1)
一些注意事项:
希望这会有所帮助