Pygame只显示一个图像/精灵

2024-06-16 09:56:52 发布

您现在位置:Python中文网/ 问答频道 /正文

# Import the library PyGame
import pygame; pygame.init()

# Create the window/GUI
global window
window = pygame.display.set_mode((800, 800))
pygame.display.set_caption('Space Invaders')


class sprite:
    """A class that you assign to the a sprite, it has the functions     draw() and resize()"""

    def __init__(self, fileto):
        self.x = 330
        self.y = 700
        self.width = 100
        self.height = 100
        self.image = pygame.image.load(fileto).convert()

    # Blit the sprite onto the screen, ex: plane.draw()
    def draw(self):
        window.fill(255)
        window.blit(self.image, (self.x, self.y))
        self.image = pygame.transform.scale(self.image, (self.width, self.height))
        pygame.display.flip()


bakgrunn = pygame.image.load("stars.png").convert()

# Assign the variable plane to the class "sprite"
plane = sprite("plane.gif")
projectile = sprite("projectile.png")

while True:
    # Draw the plane and set the size
    plane.draw()
    plane.width = 100
    plane.height = 100

    projectile.draw()

我在PyGame中制作了一个太空入侵者游戏,但当我试图绘制出弹丸时,它会被主精灵(飞机)覆盖/改变。我如何解决这个问题,以便我可以有几个精灵显示在屏幕上?


Tags: theimageselfdisplaywindowwidthpygameclass
1条回答
网友
1楼 · 发布于 2024-06-16 09:56:52

你的精灵的绘制功能给你带来了麻烦。每次绘制精灵时,它都会填充并刷新显示。也就是说,如果有两个或多个对象,则只显示最后一个对象。只对每个对象使用blit函数,并在每个游戏循环中填充/刷新屏幕一次。在

# Import the library PyGame
import pygame; pygame.init()

# Create the window/GUI
window = pygame.display.set_mode((800, 800))
pygame.display.set_caption('Space Invaders')


class Sprite:
    """A class that you assign to the a sprite, it has the functions     draw() and resize()"""

    def __init__(self, fileto):
        self.x = 330
        self.y = 700
        self.width = 100
        self.height = 100
        self.image = pygame.image.load(fileto).convert()

    # Blit the sprite onto the screen, ex: plane.draw()
    def draw(self):
        window.blit(self.image, (self.x, self.y))    

# Assign the variable plane to the class "sprite"
plane = Sprite("plane.gif")
projectile = Sprite("projectile.png")

while True:
    # Clear the screen.
    window.fill((255, 255, 255))

    # Draw all objects to the screen.
    plane.draw()
    projectile.draw()

    # Make all everything you've drawn appear on your display.
    pygame.display.update()  # pygame.display.flip() works too

这将正确绘制所有精灵。但是,它会在几秒钟后崩溃,因为您没有处理事件。你需要先查阅一下关于这方面的教程,然后才能进一步发展。在

相关问题 更多 >