Skip to main content
Engineering LibreTexts

9.27: Drawing a Graphical Health Meter

  • Page ID
    14646
  • def drawHealthMeter(currentHealth):
        for i in range(currentHealth): # draw red health bars
            pygame.draw.rect(DISPLAYSURF, RED,   (15, 5 + (10 * MAXHEALTH) - i * 10, 20, 10))
        for i in range(MAXHEALTH): # draw the white outlines
            pygame.draw.rect(DISPLAYSURF, WHITE, (15, 5 + (10 * MAXHEALTH) - i * 10, 20, 10), 1)
    

    To draw the health meter, first the for loop on line 2 [317] draws the filled-in red rectangle for the amount of health the player has. Then the for loop on line 4 [319] draws an unfilled white rectangle for all of the possible health the player could have (which is the integer value stored in the MAXHEALTH constant). Note that the pygame.display.update() function is not called in drawHealthMeter().