3

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
1
  • 2
    That's not how you use classes. Commented Mar 4, 2015 at 4:03

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

So if the user inputs "cannon" this would do 4 damage to whoever happened to be the enemy? Also, can this be used with Booleans? I have an owned attribute.
Also, what does namedtuple do?
1

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)
    #....

Comments