I'm relatively new with a decent amount of experience and I'm trying to make a text based adventure, I'm making a fighting system and wish to have enemy's that have different abilities. Instead of recreating the fight for a different enemy every time, I'm trying to use interchangeable dictionaries for each enemy. My goal is to create a function call that varies depending on what enemy is in the fight without getting into objects. I have an example below and would like to know if there is a way to do something similar.
wolf = {'ability': 'bite'}
bear = {'ability': 'claw'}
enemy = {}
def claw():
print('stuff')
def bite():
print('different stuff')
def use_ability():
enemy = wolf
enemy['ability']()
use_ability()
In python functions are first class objects. You can just use them as values in your dictionary.
wolf = {'ability': bite}
bear = {'ability': claw}
However be careful as there is no forward referencing in python. So make sure you define your functions before you assign them to a dictionary.
def claw():
print('stuff')
def bite():
print('different stuff')
wolf = {'ability': bite}
bear = {'ability': claw}
def use_ability():
enemy = wolf
enemy['ability']()
use_ability()
You can do it:
def claw():
print('stuff')
def bite():
print('different stuff')
wolf = {'ability': bite}
bear = {'ability': claw}
def use_ability(enemy):
enemy['ability']()
use_ability(wolf)
# different stuff
It really doesn't mean you should do it this way, though.
Use Object-Oriented programming. If you only want to use dicts and functions, you probably should write Javascript instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With