Session 9: Cheatsheet
Moving the boss back and forth
boss_rect.x += boss_speed
if boss_rect.right >= WIDTH or boss_rect.left <= 0:
boss_speed = -boss_speed # reverse direction
Drawing an HP bar
BOSS_MAX_HP = 100
# Background
pygame.draw.rect(screen, (80, 0, 0), (10, 10, 300, 20))
# Filled part
breedte = max(0, int(300 * boss_hp / BOSS_MAX_HP))
pygame.draw.rect(screen, RED, (10, 10, breedte, 20))
Bullet collision with the boss
for b in player_bullets[:]:
b.y -= 8
if b.colliderect(boss_rect):
player_bullets.remove(b)
boss_hp -= 1
Boss shoots (timer pattern)
boss_shoot_timer += 1
if boss_shoot_timer >= boss_shoot_interval:
boss_shoot_timer = 0
boss_bullets.append(
pygame.Rect(boss_rect.centerx - 4, boss_rect.bottom, 8, 16)
)
Phase logic (state machine)
if boss_hp > 50:
boss_phase = 1
boss_speed_abs = 3
boss_shoot_interval = 60
elif boss_hp > 25:
boss_phase = 2
boss_speed_abs = 5
boss_shoot_interval = 35
else:
boss_phase = 3
boss_speed_abs = 7
boss_shoot_interval = 20
# Keep the direction:
boss_speed = boss_speed_abs * (1 if boss_speed > 0 else -1)
Win screen
screen.fill((0, 0, 0))
win = font.render("BOSS DEFEATED!", True, YELLOW)
screen.blit(win, (WIDTH // 2 - win.get_width() // 2, HEIGHT // 2))
pygame.display.flip()
pygame.time.wait(3000)
Player lives as hearts
for i in range(player_lives):
pygame.draw.circle(screen, RED, (WIDTH - 20 - i * 30, 20), 10)