Search code examples
pythonif-statementfor-loopnested-loopsturtle-graphics

Python nested loops


I am working on a project and cannot seem to fix this issue. I have a for loop and then several if conditions in it. I want, for one of the ifs to change the global variable "enemyspeed" just for that item that meets the condition.

Is there any way to manipulate a turtle's position like this? My list consists of turtles that I created.

Basically this code is for a space invaders game I am doing. The code shown moves the enemy. My first if statement moves the players sideways. The next two move the enemy down and the opposite direction. As is, the code changes the direction of all the enemies because I am changing the global variable for the speed. I wish to change the direction the enemy is heading for the specific enemy that dropped down.

for enemy in enemies_1:
    if enemy.heading() == 0:
        x = enemy.xcor()
        x -= enemyspeed
        enemy.setx(x)
    elif enemy.heading() == 1:
        x = enemy.xcor()
        x += enemyspeed
        enemy.setx(x)

    # Move the enemy back and down
    if enemy.xcor() > 300:
        y = enemy.ycor()
        y -= 40
        enemyspeed *= -1
        if enemyspeed < 0:
            enemyspeed -= .2
        else:
            enemyspeed += .2
        enemy.sety(y)


    if enemy.xcor() < - 300:
        y = enemy.ycor()
        y -= 40
        enemyspeed *= -1
        if enemyspeed < 0:
            enemyspeed -= .2
        else:
            enemyspeed += .2
        enemy.sety(y)

Solution

  • If you want to change the speed only for one enemy, you need to have enemy.speed properties for all enemies. Then each enemy can start with the default speed and later on update it according to whatever conditions.