Reputation: 499
I am practicing my pygame skills by making a small project. In it, it will blit a background image to the screen. Afterwards, it will use a list called soldiers, and if the item it takes in the list is 1, it will print a soldier, if it is 0, it will skip a space. When I run the code however, it blits the background, then the sprites, then the sprites disappear. I want my sprites to stay on the screen after the for loop has finished. Here is the for loop section:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(background_img, (0,0))
for i in soldiers:
if i == 1:
screen.blit(sprite_img,(x,y))
x = x + 50
time.sleep(0.5)
pygame.display.update()
elif i == 0:
x = x + 50
time.sleep(0.5)
pygame.display.update()
pygame.display.update()
Here is all my code:
import sys, pygame, time
from pygame.locals import *
pygame.init()
soldiers = [0,1,1,1,1,0,0,1,1,0]
x = 0
y = 50
background_img = pygame.image.load("/home/myname/Desktop/Army Project/images/background.png")
sprite_img = pygame.image.load("/home/myname/Desktop/Army Project/images/sprite.png")
size = background_img.get_size()
rect = background_img.get_rect()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Army Men")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(background_img, (0,0))
for i in soldiers:
if i == 1:
screen.blit(sprite_img,(x,y))
x = x + 50
time.sleep(0.5)
pygame.display.update()
elif i == 0:
x = x + 50
time.sleep(0.5)
pygame.display.update()
pygame.display.update()
Thank you for your time.
Upvotes: 0
Views: 1697
Reputation: 11170
There are few issues with your code.
First, the pygame.display.update() is redundant in the for loop. You only need to call it once per frame, in your case it will be twice.
Second, do not use time.sleep() in pygame. This essentially freezes your game. So you cannot do anything in it. If you want some sort of a delay, use a timer.
Third, this line appears twice in your if else construct x = x + 50
. You could move it outside of the if else.
Lastly, I think your problem is caused by not reseting the variable x. So they still get blit, but outside of the screen.
The code after fixing:
import sys, pygame, time
from pygame.locals import *
pygame.init()
soldiers = [0,1,1,1,1,0,0,1,1,0]
x = 0
y = 50
background_img = pygame.image.load("/home/myname/Desktop/Army Project/images/background.png")
sprite_img = pygame.image.load("/home/myname/Desktop/Army Project/images/sprite.png")
size = background_img.get_size()
rect = background_img.get_rect()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Army Men")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(background_img, (0,0))
x = 0
for i in soldiers:
if i == 1:
screen.blit(sprite_img,(x,y))
x = x + 50
pygame.display.update()
Upvotes: 0