2

I'm fairly new to the programming game; I'm 3/4 of the way through Learn Python the Hard Way and I had a question about a little text-based game I made... So in this game my guy is stranded on a desert island and you have the option(raw input) of going left right or into the jungle. After choosing a direction, you're given the option to choose how many miles to walk. Each direction is supposed to have a different end result (and mile distance).

If you enter a number that is less than the number of miles to the destination, you're prompted with a choice to either "turn around or "keep going". If you enter turn around, you're taken back to the beginning, where you're again asked to choose a direction. If you enter keep going, the program returns to miles(), where you can choose a new amount of miles to walk.

def miles():
        print "How many miles do you walk?"     
    miles_choice = raw_input("> ")
    how_much = int(miles_choice)    
    if how_much >= 10:
        right_dest()    
    elif  how_much < 10:
        turn()  
    else: 
        print "You can't just stand here..."
        miles() 

Ok so here's two questions:

  1. How would I make it so that if the user originally enters a number of miles less than the destination distance, and the second mile input + the first mile input == the amount of miles to the destination, it will add the inputs and run my destination function, not just repeat miles().

  2. Since all three final destinations will have different distances, should I write three separate mile functions? Is there a way to make it so that depending on the original direction chosen, miles() will run the different endpoints?

I'm sorry if this doesn't make a lick of sense... I'm still learning and I'm not sure how to fully explain what I'm trying to get across.

msvalkon
  • 11,887
  • 2
  • 42
  • 38

3 Answers3

0

You could store the amount of miles to walk in each direction in a dict, and then check the dict to see if the user has walked far enough:

distances = {
    'right': 7,
    'left': 17,
    'forward': 4
}

direction_choice = raw_input("> ")
miles_choice = raw_input("> ")

if how_much >= distances['direction_choice']:
    right_dest()    
elif  how_much < distances['direction_choice']:
    turn()  
else: 
    print "You can't just stand here..."
    miles()

Be sure to properly validate and cast the user input, which I have not addressed. Good luck!

dotancohen
  • 30,064
  • 36
  • 138
  • 197
0

I don't fully understand the requirements (the intended behavior and constraints). However, you might consider passing a parameter to your function (through and argument) to convey the maximum number of miles which the play could go in that direction).

For example:

#!/usr/bin/env python
# ...
def miles(max_miles=10):
    print "How many miles do you walk?"
    while True:     
        miles_choice = raw_input("> ")
        try:
            how_much = int(miles_choice)
        except ValueError, e:
            print >> sys.stderr, "That wasn't a valid entry: %s" % e
            continue

        if max_miles > how_much > 0:
            break
        else:
            print "That's either too far or makes no sense"
    return how_much

... in this case you pass maximum valid number of miles into the function through the "max_miles" argument and you return a valid integer (between 1 and max_miles) back.

It would be the responsibility of this function's caller to then call right_dest() or turn() as appropriate.

Note that I've removed your recursive call to miles() and replace it with a while True: loop, around a try: ... except ValueError: ... validation loop. That's more appropriate than recursion in this case. The code does a break out of the loop when the value of how_much is valid.

(By the way, if you call miles() with no parameter then the argument will be set to 10 as per the "defaulted argument" feature. That's unusual to Python (and Ruby) ... but basically makes the argument optional for cases where there's a sensible default value).

Jim Dennis
  • 17,054
  • 13
  • 68
  • 116
0

@Question #1: I used Class intern variables. You will maybe need them for further programming parts and should take it to zero when you are done on one direction, to start with zero for next step/lvl.

@Question #2: Dictionaries are the best way to do so,self.dest. Parameter pos used as key to get the value from the dictionary.

class MyGame:
    def __init__(self):
        self.current_miles = 0
        self.dest = {'Left' : 10, 'Into the jungle' : 7, 'Right' : 22}

    def miles(self,pos):

        print "How many miles do you walk?"     
        miles_choice = raw_input("> ") 
        self.current_miles += int(miles_choice) 

    if self.current_miles >= self.dest.get(pos):
            self.miles("Right")    
    elif  self.current_miles < self.dest.get(pos):
        print "you went "+ str(self.current_miles) + " miles"
    else: 
        print "You can't just stand here..."
        self.miles(pos) 

mg = MyGame()
mg.miles('Into the jungle')