Search code examples
pythondirection

How do I update 'x' correctly?


So I'm working on a game, and here is my current code, which works fine:

print("Type directions() to see commands" )

def directions() :

    print("Type North, East, South or West to move" )
    move = input("North, East, South or West? ")
    if move == "North":
    north()
    elif move == "East":
    east()
    elif move == "South":
    south()
    elif move == "West":
    west()


def north():
    print("You moved North")
    x=0
    x=(x+1) 
    print("You are at co-ordinates", x, "x:0 y" )

However, I am aware that later there will be a problem as x would be reset for each direction. When putting x=0 at the top of the code and removing it from the def north() part, when running the code, Python gives me the error:

'UnboundLocalError: local variable 'x' referenced before assignment'

How can I code this so that 'x' is 0 to begin with, but can be altered by def functions?


Solution

  • You can do one of 2 things: either use a global variable (which should be mostly avoided), or use return values. The global method:

    x=0
    .
    .
    def directions():
        .
        .
    def north():
        global x
        x=x+1
        print("moved north...")
    

    or, the return value:

    def directions():
        current_location = 0
        .
        .
        if move == "North":
             current_location = North(current_location)
        .
        .
    def North(location):
        print("moved north...")
        return location+1
    

    Judging by your question and the existence of y, you can do the following:

    def directions():
    .
    .
        if move == "North":
            (x,y) = North(x,y)
    .
    .
    def North(x,y):
        return (x+1,y)
    def East(x,y):
        return (x,y+1)
    def South(x,y):
        return (x-1,y)