Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changeable function call from dict

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()
like image 266
Nate B. Avatar asked Jul 01 '26 17:07

Nate B.


2 Answers

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()
like image 173
Mark Beilfuss Avatar answered Jul 03 '26 07:07

Mark Beilfuss


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.

like image 25
Eric Duminil Avatar answered Jul 03 '26 08:07

Eric Duminil