tda
tda

Reputation: 241

Looping in Guessing Game in Python

As a beginner with some knowledge from past code reviews, I tried doing a code review, but somehow got the program to stop working as intended. Supposed to break loop after 5 games, only does this sometimes.

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

Upvotes: 0

Views: 961

Answers (2)

Ivaylo
Ivaylo

Reputation: 2192

I think if you properly account for the result, it will be fine:

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"

Upvotes: 2

jonrsharpe
jonrsharpe

Reputation: 122154

You only break if one player or the other gets 4 wins. It's much easier to use a for loop to limit the rounds:

for _ in range(5):

Upvotes: 1

Related Questions