簡體   English   中英

Python 3.4 Pygame我的精靈沒有出現

[英]Python 3.4 Pygame My sprite does not appear

我編寫了簡單的代碼來獲得一個綠色塊,這是我的精靈在屏幕上滾動。 游戲開始時,精靈將顯示在屏幕中央,但是,當我運行代碼時,屏幕只是黑色,除非單擊窗口上的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()

所有用於更新精靈,填充屏幕並繪制精靈的代碼都在主循環之外( while running

您必須牢記identification 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM