简体   繁体   中英

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

You must have in mind that identation Python's syntax: your commands are just outside your mainloop.

Moreover, I'd strongly advise to put that mainloop inside a proper function, instead of just leaving it on the module root.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM