python - 如何在 Pygame 中正确加载图像?

标签 python pygame

每当我尝试加载一些薯条(游戏中的敌人)的图像时,它都会加载 Sprite 。我想,图像是空白的。如何正确加载图像以使其显示?

我尝试更改加载图像的方法,选择从类外部而不是内部加载图像。

import pygame
pygame.init()
# how big the game window is
wind = pygame.display.set_mode((600,700))

pygame.display.set_caption("Heart Attack")

x = 50
y = 50
width = 40
height = 60
vel = 0.8

fries = pygame.image.load('enemy.png').convert_alpha()

class Enemy(pygame.sprite.Sprite):
    def __init__(self, pos):
        super().__init__()
        self.image = fries
        self.rect = self.image.get_rect(center = pos)

move = True
Enemy((100, 300))

while move:
    pygame.time.delay(1)
#kill switch
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            move = False
    keys = pygame.key.get_pressed()
#moves character
    if keys[pygame.K_LEFT]:
        x -= vel
    if keys[pygame.K_RIGHT]:
        x += vel
    if keys[pygame.K_UP]:
        y -= vel
    if keys[pygame.K_DOWN]:
        y += vel
 # makes the character not clone itself
    wind.fill((0,0,0))      
 # draws and displays character with the color red
    pygame.draw.rect(wind, (255, 0, 0), (x, y, width, height))
    pygame.display.update()

pygame.quit()

我需要 Sprite 出现,但它显示为空白。我希望它在屏幕中间生成,因此 center = pos

最佳答案

图像可能加载得很好;但您从未真正将其 blit 到屏幕表面。

您可以将代码更改为:

...
sprites = pygame.sprite.Group(Enemy((100, 300)))

move = True
while move:
...
    sprites.draw(wind)
    pygame.display.update()

使用 Group ,这是 pygame 绘制 Sprite 的默认方式。

关于python - 如何在 Pygame 中正确加载图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55458106/

相关文章:

For 循环中的 Python 列表

python - 在 Pygame.mixer 的声音结尾处防止 "popping"

python - Pygame电影每隔一次播放就没有声音

python - 库未在 Python (pygame) 中初始化

python - libpythonX.X 中包含的符号如何链接到 numpy 扩展动态库?

Python Google Cloud Storage 未列出某些文件夹

python - pygame,检测旋转矩形的碰撞

python - 如何阻止调用打印?

python - 获取错误 search_products() 至少需要 2 个参数(给定 2 个)

python - 避免在单元测试中运行顶级模块代码