Need help improving number guessing game

feba febaen at gmail.com
Mon Dec 15 13:29:49 EST 2008


Alright! This is feeling more like it.

#!/usr/bin/python
#Py3k, UTF-8
import random

def setup(game, minr=1, maxr=99):
    #minr, maxr make minimum and maximum. Can be adjusted.
    game['minr'], game['maxr'] = minr, maxr
    game['gcount'] = 0 #Reset guess count
    game['target'] = random.randint(minr, maxr)

def playerswitch(game):
    #Player Switch
    #if player's a witch: burn(her)
    if game['player'] == game['player1']:
        game['player'] = game['player2']
    else:
        game['player'] = game['player1']

def youwin(game):
    if game['pnum'] == 1:
        print("CONGRATULATIONS! IT TOOK YOU %s GUESSES" % game
['gcount'])
    else:
        if game['player'] == game['player1']:
            game['p1sc'] += 1
        else:
            game['p2sc'] += 1
        end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s"
        #Can the following line be more compact?
        print(end % (game['player'], game['p1sc'], game['p2sc']))

def playagain(game):
    playover = input("PLAY AGAIN? Y/N: ")
    if playover.strip().lower() == "y":
        game['play'] = True
        setup(game)
    else:
        print("GOOD BYE. PLAY AGAIN SOON!")
        game['play'] = False

def autofinish(game):
    if game['maxr'] - game['minr'] == 2:
        print("...ONLY ONE OPTION LEFT!")
        youwin(game)
        playagain(game)

def numplayers(game, prompt="1 OR 2 PLAYERS?\n> "):
    while True:
        num = input(prompt)
        try:
            num = int(num)
        except ValueError:
            print("BAD VALUE")
        else:
            break
    game['pnum'] = num

def guesses(game):
    game['guess'] = int(input("[%s-%s]%s>> " \
    #keeps user aware of who's turn it is, and the range
    % (game['minr'], game['maxr'], game['player'])))

def guesscheck(game):
    if game['guess'] == game['target']:
        if game['pnum'] == 1:
            game['gcount'] += 1
        youwin(game)
        playagain(game)
    elif game['guess'] >= game['maxr']:
        print("NUMBER MUST BE IN RANGE")
        guesses(game)
        guesscheck(game)
    elif game['guess'] <= game['minr']:
        print("NUMBER MUST BE IN RANGE")
        guesses(game)
        guesscheck(game)
    elif game['guess'] > game['target']:
        print("TOO HIGH")
        if game['pnum'] == 1:
            game['gcount'] += 1
        game['maxr'] = game['guess']
    else:
        print("TOO LOW")
        if game['pnum'] == 1:
            game['gcount'] += 1
        game['minr'] = game['guess']

def guessing(game):
    guesses(game)
    guesscheck(game)
    if game['pnum'] == 2:
        playerswitch(game)
    autofinish(game)

def main(game=None):
    if game is None:
        game = {}
    print("WELCOME TO THE SUPER NUMBER GUESSING GAME!")
    numplayers(game)
    game['play'] = True
    game['player1'], game['player2'] = "P1", "P2"
    game['player'] = game['player1']  # P1 goes first
    #Scores start at 0
    game['p1sc'], game['p2sc'], game['gcount'] = 0, 0, 0
    setup(game)

    while game['play'] is True:
        guessing(game)

if __name__ == "__main__":
    main()


first off, I want to thank all of you for your help with this. I
really don't think I could've learned all of this out nearly as
quickly by reading tutorials and documentation, let alone had anything
near the grasp I have on it now. '''This''' is why I like learning by
doing. The only things I still don't really understand are .strip
().lower(), and try/except/else, and I plan on looking them up before
I do anything else. In the past few hours I've gone from not having a
clue what the whole {'fred': 0, 'barney': 0} thing was about to being
able to fully understand what you're talking about, and put it into
practice

2; I feel like this process is going quicker and quicker every time I
refine it. It also feels like it's getting easier to solve various
bugs when <s>I create them</s> they pop up. It might be because I'm
getting into it and having more fun, because the refinements are less
major each time, because they're easier to pick up, or some
combination of all of those. Either way, I feel very excited about it.

3; I found some very helpful gedit plugins. While I was in
preferences, I noticed you can have it highlight the margin; so I set
that to 75 to try to keep from going over the character limit/line
recommendation. Draw Spaces, a plugin, showing spaces is also pretty
helpful. I also found a python auto complete plugin which I haven't
used so far, but which looks very promising, along with a terminal
program (Keeps me from juggling windows, anyway)

4; I readded the counter for one player games. Out of curiosity, what
do you think of:

if game['pnum'] == 1:
    game['gcount'] += 1

? I'm not sure whether this is good or bad. On the one hand, it keeps
it from adding to gcount without needing to, on the other hand it
seems like it might be more wasteful to check pnum than to just add to
gcount. It also makes it harder to adjust it to show gcount in two
player mode, if you want to do that for some reason.

5; I added the ability for it to automatically complete when there's
only one option left. I was amazed' I was actually going to ask for
advice on how to do it here. I was going to say "I was thinking (blah
blah)", but then I just typed it in, and it worked flawlessly. This
goes back to one, but I'm very excited, and thankful.

6; can anyone think of anything else to add on to/do with this game?
With the minr/maxr display, multiplayer, score keeping, and
automation, I'm just about all of ideas. All I can think of left to
add is 3 and 4 player modes, or a fork where player 2 can't win
(kekekekeke. Though I'm not sure how to do it...), both of which I
feel are somewhat pointless for a game like this. If I can't learn
anything more from it, I will probably go back to reading python
guides for a bit, and then try to make something else.





More information about the Python-list mailing list