2

for some reason when the game reaches gold room it doesn't work right. when i enter any number i get the death message 'man, learn to type a number'

thanks

from sys import exit

def gold_room():
    print 'this room is full of gold, how much do you take?'

    next = raw_input('> ')
    if '0' in next or '1' in next:
        how_much = int(next)
    else:
        dead('man, learn how to type a number')


    if how_much < 50:
        print 'nice! your not too greedy. you win!'
        exit(0)
    else:
        dead('you greedy bastard!')


def bear_room():
    print 'there is a bear here.'
    print 'the bear has a bunch of honey'
    print 'the fat bear is in fromt of another door'
    print 'how are you going to move the bear?'
    bear_moved = False


    while True:
        next = raw_input('> ')

        if next == 'take honey':
            dead('the bear looks at you then pimp slaps you in the face')
        elif next == 'taunt bear' and not bear_moved:
            print 'the bear has moved from the door now. you can go through.'
            bear_moved = True
        elif next == 'taunt bear' and bear_moved:
            dead('the bear gets pissed off and chews your crotch off')
        elif next == 'open door' and bear_moved:
            gold_room()
        else:
            print 'i have no idea what that means.'


def bolofumps_room():
    print 'here you see the great evil bolofump'
    print 'he, it whatever stares at you and you go insane'
    print 'do you flee for your life or eat your head?'

    next = raw_input('> ')
    if 'flee' in next:
        start()
    elif 'head' in next:
        dead('well, that was tasty!')
    else:
        bolofumps_room()

def dead(why):
    print why, 'good job!'
    exit(0)


def start():
    print 'you are in a dark room'
    print 'there is a door to your left and right'
    print 'which one do you take?'

    next = raw_input('> ')

    if next == 'left':
        bear_room()
    elif next == 'right':
        bolofumps_room()
    else:
        dead('you stumble around the room until you starve to death')


start()

EDIT: typing one works, but 2 does not

neil
  • 203
  • 1
  • 4
  • 14
  • 1
    What output do you get when you put `print next` before the if statement in the gold_room function? – GWW Mar 14 '11 at 15:13
  • @GWW it prints the number i enter, then proceeds to the death message – neil Mar 14 '11 at 15:18
  • it's confusing, why is the if how_much < 50: part there if it kills you for entering more than 1? – neil Mar 14 '11 at 15:27

8 Answers8

9

You do this in gold_room:

next = raw_input('> ')
if '0' in next or '1' in next:
    how_much = int(next)
else:
    dead('man, learn how to type a number')

it checks only if '0' in next or '1' in next, so it's not really surprising that '2' does not work, right?

What you want goes along these lines

next = raw_input('> ')
try:
    how_much = int(next)
except ValueError:
    dead('man, learn how to type a number')

Doing this without exceptions is possible too, but please keep in mind that avoiding something as important and fundamental as exceptions is a really bad idea. I hope the book at least makes that clear later.

Anyways, so we know that int accepts only digits, so we simply check just that:

if next.isdigit():
    how_much = int(next)
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
  • 1
    oh yes extra credit says this:The gold_room has a weird way of getting you to type a number. What are all the bugs in this way of doing it? Can you make it better than just checking if “1” or “0” are in the number? Look at how int() works for clues. – neil Mar 14 '11 at 15:22
  • but i doubt i am meant to use try since the book hasn't even covered that yet – neil Mar 14 '11 at 15:23
1

If you consider what you should know at this moment in the tutorial, which consist of

  • parse arguments
  • read user inputs
  • using if/loop/while,
  • functions,
  • print
  • list and it's specific functions

you cannot use the magic functions like catching errors and or using "isdigit()".

By trying in an other example, I found that using "sorted" on a string, separates all the characters, and I will use that here.

What I thought about, my definition of a number will be "a string that contains only characters from 0 to 9". It's enough for the need of the exercise.

So my way was to remove all the digits from the input and check if it ended being empty. If it the case, it is an int, else if there are characters remaining, it is not.

def remove_all_occurences(char_list, item):
    value = "%d" % item  # convert to string
    while char_list.count(value) != 0:
        char_list.remove(value)
    return char_list


def is_int(input):
    """Personnal function to test if something is an int"""
    # The sort separates all the characters of the list
    characters_list = sorted(input)

    for num in range(0,10):
        characters_list = remove_all_occurences(characters_list, num)
    return len(characters_list) == 0
cladmi
  • 155
  • 1
  • 7
1

I could be missing something but this is how I changed it. Less code and runs good.

Def gold_room():
       Print("This room is full of gold. How much do you take?")

       choice = input('  ')
       next = int(choice)
       If next > 50:
            dead("Man, learn to type a number.")
       else:
             print("your not greedy. Good job!")
             exit(0)
HK boy
  • 1,398
  • 11
  • 17
  • 25
Ernie
  • 11
  • 1
  • Don't know why it didnt start at def even though I put it in the box when I posted this. – Ernie Jun 01 '19 at 14:30
0

My solution for the number Extra Credit checks that the characters of the input were integers like cladmi's, but goes through each character to see if it's an integer (via a maybe too obtuse boolean operation - it's simpler just to check if it's in '123456789'), logs the boolean value in a list, then goes this list with the and operator, returning True if all characters are in. I'm new to all this. I thought it was fairly novel, using only what we've learned so far, and it might be helpful for someone else stuck on neil's problem:

def is_integer(input):
    bool_list = [] # to hold the b
    truth = True 
    for i in input: 
        # tests if i is an integer, records the boolean in bool_list
        bool_list.append(i in str(range(0, 10)) and i != " " and i != ",")
    for t in bool_list: 
        truth = truth and t # 'adds' each boolean in bool_list 
    return truth # True if all are integers, False if not.
0

I personally did this in the gold_room function. This will help for whatever range you put. I hope this is not overdue.

elements = [ ] for i in range(0, 61): elements.append(i) next = int(raw_input("> ")) if next in elements: how_much = int(next) else:

0

I wasted a few days really thinking hard about how to solve this problem for the extra credit. I read up on 2 different things that could solve this for me: exception and isdigit. At first, I was determined to figure out how to figure this out without learning anything new and just using what we had covered at that point in the book and the info I could squeeze out of pydoc about int. I came up with a solution that involved a huge convoluted mess of lists, loops, Boolean stuff and blah blah blah and it ended up being like 60 lines long and an absolute headache to follow. I thought to myself, what would Zed say about this code if he looked at it and compared it to what I ultimately ended up with. I think its good that a few people on here, and maybe I'd include myself, were able to come up with complex, inventive and creative ways to get around this problem, because problem solving will obviously be a necessary skill for us, however, this big mess of code vs what I now believe to be what he was getting at is a no brainer. Do you think he intended you to waste a ton of time writing something ugly and hard to follow? or, based on the stuff we have heard him say, do you think he would rather you just look up a way to get it done in a neat and tidy way with 3 or 4 lines of very simple easy-to-read code? I ended up satisfied with this:

def gold_room():
    print "This room is full of gold! How much do you take?"
    try:
        next = float(raw_input(">"))
    except ValueError:
        dead("Man, learn to type a number.")
    if (next) < 50:
        print "Nice, you're not greedy, you win!"
        exit(0)
    elif(next) >= 50:
        dead("You greedy bastard!")

Anything works in it and it doesn't screw up. Just learn the new thing on your own.

0

I used the try and except statements too, but I don't think you need parenthesis around (next). You can also just use else instead of elif to keep your code cleaner.

def gold_room():
print "This room is full of gold! How much do you take?"
try:
    next = float(raw_input(">"))
except ValueError:
    dead("Man, learn to type a number.")
if next < 50:
    print "Nice, you're not greedy, you win!"
    exit(0)
else:
    dead("You greedy bastard!")
Koal
  • 9
  • 4
0

next is a built-in Python function, so you would want to avoid naming variables after it... Might not be the cause of your problem, but try changing the name of that variable.

Benjamin
  • 11,560
  • 13
  • 70
  • 119
  • [The documentation](http://docs.python.org/reference/lexical_analysis.html#keywords) disagrees with you. – Joachim Sauer Mar 14 '11 at 15:16
  • 1
    You previously mentioned "keyword" in your answer. And a built-in function on some type doesn't prevent him from using that name. It *should* be changed to avoid confusion, however. – Joachim Sauer Mar 14 '11 at 15:21
  • Not just to avoid confusion... It will also cause errors if it happens not to be defined (as a variable), or if you actually need to use `next()` and have used it as a variable instead... For instance, you would never use `int` as a variable name, although you could... – Benjamin Mar 14 '11 at 15:25