gpt4 book ai didi

python - 图像未显示在 pygame 屏幕上

转载 作者:行者123 更新时间:2023-12-04 03:34:26 26 4
gpt4 key购买 nike

我是第一次用 pygame 制作我自己的游戏,而且我正在使用 sprite。我正在尝试将图像 blit 到屏幕上,但它不起作用。它所显示的只是一个空白的白色屏幕。这是代码:

BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
class SpriteSheet(object):
def __init__(self, file_name):
self.sprite_sheet = pygame.image.load(file_name).convert()
def get_image(self, x, y, width, height):
image = pygame.Surface([width, height]).convert()
image.blit(self.sprite_sheet, (0, 0), (x, y, width, height))
image.set_colorkey(BLACK)
return image

class Bomb(pygame.sprite.Sprite):
change_x =0
change_y = 0
def __init__(self):
image = pygame.Surface([256, 256]).convert()
sprite_sheet = SpriteSheet("Bomb_anim0001.png")
image = sprite_sheet.get_image(0, 0, 256, 256)

pygame.init()
screen_width = 700
screen_height = 400
screen = pygame.display.set_mode([screen_width, screen_height])
pygame.display.set_caption("Game")
clock = pygame.time.Clock()
done = False

while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True

screen.fill(WHITE)
bomb = Bomb()
clock.tick(60)
pygame.display.flip()
pygame.quit()

这是图片: Click on this link.

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

最佳答案

你必须blit 屏幕 Surface 上的图像。

但还有更多工作要做。将 rect 属性添加到 Bomb 类:

class Bomb(pygame.sprite.Sprite):

def __init__(self, x, y):
super().__init__()
sprite_sheet = SpriteSheet("Bomb_anim0001.png")
self.image = sprite_sheet.get_image(0, 0, 256, 256)
self.rect = self.image.get_rect(topleft = (x, y)
self.change_x = 0
self.change_y = 0

创建一个 pygame.sprite.Group并将 bomb 添加到 Groupdraw屏幕上 Group 中的所有 Sprite :_

bomb  = Bomb(100, 100)
all_sprites = pygame.sprite.Group()
all_sprites.add(bomb)

while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True

screen.fill(WHITE)
all_sprites.draw(screen)
pygame.display.flip()
clock.tick(60)

pygame.quit()

pygame.sprite.Group.draw()pygame.sprite.Group.update()pygame.sprite.Group 提供的方法。

前者委托(delegate)给包含的pygame.sprite.Spritesupdate 方法。 - 你必须实现这个方法。参见 pygame.sprite.Group.update() :

Calls the update() method on all Sprites in the Group [...]

后者使用包含的 pygame.sprite.Spriteimagerect 属性来绘制对象 - 你必须确保pygame.sprite.Sprite 具有所需的属性。参见 pygame.sprite.Group.draw() :

Draws the contained Sprites to the Surface argument. This uses the Sprite.image attribute for the source surface, and Sprite.rect. [...]

关于python - 图像未显示在 pygame 屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67190940/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com