0

I'm making a basic version of pokemon, and I have a function that looks like this:

global userhp, comphp
userhp = 100
comphp = 100

def doturn(attacker, enemy, move, attackerhp, enemyhp):
from random import randint
if move == 1:
    dmg = randint(18, 25)
    enemyhp -= dmg
    print("\t" + attacker, "have done", str(dmg), "damage")
    print("\t" + enemy, "now have", enemyhp, "health\n")
if move == 2:
    dmg = randint(8, 35)
    enemyhp -= dmg
    print("\t" + attacker, "have done", str(dmg), "damage")
    print("\t" + enemy, "now have", enemyhp, "health\n")
if move == 3:
    dmg = randint(15, 22)
    attackerhp += dmg
    print("\t" + attacker, "have healed", str(dmg), "health")
    print("\t" + attacker, "now have", attackerhp, "health\n")

Here is an example call:

doturn(user, comp, 3, userhp, comphp)

The problem I'm having is that changing attackerhp and enemyhp doesn't affect userhp and comphp. It stays at 100, and the game is unable to progress. I need a way of changing the global variables, but also doing it without hard-coding the variables into the function, because that way it would only work for the user or the computer.

I've been able to solve it, but my solution was to return the damage value and applying that to userhp and comphp outside this function. I could write separate functions for user and comp, or have an if statement check who's turn it is and do it that way, but I'd quite like to keep this compact. Any feedback would be appreciated.

1
  • That indentation doesn't make any sense. Commented Aug 23, 2015 at 14:16

1 Answer 1

1

So you don't need to put the global statement in the first line. You only need that inside any function where you change the variable.

My understanding is that your issue is that the user or the computer could be either the attacker or the defender? Have I got this right?

In this case, why not make an object for attacker and defender, which stores their name and hp. That way, you can update attacker.hp and defender.hp inside the function without worrying about which is the user and which is the defender.

Something like this

class Player:
  def __init__(self, name, hp):
    self.name = name
    self.hp = hp

And get rid of the global variables altogether.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.