Enemy health bar aint draining pygame [duplicate]

2024/7/8 8:06:19

Okay so I was trying to make a health bar for my enemy class and only a part of it is working, what I mean is that every time I hit my enemy, I want its health bar to turn green to red and ,ale is lose 50 percent of it health, but that's not really working, the part of it needing 2 hits to kill my enemy is working but the part of the health draining and turning from green to red is not working. My problem is in the second main loop.

https://gyazo.com/9ab3f871afb9d3bcdd0fea0a0eadec87

when I shot at the player, the heath did not go down at all.

this is were I drew my color red and green.

pygame.draw.rect(window, (255,0,0), (self.hitbox[0], self.hitbox[1] - 20, 80, 10))
pygame.draw.rect(window, (0,255,0), (self.hitbox[0], self.hitbox[1] - 20, 80 - (5 * (10 - self.health)), 10))
self.hitbox = (self.x + 17, self.y + 2, 31, 57)

this is were I told it to take away health

if Enemy.health > -10:Enemy.health -= 5
else:del enemys[one]

my full code

Answer

I can't see anything immediately wrong with the code sections. I suspect it's not working because of the "health units" being used.

It may help to change you code to express these units as a percentage. That way no matter what kind of enemy it is, 0 health means destroyed, and removes potentially confusing comparisons, e.g.: -8 health = "somehow OK".

I've created a simple function to draw a red/green health bar. I reasoned that for some larger time the health is at 100%, so only draw the negative-health part when necessary.

def drawHealthBar( window, position, health_percent ):""" Draw a health bar at the given position, showing thehealth level as a green part and a red part of 100% """BAR_WIDTH = 64BAR_HEIGHT= 8# Start with full healthbar = pygame.Surface( ( BAR_WIDTH, BAR_HEIGHT ) )bar.fill( GREEN )# Work out the relative bar sizeif ( health_percent < 100 ):health_lost = BAR_WIDTH - round( BAR_WIDTH * health_percent / 100 )pygame.draw.rect( bar, RED, ( BAR_WIDTH - health_lost, 0, BAR_WIDTH, BAR_HEIGHT ) )# Draw the resultant barwindow.blit( bar, position )

demo screen shot

Obviously if your targets have RPG-style "hit points", the percentage can always be passed as:

health_percentage = round( current_hp / maximum_hp * 100 )

Reference Code:

import pygame# Window size
WINDOW_WIDTH    = 400
WINDOW_HEIGHT   = 400BLUE  = (   3,   5,  54 )
RED   = ( 200,   0,   0 )
GREEN = ( 0,   200,   0 )def drawHealthBar( window, position, health_percent ):""" Draw a health bar at the given position, showing thehealth level as a green part and a red part of 100% """BAR_WIDTH = 64BAR_HEIGHT= 8# Start with full healthbar = pygame.Surface( ( BAR_WIDTH, BAR_HEIGHT ) )bar.fill( GREEN )# Work out the relative bar sizeif ( health_percent < 100 ):health_lost = BAR_WIDTH - round( BAR_WIDTH * health_percent / 100 )pygame.draw.rect( bar, RED, ( BAR_WIDTH - health_lost, 0, BAR_WIDTH, BAR_HEIGHT ) )# Draw the resultant barwindow.blit( bar, position )### initialisation
pygame.init()
pygame.mixer.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
pygame.display.set_caption("Health Bar")
font = pygame.font.Font( None, 16 )### Main Loop
clock = pygame.time.Clock()
done = False
while not done:# Handle user-inputfor event in pygame.event.get():if ( event.type == pygame.QUIT ):done = Trueelif ( event.type == pygame.MOUSEBUTTONUP ):# On mouse-clickpasselif ( event.type == pygame.KEYUP ):# on Key-releasedpass# Movement keys#keys = pygame.key.get_pressed()#if ( keys[pygame.K_UP] ):#    print("up")# Update the windowwindow.fill( BLUE )x = WINDOW_WIDTH  // 2y = WINDOW_HEIGHT // 7 # Draw health bars from 100 - 0 %for health_remaining in range( 100, -10, -10 ):# The health as a numbertext = font.render( str( health_remaining ) + '%' , True, (200, 200, 200) )window.blit( text, ( x-50, y) )# The bardrawHealthBar( window, ( x, y ), health_remaining )y += 25pygame.display.flip()# Clamp FPSclock.tick( 3 )pygame.quit()
https://en.xdnf.cn/q/119451.html

Related Q&A

Python - Create and instantiate class

I am building a class of playlists, which will hold many playlists of the same genre.class playlist(object):def __init__(self,name):self.name = nameI would like to instantiate them passing the user:def…

Missing samples of a dataframe in pandas

My df:In [163]: df.head() Out[163]: x-axis y-axis z-axis time 2017-07-27 06:23:08 -0.107666 -0.068848 0.963623 2017-07-27 06:23:08 -0.105225 -0.070068 0.963867 .....I set the index as dateti…

How to hide a button after clicked in Python

I was wondering how to hide my start button after being clicked so that If the user accidentally was clicker happy they wouldnt hit the button causing more bubbles to appear on screen. Below is a snipp…

Unable to click on QRadioButton after linking it with QtCore.QEventLoop()

Few days back i had situation where i had to check/uncheck QRadioButton in for loop. Here is the link Waiting in for loop until QRadioButton get checked everytime? After implementing QEventLoop on thi…

Distance Matrix Haversine

I am working on a data frame that looks like this :lat lon id_zone 0 40.0795 4.338600 1 45.9990 4.829600 2 45.2729 2.882000 3 45.7336 4.850478 4 45.6981 5.…

python google geolocation api using wifi mac

Im trying to use Googles API for geolocation giving wifi data to determine location. This is their intro. And this is my code@author: Keith """import requestspayload = {"c…

Python requests and variable payload

Reticulated members,I am attempting to use a GET method that is supported against the endpoint. However, I am using python and wanting to pass the user raw_input that is assigned to a variable:uid = ra…

How should I read and write a configuration file for TkInter?

Ive gathered numbers in a configuration file, and I would like to apply them to buttons. Clicking the button should allow the number to be changed and then re-written to the config file. My current cod…

How to convert this nested dictionary into one single dictionary in Python 3? [duplicate]

This question already has answers here:Convert nested dictionary into a dictionary(2 answers)Flatten nested dictionaries, compressing keys(32 answers)Closed 4 years ago.I have a dictionary like this:a …

How to click unopened tabs where the numbers change

How do I click all the unopened tabs pages where the value changes when you click tabs? (see image below)Take the following script, based off of this question with the following approach:clickMe = wai…