2016-08-02 56 views
0

我写了简单的代码来获得一个绿色的块,这是我的精灵滚动屏幕。当游戏开始时,精灵将出现在屏幕中央,但是当我运行我的代码时,屏幕只是黑色,并且绿色模块不会出现,除非我单击窗口上的x十字来退出屏幕,那么当窗户关闭时它会出现一秒钟。任何想法,我可以解决这个问题。Python 3.4 Pygame我的精灵没有出现

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() 

回答

0

所有代码到updat精灵,充满屏幕,并绘制精灵是你的主循环外(while running

你必须记住,identation 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() 
+0

谢谢,现在正在工作,谢谢你的回应。 –