0

I am working on a small game in pygame and I have set up a health variable so each time my player gets hit by an enemy ship my health decreases by 25, however sometimes (If I my player rapidly across the screen) I am able to get this below 0 and it continues reducing by 25 into minus numbers.

Is there any way I can set it so the score cannot go below 0 once 0 is reached?

Heres my code so far:

for player in player_list:

    block_hit_list = pygame.sprite.spritecollide(player, block_list, True)

    for block in block_hit_list:
        health -= 25
        collision.play()

    if health < 0:
        health = max(value, 0)

    if health == 0:
        gameover.play()
        collision.stop()
        player_list.remove(player)
        all_sprites_list.remove(player)
        block_list.remove(block)
        all_sprites_list.remove(block)

Update

I have updated the code and now it seems to be functioning properly, not sure if I have used something which makes sense (If so, any improvements are welcomed) :( I am quite new to python.

Oscar
  • 97
  • 4
  • 14

3 Answers3

2

Try replacing the:

if health == 0:

    health = min

with:

if health < min:

    health = min

This should work. I hope this helps.

laurencevs
  • 923
  • 8
  • 20
  • I tried your suggestion but I encountered an error :( Ive managed to find a snippet of code which seems to be working, though. I have updated my code above. Thank you for your reply :) – Oscar Apr 20 '14 at 20:31
1

I am not too sure what you final goal is since this is only a snippet of code but you need to either increase your health variable or break the loop

if health == 0:
    break
Alexander Ejbekov
  • 5,594
  • 1
  • 26
  • 26
  • Thanks for your reply, I tried your suggestion but the numbers still ran below 0 :( However I have updated my code above to show something which seems to be working so far. – Oscar Apr 20 '14 at 20:29
  • 1
    Log all events where you decrease the value of health. My example applies only when the health variable hits exactly 0. But if for example in some case your health is 20, then 20-25 = -5, so the condition is never met. If that's the case then `if health <=0:` etc. – Alexander Ejbekov Apr 20 '14 at 20:33
  • Here is my full code: http://pastebin.com/2dccQ1f5 Sorry if I have made any mistakes, I am very new to python – Oscar Apr 20 '14 at 20:37
  • 1
    Well you were on the right track. Line 111 and 112 - put those inside the for loop and it works fine(an extra indent will do the job). Put that there and it will work fine. – Alexander Ejbekov Apr 20 '14 at 20:46
  • Ah, Thank you so much. Sorry for making such an obvious mistake haha, I feel silly now! – Oscar Apr 20 '14 at 20:58
1

Add extra logic. When the life is 0 or less after reduce -25:

if health <= 0:
    break

This is better because if there's another enemy that hits -35 and your life is 25? Of course the result will be -10 <= 0 and break.

Victor Martins
  • 739
  • 7
  • 21