当某个命令为真时,如何更新 python pygame 中的文本?

Posted

技术标签:

【中文标题】当某个命令为真时,如何更新 python pygame 中的文本?【英文标题】:How do I update the text in python pygame when a certain command is true? 【发布时间】:2021-12-05 07:55:48 【问题描述】:

我正在尝试构建一个类似太空入侵者的游戏以供娱乐。 基本上已经完成了,但是当我射击敌人时,我希望屏幕上的文字与他的生命值一起减少。

这是我的代码仅剥离到健康更新部分:

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)

这不是游戏的全部,但它是基本理念。 在激光击中敌人之前,游戏中的分数不会更新。

这是整个游戏,如果代码可以帮助您理解我的问题:

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)

任何帮助将不胜感激。 :) 谢谢!

【问题讨论】:

您剥离的代码是minimal reproducible example 上的完美示例!虽然我认为你的意思是写enemy_health -= 1 而不是enemy_health_text -= 1。但除此之外,第一个问题很好! 【参考方案1】:

文本在enemy_health_text Surface 中呈现,值为enemy_health。您必须更改 enemy_health 并再次呈现文本:

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()

【讨论】:

谢谢,这行得通,但它只覆盖了已经存在的文本。你知道如何删除已经存在的文本,然后绘制更新的文本吗? @IsaacJohnson 无需清除每一帧的显示。在答案中,这是通过win.fill(0) 完成的。 @IsaacJohnson 答案可以接受吗? (复选标记 - How does accepting an answer work?)

以上是关于当某个命令为真时,如何更新 python pygame 中的文本?的主要内容,如果未能解决你的问题,请参考以下文章

当某个条件为真时,如何在 Eclipse 中以编程方式设置 C++ 断点?

如何将一个观察值与先前的观察值相乘,但仅当某个条件为真时

Swift 3 - 当布尔为真时如何移动精灵节点?

如何执行?当某些条件为真时,带有 OR 的 jquery.on 事件?

PHP/jQuery - 当 PHP 语句为真时如何使用 jQuery 播放 mp3 音频文件

当其他可观察对象为真时,从可观察对象中获取项目