0

ループが完了した後、どうすれば勝利を集計できますか?

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'
4

3 に答える 3

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)

わかる?

于 2012-07-29T02:16:08.123 に答える
3

winsの両方の変数を追跡し、勝利が記録されるたびにインクリメントできます。例えばcpuhuman

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'
    ...
于 2012-07-29T02:13:30.433 に答える
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()
于 2012-07-29T02:46:05.980 に答える