Search code examples
pythonpygame2d-games

How do I update the text in python pygame when a certain command is true?


I'm trying to build a space invader-like game for fun. It's mostly done, but when I shoot the enemy I want the text on the screen with his health to decrease.

Here is my code stripped only to the health updating part:

import pygame
from sys import exit

enemy_health = 10

pygame.init()
win = pygame.display.set_mode((1000, 1000))
pygame.display.set_caption("Fighter Pilot Go!")
clock = pygame.time.Clock()

font = pygame.font.Font(None, 55)
enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                enemy_health_text -= 1

    win.blit(enemy_health_text, (350, 60)

That's not all of the game, but it's the basic idea. The score doesn't update in the game till a laser hits the enemy.

Here is the whole game, if the code helps you understand my issue:

import pygame
from sys import exit
import random

speed = 5
laser_speed = 7
bullets = []
score = 0
max_num_of_bullet = 3
background_speed = 3
enemy_health = 10
direction = True
enemy_speed = 7

pygame.init()
win = pygame.display.set_mode((1000, 1000))
pygame.display.set_caption("Fighter Pilot Go!")
clock = pygame.time.Clock()

background1 = pygame.image.load('assets/background.gif')
background2 = pygame.image.load('assets/background.gif')
background1_rect = background1.get_rect(topleft=(0, 0))
background2_rect = background2.get_rect(topleft=(0, -1000))

player = pygame.image.load('assets/player.gif')
player_rect = player.get_rect(midtop=(500, 750))

enemy = pygame.image.load('assets/enemy.gif')
enemy_rect = enemy.get_rect(center=(500, 350))

laser = pygame.image.load('assets/laser.gif')
# laser_rect = laser.get_rect(midtop=(500, 800))

font = pygame.font.Font(None, 55)
enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')


def is_collided_with(a, b):
    return abs(a[0] - b.centerx) < 51 and abs(a[1] - b.centery) < 51



while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                if len(bullets) <= max_num_of_bullet - 1:
                    bullets.append([player_rect.x + 49, player_rect.y - 60])
                elif len(bullets) > max_num_of_bullet - 1:
                    continue
                else:
                    print("Something Weird is Happening!")

    key = pygame.key.get_pressed()
    if key[pygame.K_a]:
        player_rect.x -= speed
    if key[pygame.K_d]:
        player_rect.x += speed

    win.blit(background1, background1_rect)
    win.blit(background2, background2_rect)
    win.blit(player, player_rect)
    win.blit(enemy, enemy_rect)

    background1_rect.y += background_speed
    background2_rect.y += background_speed

    if direction:
        enemy_rect.x -= enemy_speed
    elif not direction:
        enemy_rect.x += enemy_speed

    if enemy_rect.x <= 0:
        direction = False
    elif enemy_rect.x >= 900:
        direction = True

    if player_rect.x < -20:
        player_rect.x = 1020
    if player_rect.x > 1020:
        player_rect.x = -20

    for bullet in bullets:
        win.blit(laser, bullet)

    for bullet in bullets:
        bullet[1] -= laser_speed

    win.blit(enemy_health_text, (350, 60))

    for bullet in bullets:
        if is_collided_with(bullet, enemy_rect):
            bullets.remove(bullet)
            enemy_health -= 1

    for bullet in bullets:
        if bullet[1] < 0:
            bullets.remove(bullet)

    if background1_rect.y >= 1000:
        background1_rect.topleft = (0, -1000)
    if background2_rect.y >= 1000:
        background2_rect.topleft = (0, -1000)

    if enemy_health <= 0:
        pass


    pygame.display.update()
    clock.tick(60)

Any help would be appreciated. :) Thanks!


Solution

  • The text is rendered in the enemy_health_text Surface with the value of enemy_health. You have to change enemy_health and render the text again:

    font = pygame.font.Font(None, 55)
    enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')
    
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    enemy_health -= 1
                    enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')
    
        win.fill(0)
        win.blit(enemy_health_text, (350, 60)
        pygame.display.flip()