1

So I am creating a survival game, and I need to know how to loop back to a certain point in the code. I have wrapped the entire game in a function, but--now when in run it-- it just restarts itself.

import random
def game(choice1):
    print "You need to build a fire. the recipe is 5 stick and 3 coal."
    choice1 = raw_input("There are trees to your left and rocks to your right. Which way will you go?")
    if choice1 == "left" or choice1 == "Left":
        choice2a = raw_input("You go to the tree. Would you like to punch it?")
        if choice2a == "yes" or choice2a == "Yes":
            R = random.randint(1,11)
            print "You punched the tree " + str(R) + " times."
            if R <= 5:
                print "It did not fall down"
            elif R > 5:
                R2 = random.randint(0, 5)
                print"It fell down. It dropped " + str(R2) + " sticks."
            elif choice2a == "no" or choice2a == "No":
                game(choice1)
    if choice1 == "right" or choice1 == "Right":
        choice2b = raw_input("You go to the rocks. Would you like to pick up the coal in them?")
    return game(choice1)
orde
  • 5,233
  • 6
  • 31
  • 33
Aubrey Champagne
  • 123
  • 1
  • 10

3 Answers3

0

I imagine you want to loop back to the first raw_input statement, if that is the case, you can use while loops as Celeo has pointed above. You will have to use an exit condition to escape the while loop once you are done looping.If you want to loop back to different parts of the program then I would recommend you write the code block as functions and call them as necessary.

nixtish
  • 3
  • 3
0

Try reading about while loops here: http://www.tutorialspoint.com/python/python_while_loop.htm

A while loop lets you repeat a code depending on a condition (while a condition is met, go back to the start).

CodeMonkey
  • 11,196
  • 30
  • 112
  • 203
0

To make such a game I would recommend using a (decision) state-machine. If the game is in a certain state, the player is asked the corresponding question and depending on the answer the game is moved to an other state. Each state should be implemented independently from the others, i.e. avoid deeply nested if/else constructs, this avoids errors and helps you to stay on top of things. You can also visualize/draw the game decision plan as a graph, where each node represents a state (or decision to be made) and each decision connects the node to an other state.

For your concrete example, you also need to keep track of what the player has collected so far, which is essentially an other state-system.

To implement such a state-based-game you can (ab-)use the python concept of generators. A generator is basically an object that returns 'items' with yield when queried with next(). A generator can provide a finite or an infinite amount of 'items', it can also return 'items' from an other generator with yield from.

Here an example implementation of your game: Be aware that this code works only with python3! It should be possible to translate it into python2 (perhaps even automatically), but I feel no strong urge to do so ATM ;)

import random
import collections


def main(backpack):    
    print("You need to build a fire. the recipe is 5 stick and 3 coal.")
    print("You have the following items in your backpack:")
    for k,v in backpack.items():
        print('  % 3d %s' % (v,k))

    #TODO: add check if we have collected enough here

    yield from choice1(backpack)

# tree or stone
def choice1(backpack):
    answer = input("There are trees to your left and rocks to your right. Which way will you go?")
    if answer.lower() in ('l', 'left'):
        yield from choice2a(backpack)
    elif answer.lower() in ('r', 'right'):
        yield from choice2b(backpack)
    else:
        print('I could not understand you. Answer with either "left" or "right".')
        yield from choice1(backpack)

# punch or not
def choice2a(backpack):
    answer = input("You go to the tree. Would you like to punch it?")
    if answer.lower() in ('y', "yes"):
        R = random.randint(1,11)
        print( "You punched the tree " + str(R) + " times.")
        if R <= 5:
            print("It did not fall down")
        else:
            R2 = random.randint(0, 5)
            print("It fell down. It dropped " + str(R2) + " sticks.")
            backpack['stick'] += R2
        yield from choice2a(backpack)
    elif answer.lower() in ('n', "no"):
        yield from main(backpack)
    else:
        print('I could not understand you. Answer with either "yes" or "no".')
        yield from choice2a(backpack)

# pick up or not      
def choice2b(backpack):
    answer = input("You go to the rocks. Would you like to pick up the coal in them?")

    # TODO: implement this
    yield main(backpack)



if __name__ == '__main__':

    backpack=collections.defaultdict(int)
    while True:
        next(main(backpack))

Each of the functions is a generator-function, i.e. a function that returns a generator. Each of them represents a game-state that requires a decision. The player-state (i.e. what the player has collected so far) is passed along as backpack which is a dictionary that contains the amount per item.

(yield from xyz() could be interpreted as a kind of goto command.)

PeterE
  • 5,715
  • 5
  • 29
  • 51
  • it looks cool but i really do not have a clue what this is so maybe if you could point me to a tutorial on this decision state-machine it would really help. – Aubrey Champagne Apr 15 '15 at 19:40
  • @AubreyChampagne: just google for 'finite state machine'. The wikipedia article also holds some useful information. State machines are not unique to games, but in the context of your game: 1) determine all 'states' the game (or perhaps rather the character) can be in, i.e. s1: standing in front of the fire pit s2: standing at the tree s3: standing by the stones. 2) for each state determine all actions the player can perform there and what state the game should be in after each action. This results in a nice graph that depicts the execution of your game. The rest are implementation details. – PeterE Apr 15 '15 at 20:34
  • i noticed in your code that you call a function that has not been defined yet. how is that possible? – Aubrey Champagne Apr 17 '15 at 00:51
  • By the time `main()` is called all functions have been defined. References to other functions (and variables, etc) are only checked at 'runtime', i.e. when the function is executed. Only syntax errors are thrown at 'parse-time'. Semantic errors only if the corresponding code is executed. – PeterE Apr 17 '15 at 05:40
  • how can i reference the function without the error? – Aubrey Champagne Apr 18 '15 at 00:25
  • I redid my version of it and I try to call a variable that is later in the code but it says that the variable is being called before defining – Aubrey Champagne Apr 18 '15 at 12:59
  • @AubreyChampagne: As the error message says: Variables have to be declared before they can be used. – PeterE Apr 18 '15 at 21:02