简体   繁体   English

如何正确加载Pygame中的图像?

[英]How do you Load an Image in Pygame Properly?

Whenever I try to load an image of some fries (an enemy in the game), it loads the sprite. 每当我尝试加载一些薯条(游戏中的敌人)的图像时,它会加载精灵。 I think, the image is blank. 我认为,图像是空白的。 How do I properly load the image to make it appear? 如何正确加载图像以使其显示?

I've tried to change the method of loading the image, opting for loading the image from the outside of the class instead of the inside. 我试图改变加载图像的方法,选择从类外部而不是内部加载图像。

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

I need the sprite to show up, but it shows up blank. 我需要精灵出现,但它显示为空白。 I want it to spawn in the middle of the screen, hence the center = pos . 我想让它在屏幕中间产生,因此center = pos

The image is probably loaded just fine; 图像可能装得很好; but you never actually blit it to the screen surface. 但你从来没有真正把它搞砸到屏幕表面。

You could change your code to this: 您可以将代码更改为:

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

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

using a Group , which is pygame's default way of drawing sprites. 使用Group ,这是pygame绘制精灵的默认方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM