How do I get my go function to work properly?

72 views Asked by At

trying to make a text adventure here. I was setting up the actions module, and testing out the movements when the code keeps telling me my functions are not defined even though I defined them in the code itself (wouldn't recognize it in the player module) I am stuck, any ideas?

Error:

go_north(self)
NameError: name 'go_north' is not defined

Code:

def go(self, dx, dy):
        self.location_x += dx
        self.location_y += dy
        print(world.tile_exists(self.location_x, self.location_y).intro_text())

        def go_north(self):
            self.go(dx=0, dy=-1)

        def go_south(self):
            self.go(dx=0, dy=1)
 
        def go_east(self):
            self.go(dx=1, dy=0)
 
        def go_west(self):
            self.go(dx=-1, dy=0)

game = "play"
while game == "play":
    x = input()
    y = " is not a valid command"
    string = x + y
    
    if x == "go north":
        go_north(self)

    if x == "go south":
        go_south(self)

    if x == "go east":
        go_east(self)

    if x == "go west":
        go_west(self)

    else:
        print(string)
4

There are 4 answers

0
Raven On

Try self.go_north() instead of go_north(self)

0
Kunal Katiyar On

Common mistake from python beginners - A function defined in a class is not global. You first to initialize a "go" instance:

var_name = go()

Then call the function by its variable name:

var_name.go_north()

Also, "self" does not need to be passed into the function when calling it.

In addition, when calling a class function inside of the class, call it using self:

self.whatever()

To be able to pass variables into a class function, simply do it as normal, but remember (when calling it) to exclude the "self"!

0
Emrah Sulejmanovic On

Kunal Katiyar is right, but also don't forget to list all functions(define them) before calling any, i had an error and struggled for 30 minutes because a function i called earlier in the code was defined later!

1
Rohak Vaghode On

You could make the function a global so it is accessible