【问题标题】:Pygame only one image/sprite is displayingPygame 仅显示一个图像/精灵
【发布时间】:2018-05-17 01:02:43
【问题描述】:
# 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 中制作 Space Invaders 游戏,但是当我尝试绘制射弹时,它会覆盖/更改主精灵(平面)。我该如何解决这个问题,以便我可以在屏幕上显示多个精灵?

【问题讨论】:

标签: python pygame 2d


【解决方案1】:

你的精灵的绘图功能给你带来了问题。每次绘制精灵时,它都会填充并刷新显示。这意味着如果您有两个或更多对象,则只会显示最后一个。仅对每个对象使用 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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多