I am working on a game which spawns enemies. Though once these enemies are spawned, they instantly disappear again because the background is drawn on top of them.
Is there a way to have a layer system in Pygame?
Code to recreate the problem:
import pygame
import threading
from random import randint
from time import sleep
pygame.init()
window = pygame.display.set_mode((900, 900))
bg=pygame.image.load("Background.png").convert()
def Gameplay():
while True:
window.blit(bg, [0,0])
pygame.display.update()
def spawn_enemy():
enemyW = 50
enemyH = 50
enemyX = 420
enemyY = 850
pygame.draw.rect(window, (93,124,249),(enemyX,enemyY,enemyW, enemyH))
print("an enemy has been spawned")
return True # would be "return enemy" after you create your enemy entity
def EnemySpawn():
enemy_list = [] # to maintain records of all enemies made
while True: # make enemies forever
sleep(randint(1,5))
enemy_list.append(spawn_enemy()) # call our function we made above which spawns enemies
Gameplay = threading.Thread(target=Gameplay)
Gameplay.start()
EnemySpawn = threading.Thread(target=EnemySpawn)
EnemySpawn.start()
I do not understand pygame
and it for some reason becomes generally unresponsive when I run this, but it does generate enemies and show how one would implement a class to store their variables (perhaps a pygame
expert could edit it to become responsive or comment what my code is doing that makes the window "freeze up"):
import pygame
import threading
from random import randint
from time import sleep
import random
pygame.init()
window = pygame.display.set_mode((900, 900))
bg = pygame.image.load("Background.png").convert()
class Enemy:
def __init__(self):
self.W = random.randint(30, 50)
self.H = random.randint(30, 50)
self.X = random.randint(0, 900)
self.Y = random.randint(0, 900)
def Gameplay():
global enemy_list
while True:
window.blit(bg, [0, 0])
for enemy in enemy_list:
pygame.draw.rect(window, (93, 124, 249), (enemy.X, enemy.Y, enemy.W, enemy.H))
pygame.display.update()
def EnemySpawn():
global enemy_list
while True: # make enemies forever
sleep(randint(1, 5))
print("Spawned an enemy")
enemy_list.append(Enemy()) # make an instance of our class
enemy_list = [] # to maintain records of all enemies made
game_thread = threading.Thread(target=Gameplay)
game_thread.start()
enemy_spawner_thread = threading.Thread(target=EnemySpawn)
enemy_spawner_thread.start()
The key points to note are the use of enemy_list
being in the global space and then calling it into functions with global enemy_list
so they are accessing the same list object. The class does essentially the same thing you were doing in your function, but gives the enemies random spawn points. As @Rabbid pointed out, you need to draw the enemies in the same part of your code that draws the background.
P.S. You should not use Gameplay = threading.Thread(target=Gameplay)
as this overwrites your function. I've implemented a different variable for the thread in my code