python - 如何在 Pygame 中正确加载图像?
问题描述
每当我尝试加载一些薯条(游戏中的敌人)的图像时,它都会加载精灵。我想,图像是空白的。如何正确加载图像以使其显示?
我试图改变加载图像的方法,选择从类外部而不是内部加载图像。
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()
我需要精灵出现,但它显示为空白。我希望它在屏幕中间产生,因此center = pos
.
解决方案
图像可能加载得很好;但你从来没有真正将它粘贴到屏幕表面。
您可以将代码更改为:
...
sprites = pygame.sprite.Group(Enemy((100, 300)))
move = True
while move:
...
sprites.draw(wind)
pygame.display.update()
使用 a Group
,这是 pygame 绘制精灵的默认方式。
推荐阅读
- rust - 如何使用为枚举变体中嵌入的某些类型实现的特征?
- python - 我如何级联下面的值并将它们添加到 python 数据框中的顶部数字?
- crystal-reports - Sage100-如何将 Quantity On Hand 添加到组件需求报告
- python - AttributeError:模块“skimage.transform”没有属性“seam_carve”
- django - Nginx 正在渲染错误的网站。有谁知道为什么?
- numpy - Numpy Boolean 按位意外行为
- jquery - 使用 jQuery 在 Textarea 中显示 XML 文件的所有内容
- .htaccess - 在不保留参数的情况下重定向 301
- python - 如何从 BeautifulSoup 中的 bs4.elements.tag 获取所有链接(href、src、url)属性?
- java - 如何使用 Android Studio 从 SharedPreferences 中的 Arraylist 中删除项目