如何在纸质,摇滚,剪刀游戏中获胜?

时间:2012-07-29 02:04:35

标签: 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 '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'

3 个答案:

答案 0 :(得分:5)

@ kaveman的回答是对的。我只想指出,通过使用字典并从所有print 'CPU: ' + cpu语句中取出重复的if行,您可以使代码更简洁。

此代码还检查用户的输入是否有效,如@atomicinf所示。否则,我写的代码将'lol'计为自动获胜。 :)这就是下面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)

有意义吗?

答案 1 :(得分:3)

您可以跟踪winscpu的{​​{1}}个变量,并在每次记录获胜时递增。 E.g。

human

答案 2 :(得分:2)

这是一个清理版本;可能是有启发性的:

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()
相关问题