Reputation:
I'm working on a text based game, but I haven't found a very efficient solution to my fighting system yet. I currently have my statements set up sort of like this:
class Weapon1:
damage = 4
price = 5
class Weapon2:
damage = 4
price = 5
class Enemy1:
damage = 2
health = 5
class enemy2:
damage = 3
health = 6
def fight():
Weapon = raw_input("What weapon would you like to use?")
if Weapon == "Weapon 1":
if enemy = "Enemy1":
Enemy1.health -= Weapon1.damage
else:
Enemy2.health -= Weapon1.damage
else:
if enemy = "Enemy1":
pass
else:
pass
I have a lot more enemies and classes than that, so I would like to have a single statement that can reference classes' properties using variables. I decided not to upload the actual function due to it being over 100 lines long. The pseudocode for what I'm after would look something like this:
class pistol:
damage = 4
price = 5
class cannon:
damage = 4
price = 5
class Enemy1:
damage = 2
health = 5
class enemy2:
damage = 3
health = 6
def fight():
Weapon = raw_input("What weapon would you like to use?")
enemy.health -= weapon.damage
Upvotes: 3
Views: 56
Reputation: 241
make the weapon,enemy class and initiate before doing fight()
class weapon:
def __init__(self,d,p):
self.damage = d
self.price = p
def initiate():
pistol = weapon(4,5)
#....
Upvotes: 1
Reputation: 249123
You can use a simple dict
, here with namedtuple
to make the code easier to read:
from collections import namedtuple
Weapon = namedtuple('Weapon', ['damage', 'price'])
weapons = {
'pistol': Weapon(4, 5),
'cannon': Weapon(4, 5),
# ...
}
def fight():
weapon_name = raw_input("What weapon would you like to use?")
enemy.health -= weapons[weapon_name].damage
Upvotes: 1