精灵对象未显示在显示器上(Pygame)?

无限玩家

我目前正在尝试使用Pygame开发一款小型的基本游戏。但是,我无法在屏幕上绘制精灵对象。我的代码如下:

import pygame

# window
WIDTH = 400
HEIGHT = 400
FPS = 60

# colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
PINK = (255, 0, 191)
BROWN = (102, 51, 0)
GRAY = (102, 102, 51)

# player

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50,50))
        self.image.fill(GREEN)

        # variables needed for movement
        self.rect = self.image.get_rect()
        self.rect.centerx = 200
        self.rect.bottom = 200
        self.speedx = 0
        self.speedy = 0

    def update(self):
        # move sprite
        self.speedx = 0
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_w]:
            self.speedx = -5
        if keystate[pygame.K_d]:
            self.speedx = 5
        self.rect.x += self.speedx

        # boundary collision
        if self.rect.x < 0:
            self.rect.x = 0
        elif self.rect.x < 400:
            self.rect.x = 400


# initialisation
pygame.init()

# sound
pygame.mixer.init()

# draw window
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Shoot")
clock = pygame.time.Clock()

# sprite group
all_sprites = pygame.sprite.Group()

# create player
player = Player()

# add sprites to sprite group
all_sprites.add(player)

# game loop

running = True
while running:
    # keeps speed constant
    clock.tick(FPS)
    # allows for exit
    for event in pygame.event.get():
        # check before closing window
        if event.type == pygame.QUIT:
            running = False

    # update sprites
    all_sprites.update()

    # draw screen
    #screen.fill(BLACK)
    all_sprites.draw(screen)
    #player.draw(screen)
    # used to draw
    pygame.display.flip()

pygame.quit()

如您在代码中看到的,我有一个从Player类创建的播放器对象。然后,将其添加到all_sprites组。然后应在屏幕上绘制。但是,什么也没画

拉比德76

问题在于Player,由于以下原因,对象的矩形超出了窗口范围if self.rect.x < 400: self.rect.x = 400

class Player(pygame.sprite.Sprite):
   # [...]

   def update(self):
       # [...]

       if self.rect.x < 0:
           self.rect.x = 0
       elif self.rect.x < 400:
           self.rect.x = 400

必须是self.rect.x > 400

class Player(pygame.sprite.Sprite):
    # [...]

    def update(self):
        # [...]

        if self.rect.x < 0:
            self.rect.x = 0
        elif self.rect.x > 400: # <----
            self.rect.x = 400

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章