2016-08-02 60 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

謝謝,現在正在工作,謝謝你的迴應。 –