This is my first question!
I finished making a simple space invaders game in Python turtle graphics and noticed an annoying problem: the more objects I have on my screen, the slower the program runs.
My friend told me that I need to use multi-threading so that all the commands will run concurrently, and that way, the game will run smooth.
I added only the relevent code for my problem which is to move two enemy invaders from side to side of the screen. I think this will be enough to help me through this.
With this code, the enemies get stuck in their own place a couple of miliseconds every now and then. It's very noticable, what should I do?
one_enemy = turtle.Turtle()
one_enemy.shape("Invader.gif")
one_enemy.penup()
one_enemy.speed(0)
x = random.randint(-200, 200)
y = random.randint(100, 200)
one_enemy.setposition(x, y)
two_enemy = turtle.Turtle()
two_enemy.shape("Invader.gif")
two_enemy.penup()
two_enemy.speed(0)
x = random.randint(-200, 200)
y = random.randint(100, 200)
two_enemy.setposition(x, y)
def move_enemy_horizontally(enemy, direction):
while True:
while direction == "right":
x = enemy.xcor()
x += enemyspeed
enemy.setx(x)
if enemy.xcor() > 288:
y = enemy.ycor()
y -= 50
enemy.sety(y)
direction = "left"
while direction == "left":
x = enemy.xcor()
x -= enemyspeed
enemy.setx(x)
if enemy.xcor() < -288:
y = enemy.ycor()
y -= 50
enemy.sety(y)
direction = "right"
t = threading.Thread(target=move_enemy_horizontally, args=(one_enemy, direction))
t.start()
t2 = threading.Thread(target=move_enemy_horizontally, args=(two_enemy, direction))
t2.start()