back with more issues

Dave Angel davea at davea.name
Mon Aug 12 01:54:38 EDT 2013


Kris Mesenbrink wrote:

> import random
>
> def player():
>     hp = 10
>     speed = 5
>     attack = random.randint(0,5)
>
The net resut of this function is nothing.  It assigns values, then
they're lost when the function returns.  A function is the wrong way to
deal with these three names.

> def monster ():
>     hp = 10
>     speed = 4

Same here.

>
> def battle(player):

You probably want to have two parameters, player and monster

>     print ("a wild mosnter appered!")
>     print ("would you like to battle?")
>     answer = input()
>     if answer == ("yes"):
>         return player(attack)
>     else:
>         print("nope")

This function makes no sense to me.  A function should have three
well-defined pieces:  what are its parameters, what does it do, what are
its side-effects, and what does it return.  This function is confusing
on all of those.

>
>
> battle()
>
>
> ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
>
> this was a variation on a code that you guys already had helped me with,in the long run i plan to incorporate them together but as it stand i don't know how to call a specific variable from one function (attack from player) to use in another function (battle). what i want is to be able to use the variables from both player and monster to use in battle. any idea's?

What you should want is a class for each type of character. At its
simplest, the class can be a storage place for related named
attributes.

You could make a class Player, which defines attributes called hp,
speed, and attack.  Then later on you can refer to one of those
attributes with  synatax like  james.attack

class Player:
    def __init__(self):
        self.hp = 10
        self.speed = 5
        self.attack = random.randint(0,5)

Now, you create a player by
james = Player()

and the monster by
behemoth = Monster()

and you pass them into the function battle, by

result = battle(james, behemoth)

Inside the function, you'd say  player.attack to see that random value. 
 And monster.speed to see behemoth's speed.


-- 
DaveA




More information about the Python-list mailing list