循环使用Python猜猜游戏

时间:2014-04-13 19:39:17

标签: python python-2.7

作为一名初学者,我从过去的代码审查中获得了一些知识,我尝试进行代码审查,但不知何故让程序停止按预期工作。假设在5场比赛后打破循环,有时只会这样做。

import random
import math
import console

console.set_font('Arial-BoldMT',15)

print'Welcome to the guessing game!\nA number will be randomly chosen from 0 to 1000.\nThe player will make a guess, and then the computer will guess. Who ever is closest wins that round!\nFirst to 5 wins!'

rounds = 0
run_again = 'y'
player_wins = 0
computer_wins = 0
draws = 0

while run_again == 'y':
    number = random.randint(0,1000)
    player_number = input('\nPlayer: ')
    computer_number = random.randint(0,1000)

    print 'Computer:', computer_number
    print 'Number:', number

    player_score=math.fabs(player_number-number)
    computer_score=math.fabs(computer_number-number)

    if player_score>=computer_score:
        computer_wins+=1
        rounds +=1
        console.set_color(1.00, 0.00, 0.00)
        print 'You lost that round'
        console.set_color(0.00, 0.00, 0.00)

    if player_score<=computer_score:
        player_wins+=1
        rounds +=1
        console.set_color(0.00, 0.00, 1.00)
        print 'You won that round'
        console.set_color(0.00, 0.00, 0.00)

    if player_score==computer_score:    
        draws+=1
        rounds +=1
        console.set_color(0.00, 1.00, 0.00)
        print 'That round was a tie'
        console.set_color(0.00, 0.00, 0.00)


    if rounds == 5:
        if player_wins == 4:
            console.set_color(0.00, 0.00, 1.00)
            print '\nYOU WON THE GAME'
            console.set_color(0.00, 0.00, 0.00)
            break
        if computer_wins == 4:
            console.set_color(1.00, 0.00, 0.00)
            print '\nYOU LOST THE GAME'
            console.set_color(0.00, 0.00, 0.00)
            break

2 个答案:

答案 0 :(得分:2)

我认为如果你正确地考虑了结果,那就没关系了:

if rounds == 5:
    if playr_wins > computer_wins:
        console.set_color(0.00, 0.00, 1.00)
        print '\nYOU WON THE GAME'
        console.set_color(0.00, 0.00, 0.00)
        break
    elif computer_wins > playr_wins:
        console.set_color(1.00, 0.00, 0.00)
        print '\nYOU LOST THE GAME'
        console.set_color(0.00, 0.00, 0.00)
        break
    else:
       print "Wrong counts"

答案 1 :(得分:1)

如果一名球员或另一名球员获得4胜,则只有break。使用for循环来限制轮次要容易得多:

for _ in range(5):