python - 如何修复石头剪刀布中的计算机选择
问题描述
看来我一切正常。就是不知道为什么每次玩的时候,电脑的选择都不是我想要的。计算机应该从移动列表中选择一些东西,而不是返回数字。
import random
moves = ['rock', 'paper', 'scissors']
我怀疑问题可能出在 RandomPlayer
class RandomPlayer(Player):
def move(self):
index = random.randint(0, 2) # Selects random moves from the move list
return (index)
class Game():
def __init__(self, p2):
self.p1 = HumanPlayer()
self.p2 = p2
def play_game(self):
print("\nLet's play Rock, Paper, Scissors!")
for round in range(1, 4):
print(f"\nRound {round}:")
self.play_round()
if self.p1.score > self.p2.score:
print('Player 1 won!')
# print(f"The score is {self.p1.score} to {self.p2.score}")
elif self.p1.score < self.p2.score:
print('Player 2 won!')
# print(f"The score is {self.p1.score} to {self.p2.score}")
else:
print('The game was a tie!')
print(f"Final score is {self.p1.score} to {self.p2.score}")
# plays a single round if user chose to
def play_single(self):
print("Rock Paper Scissors, Go!")
print(f"Round 1 of 1:")
self.play_round()
if self.p1.score > self.p2.score:
print('Player 1 won!')
elif self.p1.score < self.p2.score:
print('Player 2 won!')
else:
print('The game was a tie!')
print(f"Final score is {self.p1.score} to {self.p2.score}")
def play_round(self):
move1 = self.p1.move()
move2 = self.p2.move()
result = Game.play(move1, move2)
self.p1.learn(move2) # stores opponent move
self.p2.learn(move1) # stores opponent move
这是我给的输入和它给我的输出
Round 1:
Rock, Paper, Scissors? rock
You played rock and opponent played 2
[ It's A TIE ]
[The score is 0 to 0]
Round 2:
Rock, Paper, Scissors? paper
You played paper and opponent played 1
[ It's A TIE ]
[The score is 0 to 0]
Round 3:
Rock, Paper, Scissors? scissors
You played scissors and opponent played 1
[ It's A TIE ]
[The score is 0 to 0]
The game was a tie!
Final score is 0 to 0
我相信问题可能出在 Class Game()
解决方案
我相信问题出在您的 RandomPlayer 类中。您应该返回与该索引相关的移动,而不是在移动方法中返回索引。换句话说,您的 RandomPlayer 类应该是:
class RandomPlayer(Player):
def move(self):
index = random.randint(0, 2) # Selects random moves from the move list
return moves[index] # Changed from return (index)
推荐阅读
- python - 如何将python参数传递给perl脚本?
- python - 附加到python中的json文件
- node.js - 我可以在 redux 商店中存储 socket.io 套接字吗?(并调用它的函数)
- mysql - MySQL:创建函数、执行语句和删除函数
- ios - 使用 Apple Watch 混合音频
- swiftui - SwiftUI - 尝试从不同的视图重新运行一个类以强制重新加载数据
- python-3.x - 如何在嵌套数据上访问 RPyC 中的公共属性?
- c# - FluentValidator 如何确定默认使用的显示名称?
- model-view-controller - Microsoft Azure Speech-to-Text MVC 应用程序
- python - 无法删除日期列 KeyError: "['Date'] not found in axis