Health Bars

Goals

  • Use variables to affect the position and size of shapes.

  • Calculate colors along a continuum between two colors using the Color.lerp() method.

Steps

Health bars consist of two components:
  • The bar to show the remaining health (the foreground)

  • The background or outline of the bar to give a sense of how much health is lost.

  1. Draw a rectangle to represent a “full” health bar. Use the color green for this (0, 200, 0).

  2. Abstract the position and size into variables (x, y, w, h). Test to see if it still draws properly. Modify the values to ensure the abstraction worked.

  3. Draw another rectangle to represent the background. Use the color red for this (200, 0, 0).

  4. Create a health_percent variable that will control the width of the green (foreground) bar.

Polish

  • Use Color.lerp() to fade between colors depending on the health percentage.

  • Change the background bar from solid to outline.

Starter code

Pygame Template

Video Tutorial

What you need to do

  1. Create a variable to store the health of a hypothetical player.

  2. Calculate the percentage of health based on the player’s health.

  3. Use that percentage to determine the width of the health bar.

Final Code

import pygame
from pygame.locals import K_ESCAPE, KEYDOWN, QUIT

pygame.init()

WIDTH = 640
HEIGHT = 480
SIZE = (WIDTH, HEIGHT)

screen = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()

# ---------------------------
# Initialize global variables
bar_min_color = pygame.Color(200, 0, 0)
bar_max_color = pygame.Color(0, 200, 0)
bar_x = 50
bar_y = 50
max_bar_width = 400
bar_height = 50

health_percent = 0.5
bar_width = max_bar_width * health_percent
bar_foreground_color = bar_min_color.lerp(bar_max_color, health_percent)

# ---------------------------

running = True
while running:
    # EVENT HANDLING
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                running = False
        elif event.type == QUIT:
            running = False

    # GAME STATE UPDATES
    # All game math and comparisons happen here

    # DRAWING
    screen.fill((255, 255, 255))  # always the first drawing command

    # bar background
    pygame.draw.rect(screen, bar_min_color, (bar_x, bar_y, max_bar_width, bar_height), 2)

    # bar foreground
    pygame.draw.rect(screen, bar_foreground_color, (bar_x, bar_y, bar_width, bar_height))

    # Must be the last two lines
    # of the game loop
    pygame.display.flip()
    clock.tick(30)
    #---------------------------


pygame.quit()