Search code examples
pythonif-statementninja-turtles

Changing color of turtles on collision in python


Attempting to change the color of one turtle when it collides with another. What I want: Nidas (a single turtle) collides with green turns red. Red|Green collision>>Green turns red. Red|Red or Green|Green no action. Whats happening is Nidas|Green collision turns red (as intended) but Red|Green collision turns red to green. How have I messed up the if statement,

for ball in balls:
    ball.sety(ball.ycor() + ball.dy)
    ball.setx(ball.xcor() + ball.dx)
    for other_ball in balls:
        if (other_ball is ball):
            # We are not interested in balls colliding with themselves.
            # Skip the current iteration of the inner for-loop, and move on to the next ball
            continue
        if is_collided_with(other_ball, nidas):
            other_ball.color("red")
        if (
                is_collided_with(ball, other_ball) and
                other_ball.color("green") and
                ball.color("red")
            ):
            other_ball.color("red")

Solution

  • figured out a solution;

    for ball in balls:
            ball.sety(ball.ycor() + ball.dy)
            ball.setx(ball.xcor() + ball.dx)
            for other_ball in balls:
                if (other_ball is ball):
                    # We are not interested in balls colliding with themselves.
                    # Skip the current iteration of the inner for-loop, and move on to the next ball
                    continue
    
                if is_collided_with(other_ball, ball) and (ball.color()!=other_ball.color()):
                    ball.color("red")
    
                elif is_collided_with(ball, nidas):
                    ball.color("red")