Python 3.4 Pygame我的精灵没有出现

时间:2016-08-02 17:09:09

标签: python pygame sprite

我编写了一个简单的代码来获取一个绿色块,这是我的精灵在屏幕上滚动。当游戏开始时,精灵会出现在屏幕的中央,但是当我运行我的代码时,屏幕只是黑色而绿色块不会出现,除非我点击窗口上的x十字以退出屏幕,然后它会在窗口关闭时显示一秒钟。任何想法我如何解决这个问题。

import pygame, random

WIDTH = 800 #Size of window
HEIGHT = 600 #size of window
FPS = 30 

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

class Player(pygame.sprite.Sprite):
    #sprite for the player
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50, 50))
        self.image.fill(GREEN) 
        self.rect = self.image.get_rect() 
        self.rect.center = (WIDTH/2, HEIGHT/2) 

    def update(self):
        self.rect.x += 5

#initialize pygame and create window
pygame.init() 
pygame.mixer.init() 
screen = pygame.display.set_mode((WIDTH, HEIGHT)) 
pygame.display.set_caption("My Game")
clock = pygame.time.Clock() 

all_sprites = pygame.sprite.Group() 
player = Player() 
all_sprites.add(player)

#Game loop
running = True 
while running:
    clock.tick(FPS) 
    for event in pygame.event.get():
        #check for closing window
        if event.type == pygame.QUIT:
            running = False
#update
all_sprites.update()

#Render/Draw
screen.fill(BLACK)
all_sprites.draw(screen) 

pygame.display.flip()

pygame.quit()

1 个答案:

答案 0 :(得分:0)

更新精灵,填充屏幕和绘制精灵的所有代码都在主循环之外(while running

你必须记住身份Python的语法:你的命令就在你的主循环之外。

此外,我强烈建议将mainloop置于适当的功能中,而不是将其留在模块根目录上。

...
#Game loop
running = True 
while running:
    clock.tick(FPS) 
    for event in pygame.event.get():
        #check for closing window
        if event.type == pygame.QUIT:
            running = False
    #update
    all_sprites.update()

    #Render/Draw
    screen.fill(BLACK)
    all_sprites.draw(screen) 

    pygame.display.flip()

pygame.quit()