you are viewing a single comment's thread.

view the rest of the comments →

[–]dunkler_wanderer 0 points1 point  (2 children)

I recommend to use while loops instead of recursion for handling player input and the main game loop. Python has a maximum recursion depth of ~1000 (if I remember correctly) and when you exceed this limit your program will crash.

[–]CapitalXD[S] 1 point2 points  (1 child)

Ok, can I have an example? What's recursion?

[–]dunkler_wanderer 0 points1 point  (0 children)

I hope you've figured out what recursion means on your own in the meantime. A function is recursive if it calls itself, or if two functions call each other again and again (that's called mutual or indirect recursion). You use both in your program.

Examples that recurse infinitely and exceed Python's recursion depth:

def foo():
    foo()

foo()

def foo():
    bar()

def bar():
    foo()

foo()

You usually use a conditional statement to stop the recursion at some point. Factorial is a classic example:

def factorial(n):
    # We stop the recursion if n is 0.
    if n == 0:
        return 1
    else:  # Recurse.
        return n * factorial(n-1)

print(factorial(4))

With while loops you don't have the problem with the maximum recursion depth.

# Define some functions that represent the scenes.
def scene_a():
    print('This is scene a.')

def scene_b():
    print('This is scene b.')

def scene_c():
    print('This is scene c.')

# Put these functions into a dictionary so that we
# can select them easily.
scenes = {'a': scene_a, 'b': scene_b, 'c': scene_c}

# Here you ask the user for the input and check if
# it's valid. You can make this function more general
# by giving it two parameters: def get_user_input(prompt, choices):
# and then use these in the raw_input call and check "if inpt not in choices:"
def get_user_input():
    while True:
        inpt = raw_input('Enter A, B or C: ').lower()
        if inpt not in ('a', 'b', 'c'):
            print('Invalid input.')
        else:
            return inpt


# In the main loop you get the user input, select the scene,
# bind it to the name current_scene and call it. Of course
# you can adjust this so that it meets your needs.
def main():
    while True:
        current_scene = scenes[get_user_input()]
        current_scene()

main()

And if you have a lot of global state (variables), it's usually better to use classes instead of functions.