Python 如何统计纸牌、石头、剪刀游戏的胜利?
循环结束后,我如何计算胜利数Python 如何统计纸牌、石头、剪刀游戏的胜利?,python,Python,循环结束后,我如何计算胜利数 print 'PLAY ROCK PAPER SCISSORS' for roundd in range(1,6): print 'Round: ' + str(roundd) human = raw_input('Whats your draw: ') from random import choice cpu = choice(('rock', 'paper', 'scissors')) if human == cpu
print 'PLAY ROCK PAPER SCISSORS'
for roundd in range(1,6):
print 'Round: ' + str(roundd)
human = raw_input('Whats your draw: ')
from random import choice
cpu = choice(('rock', 'paper', 'scissors'))
if human == cpu:
print 'CPU: ' + cpu
print 'Draw'
if cpu == 'rock' and human == 'scissors':
print 'CPU: ' + cpu
print 'You Lose'
if cpu == 'scissors'and human == 'paper':
print 'CPU: ' + cpu
print 'You Lose'
if cpu == 'paper'and human == 'rock':
print 'CPU: ' + cpu
print 'You Lose'
if cpu == 'rock' and human == 'paper':
print 'CPU: ' + cpu
print 'You Win!'
if cpu == 'scissors'and human == 'rock':
print 'CPU: ' + cpu
print 'You Win'
if cpu == 'paper'and human == 'scissors':
print 'CPU: ' + cpu
print 'You Win'
您可以跟踪
cpu
和人员
的wins
变量,以及每次记录win时的增量。例如
human_wins = 0
cpu_wins = 0
for roundd in range(1,6):
if cpu == 'paper'and\
human == 'rock':
cpu_wins += 1
print 'CPU: ' + cpu
print 'You Lose'
if cpu == 'paper'and\
human == 'scissors':
human_wins += 1
print 'CPU: ' + cpu
print 'You Win'
...
@卡夫曼的答案是正确的。我想指出的是,通过使用字典并从所有
if
语句中删除重复的print'CPU:'+CPU
行,可以使代码更加简洁
这段代码还检查用户的输入是否有效,正如@atomicinf所建议的那样。否则,我写的代码将被视为自动赢下面的while
循环就是这样做的:如果用户输入了无效的移动,它会给他们一条错误消息,并要求他们再试一次,直到他们执行了有效的移动
下面的代码进行了这些更改和其他一些更改,并对我为什么要做各种事情进行了一些评论:
from random import choice # usually, imports go at the top; easier to manage
print 'PLAY ROCK PAPER SCISSORS'
# This dictionary associates a move to the move that it beats.
beats = {
'rock': 'scissors',
'paper': 'rock',
'scissors': 'paper',
}
moves = ('rock', 'paper', 'scissors') # The tuple of all valid moves
# could also do moves = beats.keys()
draws = cpu_wins = human_wins = 0 # start our counter variables off at 0
for roundd in range(1,6):
print 'Round: ' + str(roundd)
human = raw_input("What's your draw: ")
while human not in moves: # keep retrying if they gave a bad move...
print "Invalid move '%s' - expected one of %s." % (human, ', '.join(moves))
# this % formatting just replaces the %s with the variable on the left
print "Try again!"
human = raw_input("What's your draw: ")
cpu = choice(moves)
print 'CPU: ' + cpu # this happens every time, no need to retype it so many times :)
if human == cpu:
print 'Draw'
draws += 1
elif human == beats[cpu]:
print 'You Lose'
cpu_wins += 1
else:
print 'You Win'
human_wins += 1
# done - print out the overall record
print "Your record: %s wins, %s losses, %s draws" % (human_wins, cpu_wins, draws)
有意义吗?这是一个经过清理的版本;希望它能起到启发作用:
import random
class RockPaperScissors(object):
choices = ['rock', 'paper', 'scissors']
def __init__(self):
self.wins = 0
self.draws = 0
self.losses = 0
def cpu(self):
return random.choice(type(self).choices)
def human(self):
while True:
res = raw_input("What's your draw: ").strip().lower()
if res in type(self).choices:
return res
else:
print('Enter one of {}'.format(', '.join(type(self).choices)))
def win(self):
print('You win!')
self.wins += 1
def draw(self):
print('Draw')
self.draws += 1
def lose(self):
print('You lose')
self.losses += 1
def play(self):
"""
Play one hand
"""
human = self.human()
cpu = self.cpu()
print("Computer chose {}".format(cpu))
val = type(self).choices.index
[self.draw, self.lose, self.win][(val(cpu) - val(human)) % 3]()
def main():
print('PLAY ROCK PAPER SCISSORS')
rps = RockPaperScissors()
for rnd in xrange(1,6):
print('Round: {}'.format(rnd))
rps.play()
print('Final tally: {} losses, {} draws, {} wins'.format(rps.losses, rps.draws, rps.wins))
if __name__=="__main__":
main()
根据PEP8,使用这样的`\`看起来很糟糕,被认为是不好的做法,因为太懒了,无法输入所有的代码,但只需为cpu保留一个整数,为用户保留一个整数,如果cpu赢了,
cpu\u score+=1
,否则增加用户,您需要验证用户的输入。现在,如果用户的输入恰好在“石头、布、剪刀”集合之外,那么就不会发生任何有用的事情;如果用户给了您意外的选择,您应该通知用户(并允许他们再次选择,告诉他们什么是有效的输入)。您可以通过在xrange中为rnd设置行中的6
来改进这一点,当您调用main
时,会输入一个变量,让你选择轮次。我会选择self.choices
而不是rockpaperscraster.choices
:打字更简洁,更易于子类化。另外,尽管模算术索引很可爱,但我不知道它真的比显式地说要好。@Dougal:说得好;我使用了type(self)
来表示类。