Need help improving number guessing game

feba febaen at gmail.com
Mon Dec 15 17:40:08 EST 2008


Spent a bit more time looking over suggestions and working out some
annoyances.


import random

def customrange(game, lowunsafe=True):
    game['defrang'] = False #Keeps setup from changing range to
defaults
    while lowunsafe: #makes sure that the low number is positive
        picklow = int(input("PLEASE PICK THE LOW NUMBER: "))
        if picklow < 0:
            print("LOW NUMBER MUST BE POSTIVE")
        else:
            lowunsafe = False
    pickhigh = int(input("PLEASE PICK THE HIGH NUMBER: "))
    if pickhigh - picklow <= 2: #see setup().
        print("HIGH MUST BE AT LEAST THREE GREATER THAN LOW")
    else:
        game['minr'], game['maxr'] = picklow, pickhigh
        print("RANGE IS [%s-%s]!" % (game['minr'], game['maxr']))

def wantcustom(game, unsure=True):
    #Allows user to decide their own range for guessing.
    while unsure:
        pickrange = input("WOULD YOU LIKE TO CREATE A CUSTOM RANGE? Y/
N: ")
        if pickrange.lower() == "n":
            game['minr'], game['maxr'] = 1, 99 #Default range. see
setup
            unsure = False
        elif pickrange.lower() == "y":
            customrange(game)
            unsure = False
        else:
            print("INVALID INPUT")

def samesettings(game, unsure=True):
    while unsure:
        keepset = input("USE SAME SETTINGS? Y/N: ")
        if keepset.lower() == "y":
            game['minr'], game['maxr'] = 1, 99 #Default range. see
setup
            unsure = False
        elif keepset.lower() == "n":
            wantcustom(game)
            numplayers(game)
            unsure = False
        else:
            print("INVALID INPUT")

def setup(game):
    #minr, maxr make minimum and maximum. Can be adjusted.
    #Make sure that maxr - minr is at least 3.
    #1 or less would be impossible. 2 would only have one guess for
victory
    #The first would be unplayable, the second would play itself
    if game['maxr'] - game['minr'] <= 2:
        raise ValueError("INVALID RANGE!") #If this fails, check line
43
    game['gcount'] = 0 #Reset guess count
    game['target'] = random.randint(game['minr'], game['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"
        print(end % (game['player'], game['p1sc'], game['p2sc']))

def playagain(game, unsure=True):
    while unsure:
        playover = input("PLAY AGAIN? Y/N: ")
        if playover.lower() == "y":
            game['play'] = True
            samesettings(game)
            setup(game)
            unsure = False
        elif playover.lower() == "n":
            print("GOOD BYE. PLAY AGAIN SOON!")
            game['play'] = False
            unsure = False
        else:
            print("INVALID INPUT")

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

def numplayers(game, unsafe=True, prompt="1 OR 2 PLAYERS?\n> "):
    while unsafe:
        while True:
            num = input(prompt)
            try: #Make sure that num is valid
                num = int(num)
            except ValueError:
                print("BAD VALUE!")
            else:
                break
        if num == 1 or 2: #ONLY allow 1 or 2P.
            unsafe = False
        else:
            print("INVALID INPUT")
    game['pnum'] = num

def guesses(game, unsafe=True):
    while unsafe:
        while True:
            try:
                guess = int(input("[%s-%s]%s>> " \
                #keeps user aware of who's turn it is, and the range
                % (game['minr'], game['maxr'], game['player'])))
            except ValueError:
                print("BAD VALUE!")
            else:
                break
        if guess >= game['maxr']:
            print("NUMBER MUST BE IN RANGE")
            guesses(game)
            guesscheck(game)
        elif guess <= game['minr']:
            print("NUMBER MUST BE IN RANGE")
            guesses(game)
            guesscheck(game)
        else:
            unsafe = False
    game['guess'] = guess

def guesscheck(game):
    if game['guess'] == game['target']:
        if game['pnum'] == 1:
            game['gcount'] += 1
        youwin(game)
        playagain(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!")
    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
    wantcustom(game)
    numplayers(game)
    setup(game)

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

if __name__ == "__main__":
    main()



This is basically finding a balance between being annoyed by prompts
and being annoyed by having to quit and restart. Given the sorts of
people who will play this longer than to find out how it works are the
sort of people who find spreadsheets and powerpoints and EVE online
fun, I'll go with prompts.



More information about the Python-list mailing list