编写一个名为Rock_paper_scissors的类,该类实现游戏Rockpaper-scisssors的逻辑。对于此游戏,用户与计算机进行一定数量的对战 回合。您的班级应该有多少个场的字段,当前 轮数,以及每个玩家的获胜次数。应该有获取的方法 计算机的选择,找到一轮比赛的获胜者,然后检查是否有人 (整个)游戏。您可能需要更多方法。
我创建了各种方法。一个用于cpu随机选择,另一个用于玩家输入,另一个用于游戏条件,最后一个用于查看谁赢得了玩家。
import random
class Rock_paper_scissors:
def __init__(self,player_points,cpu_points):
self.game = [] #empty list with all possible cpu & player ans
self.cpu_points = cpu_points #counts the number of cpu points
self.player_points = player_points #counts the number of player points
def cpu_round(self):
return random.choice(self.game)
def player_round(self):
return input('Final answer\n')
def games(self,rounds,player_points,cpu_points):
turns = 0 #number of turns that have passed
while turns < rounds:
cpu_ans = self.cpu_round()
print(cpu_ans)
player_ans = self.player_round()
#game conditions to be met
if cpu_ans == player_ans:
print('Draw')
self.player_points += 1
self.cpu_points += 1
turns += 1
elif self.player_ans == 'rock' and self.cpu_ans == 'paper':
print('Cpu won round')
self.cpu_points += 1
turns += 1
elif self.player_ans == 'rock' and self.cpu_ans == 'scissors':
print('Player won round')
self.player_points += 1
turns += 1
elif self.player_ans == 'paper' and self.cpu_ans == 'rock':
print('Player won round')
self.player_points += 1
turns += 1
elif self.player_ans == 'paper' and self.cpu_ans == 'scissors':
print('Cpu won round')
self.cpu_points += 1
turns += 1
elif self.player_ans == 'scissors' and self.cpu_ans == 'rock':
print('Cpu won round')
self.cpu_points += 1
turns += 1
else:
print('Player won round')
self.player_points += 1
turns += 1
def winning_conditions(self):
if self.player_points == self.cpu_points:
print('Draw',self.player_points,self.cpu_points)
elif self.player_points > self.cpu_points:
print('Player won the game with',self.player_points,self.cpu_points)
else:
print('Cpu won the game with',self.cpu_points,self.player_points)
results = Rock_paper_scissors(player_points,cpu_points)
results.game = ['rock','paper','scissors']
rounds = int(input('How many round will the game have?'))
print(results.cpu_round())
print(results.player_round())
print(results.games(rounds))
print(results.winning_conditions())
在我的句子results = Rock_paper_scissors
中,它说缺少两个参数(player_points
和cpu_points
)。但是,当我输入这两个参数时,总是会出现错误,提示未定义游戏点。
输入
回溯(最近通话最近):
中的文件“ main.py”,第91行 结果= Rock_paper_scissors(player_points,cpu_points)
NameError:未定义名称“ player_points”
答案 0 :(得分:3)
您缺少第83行中玩家点的定义。因此正确的方法是让您开始游戏:
player_points = 0
cpu_points = 0
results = Rock_paper_scissors(player_points,cpu_points)
从您的示例中,我建议您更深入地研究Python的基础。