I prepared a few hitboxes around certain enemies. These hitboxes are white. When they come into contact with a certain color, for example, red, it would trigger an if statement. I have heard pygame.mask
is useful in this situation.
The Code:
# Setting a display width and height and then creating it
display_width = 700
display_height = 500
display_size = [display_width, display_height]
game_display = pygame.display.set_mode(display_size)
intro_display = pygame.display.set_mode(display_size)
spaceship = pygame.image.load("spaceship2.png")
blue_enemy = pygame.image.load("blue_enemy.png")
green_enemy = pygame.image.load("green_enemy.png")
orange_enemy = pygame.image.load("orange_enemy.png")
pink_enemy = pygame.image.load("pink_enemy.png")
yellow_enemy = pygame.image.load("yellow_enemy.png")
# Creating a way to add text to the screen
def message(sentence, color, x, y, font_type, display):
sentence = font_type.render(str.encode(sentence), True, color)
display.blit(sentence, [x, y])
# Creating a loop to keep program running
while True:
# --- Event Processing and controls
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
spaceship_x_change = 10
elif event.key == pygame.K_LEFT:
spaceship_x_change = -10
elif event.type == pygame.KEYUP:
spaceship_x_change = 0
message(str(blue_enemy_health), white, 65, 10, font, game_display)
game_display.blit(blue_enemy, (20, 25))
blue_hit_box = pygame.draw.rect(game_display, white, [30, 35, 80, 70], 1)
message(str(green_enemy_health), white, 203, 10, font, game_display)
game_display.blit(green_enemy, (160, 25))
green_hit_box = pygame.draw.rect(game_display, white, [180, 35, 60, 70], 1)
message(str(orange_enemy_health), white, 341, 10, font, game_display)
game_display.blit(orange_enemy, (300, 25))
orange_hit_box = pygame.draw.rect(game_display, white, [315, 43, 65, 70], 1)
message(str(pink_enemy_health), white, 496, 10, font, game_display)
game_display.blit(pink_enemy, (440, 25))
pink_hit_box = pygame.draw.rect(game_display, white, [460, 35, 90, 70], 1)
message(str(yellow_enemy_health), white, 623, 10, font, game_display)
game_display.blit(yellow_enemy, (580, 25))
yellow_hit_box = pygame.draw.rect(game_display, white, [590, 40, 85, 70], 1)
# Creating a spaceship, lasers, and enemies
laser = pygame.draw.rect(game_display, red, [spaceship_x + 69, 100, 4, 300])
game_display.blit(spaceship, (spaceship_x, spaceship_y))
I want it that when the white hitboxes around the enemies to trigger an if event when they come into contact with red. I would like this to be done specifically with pygame.mask
.
Thanks