为什么精灵不动?

问题描述

我目前正在编写一个 pygame 游戏,你可以在屏幕上移动一艘宇宙飞船。目前,我已经到了我制造宇宙飞船并试图让它移动的部分。但是,当我尝试移动飞船时,飞船不动!

这是我当前的代码

import pygame

pygame.init()
screen = pygame.display.set_mode((800,500))
screen.fill((255,255,255))


class Spaceship(pygame.sprite.Sprite):
    def __init__(self,s,x,y):
        pygame.sprite.Sprite.__init__(self)

        self.screen = s
        self.x,self.y = x,y
        self.image = pygame.image.load("C:/eqodqfe/spaceship.png")
        self.image = pygame.transform.scale(self.image,(175,175))
        self.rect = self.image.get_rect()
        self.rect.center = (self.x,self.y)

    def update(self):
        self.rect.center = (self.x,self.y)


spaceship = Spaceship(screen,400,400)
screen.blit(spaceship.image,spaceship.rect)

running = True
while running:
    for event in pygame.event.get():
       if event.type == pygame.QUIT:
            running = False

    key = pygame.key.get_pressed()
    if key[pygame.K_a]:
        spaceship.x -= 5
    elif key[pygame.K_d]:
        spaceship.x += 5
    elif key[pygame.K_w]:
        spaceship.y += 5
    elif key[pygame.K_s]:
        spaceship.y -= 5

    spaceship.update()
    pygame.display.update()

我当前的代码有什么问题?

解决方法

您必须在应用程序循环中绘制Sprties

clock = pygame.time.Clock()
running = True
while running:
    
    # handle events
    for event in pygame.event.get():
       if event.type == pygame.QUIT:
            running = False

    key = pygame.key.get_pressed()
    if key[pygame.K_a]:
        spaceship.x -= 5
    elif key[pygame.K_d]:
        spaceship.x += 5
    elif key[pygame.K_w]:
        spaceship.y -= 5
    elif key[pygame.K_s]:
        spaceship.y += 5

    # update the position of the object
    spaceship.update()

    # clear the display 
    screen.fill((255,255,255))

    #  draw the object
    screen.blit(spaceship.image,spaceship.rect)

    # update the display
    pygame.display.update()

    # limit frames per second 
    clock.tick(60)

典型的 PyGame 应用程序循环必须:


此外,我建议使用 pygame.sprite.Group

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

前者将 委托给包含的 pygame.sprite.Spritesupdate 方法 - 您必须实现该方法。见pygame.sprite.Group.update()

对组中的所有 Sprite 调用 update() 方法 [...]

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

将包含的精灵绘制到 Surface 参数。这对源表面使用 Sprite.image 属性和 Sprite.rect。 [...]

spaceship = Spaceship(screen,400,400)
all_sprites = pygame.sprite.Group()
all_sprites.add(spaceship)

clock = pygame.time.Clock()
running = True
while running:
    clock.tick(60)
    for event in pygame.event.get():
       if event.type == pygame.QUIT:
            running = False

    key = pygame.key.get_pressed()
    if key[pygame.K_a]:
        spaceship.x -= 5
    elif key[pygame.K_d]:
        spaceship.x += 5
    elif key[pygame.K_w]:
        spaceship.y += 5
    elif key[pygame.K_s]:
        spaceship.y -= 5

    all_sprites.update()

    screen.fill((255,255))
    all_sprites.draw(screen)
    pygame.display.update()