Advertisement

Hard to explain in title. But vaguely, variable of same name for everything.

Started by October 17, 2015 04:07 AM
1 comment, last by Calcious 9 years, 2 months ago

(Extreme Newbie to python)

Topic probably didn't make sense, so i'm just gonna show an example.

Say that a character has an ability that they can use. The ability scales with their magical affinity or whatever.

Don't question the var name.

magicalblahahaha = (character[attackp] * 2 - defensep)

Basically, this attack damage is calculated by subtracting the player defense point(defensep) from the one using the ability attack point(attackp) * 2

to get the damage output.

How do I make it so that Python some how auto replaces the variable character with the user using it? Btw, all of the users are dictionary with values inside like attackp and such.

That's what functions are for. In this case, the function would hold the logic, and would have the character passed in as a parameter.

Observe:


def calculateMagicalBlahahahaha(characterToCheck, attackp, defensep):
    return (characterToCheck[attackp] * 2 - defensep)

def main():
    frodo_baggins = [....]
    samwise_gamgee = [....]

    attackp_meow = ...
    defensep_wuff = ...

    frodo_blahahahaha = calculateMagicalBlahahahaha(frodo_baggins, attackp_meow, defensep_wuff)
    samwise_blahahahaha = calculateMagicalBlahahahaha(samwise_gamgee, attackp_meow, defensep_wuff)

That said, the characters shouldn't be lists - they should be classes.

You should be able to access it like this:


def calculateMagicDamage(defendingCharacter, attackingCharacter):
    return (attackingCharacter.attackPower * 2 - defendingCharacter.defensePower)

def main():
    amountOfDamageDealtToFrodoBySam = calculateMagicDamage(frodo_baggins, samwise_gamgee)
    amountOfDamageDealtToSamByFrodo = calculateMagicDamage(samwise_gamgee, frodo_baggins)

And if you made the function itself be a member of the class, it'd look like this:


def main():
    samwise_gamgee.attack(frodo_baggins)
    frodo_baggins.attack(samwise_gamgee)
Advertisement

I see, thank you


This topic is closed to new replies.

Advertisement