Hit Flash
Part of the Sound and Game Feel section of Coddy's Pygame journey. Lesson 13 of 23.
When you hit an enemy, the game should show it at once, even before a health bar changes. The usual way is a hit flash: for a few frames the enemy is drawn all white.
It takes one counter, the frames left to flash. A hit sets it; each frame lowers it:
flash = 0
...
# a hit
hp -= 1
flash = 6
...
# every frame
if flash > 0:
flash -= 1When drawing, the counter picks the colour:
if flash > 0:
pygame.draw.rect(screen, (255, 255, 255), enemy)
else:
pygame.draw.rect(screen, (220, 80, 80), enemy)Six frames is a tenth of a second: long enough to see, short enough that the next hit can flash again. The player can tell at a glance that the attack landed.
A sprite with an image can flash the same way: keep a white copy of its image, or fill a copy with white, and blit that while the counter runs. Many games flash the player red when they take damage, with the same counter.
Challenge
EasyMake each hit flash the enemy white.
- Make
flash = 0before the loop, and setflash = 6on a hit. - Each frame, lower
flashby 1 while it is above 0. - Draw the enemy white
(255, 255, 255)whileflashis above 0, red otherwise.
Press Play and press Space: the enemy flashes white. Then Check.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Training Dummy")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)
hit_sound = pygame.mixer.Sound("assets/sounds/hit.ogg")
player = pygame.Rect(120, 150, 60, 60)
enemy = pygame.Rect(300, 150, 60, 60)
hp = 5
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and hp > 0:
hp -= 1
hit_sound.play()
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 160, 255), player)
if hp > 0:
pygame.draw.rect(screen, (220, 80, 80), enemy)
label = font.render(f"Enemy HP: {hp}", True, (240, 240, 240))
screen.blit(label, (300, 110))
pygame.display.flip()
clock.tick(60)
pygame.quit()
All lessons in Sound and Game Feel
Practice on your own: Pygame playground