[英]Python 3.4 Pygame My sprite does not appear
I have written simple code to get a green block which is my sprite to scroll across the screen. 我编写了简单的代码来获得一个绿色块,这是我的精灵在屏幕上滚动。 When the game starts the sprite is meant to appear in the centre of the screen, however when I run my code the screen is just black and the green block does not appear unless I click on the x cross on the window to exit the screen, then it appears for a second when the window is closing.
游戏开始时,精灵将显示在屏幕中央,但是,当我运行代码时,屏幕只是黑色,除非单击窗口上的x叉以退出屏幕,否则不会出现绿色块,然后在关闭窗口时显示一秒钟。 Any ideas how I can resolve this.
关于如何解决这个问题的任何想法。
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()
All your code to updat the sprites, fill the screens and draw the sprites is outside your main loop ( while running
) 所有用于更新精灵,填充屏幕并绘制精灵的代码都在主循环之外(
while running
)
You must have in mind that identation Python's syntax: your commands are just outside your mainloop. 您必须牢记identification Python的语法:您的命令就在您的主循环之外。
Moreover, I'd strongly advise to put that mainloop inside a proper function, instead of just leaving it on the module root. 此外,我强烈建议将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.