Need help improving number guessing game

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Dec 13 05:03:35 EST 2008


On Sat, 13 Dec 2008 00:57:12 -0800, feba wrote:

> I have one major problem with this; the 'replay' selection. It quits if
> you put in 0, as it should, and continues if you put in any other
> number. However, if you just press enter, it exits with an error. it
> also looks really ugly, and I'm sure there has to be plenty of better
> ways to do it.

Start by refactoring your code into small, easy to understand functions. 
For example, 

You mix in the same piece of code the logic for:

- error handling;
- starting a new game;
- quiting (although you use a function for this, well done);
- and game logic

and then you have to repeat it all again, almost word-for-word, for one 
player mode and two player mode.

Start with a high-level approach. The guessing game has the following 
structure:

while you want to play a game:
    play a game
    ask play again?

which in Python might look like this:

playing = True
while playing:
    play_one_game()
    playing = play_again()

def play_again():
    # For Python 3, change "raw_input" to "input".
    response = raw_input("Would you like to play again? y/n ")
    return response.strip().lower() == "y"

This function accepts *only* Y or y to play another game. Later, after 
you've got the game working, you can come back to this and modify it so 
that it accepts Yes or just enter on it's own. Make it work as simply as 
possible first, then come back and make it more complicated later.


Now do the same thing for playing one game. A single game in two player 
mode looks something like this:

pick a target number
start with one person as the guesser
until the target is guessed:
    guess a number
    let the other person be the guesser
    
which in Python might look like this:

def play_one_game():
    target = pick_target()  # you need to write this function
    guessed = False
    player = "Player One"
    while not guessed:
        guess = guess_number(player)  # you need to write this too
        if guess == target:
            guessed = True
        else:
            player = swap_player(player)  # player one <=> player two
    # When we exit the loop, player is the person who guessed correctly.
    if player == "Player One":
        p1score += 1
    else:
        p2score += 1


Best of all, you can change from two player mode to one player mode just 
by skipping the line "player = swap_player(player)". The rest of the code 
remains exactly the same, and you don't need to repeat everything.


Have a play around with this approach, and then come back to us if you 
need more hints.



-- 
Steven



More information about the Python-list mailing list