> .strip() returns a copy of the string without leading and ending
whitespaces (inlcuding newlines, tabs etc).

Ahh. I had removed it because it didn't seem to do anything, but I've
readded it.

And I understand your dictionary stuff correctly now, I think, and I
worked it in. Currently, I have:


import random

def safeint(prompt="y"):
    while True:
        x = input(prompt)
        try:
            x = int(x)
        except ValueError:
            print("BAD INPUT!")
        else:
            break
    return x

def safestr(prompt="y"):
    while True:
        x = input(prompt)
        try:
            x = str(x)
        except ValueError:
            print("BAD INPUT!")
        else:
            break
    return x

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 = safeint(prompt="PLEASE PICK THE LOW NUMBER: ")
        if picklow < 0:
            print("LOW NUMBER MUST BE POSITIVE")
        else:
            lowunsafe = False
    pickhigh = safeint(prompt="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:
        tryrange = safestr(prompt=\
                           "WOULD YOU LIKE TO CREATE A CUSTOM RANGE?
"\
                            +"Y/N: ")
        if tryrange.strip().lower() == "n":
            game['minr'], game['maxr'] = 1, 99 #Default range. see
setup
            unsure = False
        elif tryrange.strip().lower() == "y":
            customrange(game)
            unsure = False
        else:
            print("INVALID INPUT")

def samesettings(game, unsure=True):
    while unsure:
        keepset = safestr(prompt="USE SAME SETTINGS? Y/N: ")
        if keepset.strip().lower() == "y":
            game['minr'], game['maxr'] = 1, 99 #Default range. see
setup
            unsure = False
        elif keepset.strip().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'] is 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:
        game['player']['score'] += 1
        end = "CONGRATULATIONS %s! SCORE -- P1:%s P2:%s"
        print(end % (game['player']['name'],\
             game['player1']['score'], game['player2']['score']))

def playagain(game, unsure=True):
    while unsure:
        playover = safestr(prompt="PLAY AGAIN? Y/N: ")
        if playover.strip().lower() == "y":
            game['play'] = True
            samesettings(game)
            setup(game)
            unsure = False
        elif playover.strip().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):
    while unsafe:
        num = safeint(prompt="1 OR 2 PLAYERS?\n> ")
        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:
        guess = safeint(prompt="[%s-%s]%s>> " % \
                        #Shows range
                        (game['minr'], game['maxr'],\
                        #And which player's turn
                        game['player']['name']))
        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):
    player1, player2 = dict(name="P1",score=0), dict
(name="P2",score=0)
    if game is None:
        game = dict(
            player1 = player1,
            player2 = player2,
            player = player1,
            play = True
            )
    print("WELCOME TO THE SUPER NUMBER GUESSING GAME!")
    wantcustom(game)
    numplayers(game)
    setup(game)

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

if __name__ == "__main__":
    main()



>rewrite it once again using objects instead of dicts ?

I'd need to find out how those work, and I have a list of python stuff
to read piling up anyway... That said, I think for something like
that, something that's not a major flaw, I'd prefer to make something
else, and maybe work on this again later on. There is only so much
guessing numbers one person can take.
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to