I am currently using OOP in python to program a game. I have created a class with attributes and methods. I wanted to do basic movement where if the user types "go north" it will move to the north square. However it is saying i have an error and that north isn't defined. Here is my code:
class square():
def __init__(self, action, square_no, north, east, south, west):
self.action = action
self.square_no = square_no
self.north = north
self.east = east
self.south = south
self.west = west
def user_action(action):
action = input("---").lower()
square.movement(action, north)
def Help():
print("Commands are: \n Go(north/ east /south /west) \n Mine \n Craft (object) \n Look around \n Collect (blueprint)\n Fix (wing/ thruster/ engine/ battery/ fuel tank) \n Save \n Info \n You will see this symbol when you are expected to type something ---")
square.user_action(action)
def movement(action, north):
if action == "go north":
print(north)
elif action == "info":
square.Help()
else:
print("You can't do that here.")
square.user_action(action)
action = ""
square1 = square(action, 1, 0, 2, 4, 0)
print(square1)
square1.user_action()
Thanks
You are missing self
in various places for the code to work as intended
class square():
def __init__(self, action, square_no, north, east, south, west):
self.action = action
self.square_no = square_no
self.north = north
self.east = east
self.south = south
self.west = west
def user_action(self):
action = input("---").lower()
self.movement(action)
def Help(self):
print("Commands are: \n Go(north/ east /south /west) \n Mine \n Craft (object) \n Look around \n Collect (blueprint)\n Fix (wing/ thruster/ engine/ battery/ fuel tank) \n Save \n Info \n You will see this symbol when you are expected to type something ---")
self.user_action(action)
def movement(self,action):
if action == "go north":
print(self.north)
elif action == "info":
square.Help()
else:
print("You can't do that here.")
square.user_action(action)
action = ""
square1 = square(action, 1, 0, 2, 4, 0)
print(square1)
square1.user_action()
Try using self.north.
square.movement(action, self.north)
You are trying to use a variable called north which isn't set. But you do have the variable north in your class which you have to acces via self.<variable_name>.
I hope it solves your problem
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.