I want to spawn an enemy into the game at random intervals of 1-5 seconds. To prevent the gameplay part of the program (moving character etc.) from pausing whenever there is a sleep
, I have split the whole code into 2 methods so that I can have 2 threads- one that sets enemyspawn True
every 1-5 seconds and another one which controlls the character.
Sadly, either the 2nd method doesn't change enemyspawn
in the first method or threading outputs an error. I have read about and tried retrieving the value from EnemySpawn()
before the if statement but that didn't work (or I just did it wrong). I have also tried turning enemyspawn
to a global variable. Didn't change anything.
def Gameplay():
width=80
height=80
y = 720/2+height/2
x = 720/2+width/2
speed=2
enemyspawn = False
while True:
#controll character here
if enemyspawn:
enemyspawn=False
print(enemyspawn) #Spawn enemy here later
window.blit(bg, [0,0])
pygame.draw.rect(window,(100,100,100),(x,y,width,height))
pygame.display.update()
def EnemySpawn():
enemyspawn = EnemySpawn() #idrk about this line
while True:
sleep(randint(1,5))
enemyspawn=True
print(enemyspawn)
return enemyspawn
Gameplay = threading.Thread(target=Gameplay)
Gameplay.start()
EnemySpawn = threading.Thread(target=EnemySpawn)
EnemySpawn.start()
The threading error message:
line 51, in EnemySpawn
enemyspawn = Gameplay(enemyspawn)
UnboundLocalError: local variable 'enemyspawn' referenced before assignment
Another error message:
line 51, in EnemySpawn
enemyspawn = EnemySpawn()
TypeError: 'Thread' object is not callable