首页 > 解决方案 > 精灵没有在 Pygame 中显示

问题描述

我不确定我在这里做错了什么。没有出现错误,但是当游戏加载时什么都没有出现,只有黑色背景。这是我正在运行的将我的精灵加载到游戏中的代码。

import pygame
import sys
import os
pygame.init()

"""
Spawn Player
"""

class Player(pygame.sprite.Sprite):
    pygame.display.set_mode()
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.images = []
        img = pygame.image.load(os.path.join("images", "ninja.jpeg")).convert()
        self.images.append(img)
        self.image = self.images[0]
        self.rect = self.image.get_rect()
    def Run(self):
        pygame.sprite.Sprite.__init__(self)
        self.images = []
        for i in range(1,5):
            run_img = pygame.image.load(os.path.join("run","ninja_run" + str(i) + ".jpeg")).convert()
            self.images.append(run_img)
            self.image = self.images[0]
            self.rect = self.image.get_rect()

"""
Setup
"""
worldx = 900
worldy = 700
fps = 40
ani = 4
clock = pygame.time.Clock()
world = pygame.display.set_mode([worldx, worldy])

player = Player()
player.rect.x = 32
player.rect.y = 32
player_list = pygame.sprite.Group()
player_list.add(player)

BLUE = (25, 25, 200)
BLACK = (20, 20, 20)
WHITE = (255, 255, 255)
RED = (200, 25, 25)
"""
Main Loop
"""
main = True
while main:
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
            break




    #world.blit(backdrop, backdrop_box)
    player_list.draw(world)
    world.fill(BLACK)
    pygame.display.flip()
    clock.tick(fps)

我让一个朋友查看了代码,他说播放器类下的init有问题,但除此之外,我真的不明白代码中的问题出在哪里。

窗口正在正确调用,我将背景设为黑色,但精灵根本不会加载。

我在这里使用教程来显示精灵。我已经设置了其他部分之间的运动,唯一似乎不起作用的是围绕精灵旋转的代码。

这里的任何帮助都会很棒。

标签: pythonpygamespritepygame-surface

解决方案


world.fill(BLACK)立即为pygame.display.flip().
world.fill(BLACK)用黑色填充整个窗口表面并覆盖之前绘制的所有内容。pygame.display.flip()更新窗口。这导致窗口看起来完全是黑色的。

更改说明的顺序以解决问题:

world.fill(BLACK) 
player_list.draw(world)
# world.fill(BLACK)      <---- delete
pygame.display.flip()

推荐阅读