user7375572
user7375572

Reputation:

How do I work player health In Python 2.7?

I am unsure how to make a health system for a class player to get killed after getting hit three times. Can someone please help? I am using Python 2.7 to code. I currently have

if pygame.sprite.spritecollideany(player, opponents):
   player.kill()

and i was considering using a variable

player.HP = 3

but it won't die!

if pygame.sprite.spritecollideany(player, opponents):
   player.HP -1
   if player.HP == 0:
      player.kill

but, like i said, it won't die but the code works. It was killing until i added the new system, and now it won't. Can somebody help? Thanks.

Upvotes: 0

Views: 1744

Answers (1)

Will
Will

Reputation: 4469

As @juanpa.arrivillaga said in a comment, you need to assign the decremented value of player.HP or else, you are doing subtraction and throwing away the value. You need to change:

player.HP -1

to

player.HP -= 1

Here's an example:

>>> class A:
...   def __init__(self, val):
...     self.val = val
...   def decrement(self):
...     self.val - 1              # <- Does not reassign decremented value
...     print self.val
...
>>> a = A(10)
>>> a.decrement()
10
>>> a.decrement()
10
>>> a.decrement()
10
>>> a.decrement()
10
>>> class A:
...   def __init__(self, val):
...     self.val = val
...   def decrement(self):
...     self.val -= 1             # <- Does reassign value
...     print self.val
...
>>> a = A(10)
>>> a.decrement()
9
>>> a.decrement()
8
>>> a.decrement()
7
>>> a.decrement()
6

Upvotes: 1

Related Questions