Reputation:
i know the title sounds confusing but bear with me. im coding my first game and i'm trying to set up a class for AI (called AI_mode) that my obj_creature class can use to get whatever kind of AI the creature entity needs. im passing a method from AI_mode as a variable to obj_creature. the method thats passed from AI_mode to obj_creature calls another method from inside the obj_creature class. heres some stripped down code:
class obj_creature:
def __init__(self, npc_mode=None):
self.npc_mode=npc_mode
def move(self, word):
print(word)
class AI_mode:
def ai_move_left(self):
self.owner.move("Hello World")
enemy_ai=AI_mode().ai_move_left
enemy_creature=obj_creature(npc_mode=enemy_ai)
if enemy_creature.npc_mode:
enemy_creature.npc_mode()
this code gives the error:
self.owner.move("Hello World")
AttributeError: 'AI_mode' object has no attribute 'owner'
im pretty sure .owner() isnt the correct thing to use there since i never declare obj_creature as the owner but im not really sure what to use in its place. when i try to declare obj_creature as the owner of AI_mode like so:
class obj_creature:
def __init__(self, npc_mode=None):
self.npc_mode=npc_mode
if npc_mode:
npc_mode.owner=self
i get this error:
npc_mode.owner=self
AttributeError: 'method' object has no attribute 'owner'
my end goal is to make it easy to assign a wide array of AI all from the same class to any kind of creature and be able to call whatever AI was assigned to it with the same command later on
Upvotes: 1
Views: 46
Reputation: 820
Find the below code design:
class obj_creature:
def __init__(self, npc_mode=None):
self.npc_mode=npc_mode
def move(self, word):
print(word)
class AI_mode:
def __init__(self, owner):
self.owner = owner
def ai_move_left(self):
self.owner.move("Hello World")
enemy_creature=obj_creature()
enemy_ai=AI_mode(enemy_creature)
enemy_creature.npc_mode=enemy_ai.ai_move_left
if enemy_creature.npc_mode:
enemy_creature.npc_mode()
Upvotes: 1