I want to create a program using the turtle that makes 50 moves in a random direction for a random distance, staying within -300 to 300 on the x and y axis (by turning in the opposite direction and moving forward when it reaches the boundary).
The code runs fine when the if statement is true, but occasionally when the else statement is executed (due to exceeding the boundaries) the else statement will execute again and again until the count reaches 50. In other words it goes backwards and forwards along the same line. I don't understand why because when the turtle bounces off it should then be within the boundary and run the if statement again, not the else statement. How can i fix this so that the turtle continues its random walk after bouncing? Thanks
My code is shown below
import turtle
import random
count = 0
while count <51:
count += 1
if (turtle.xcor() >-300 and turtle.xcor() <300) and\
(turtle.ycor() >-300 and turtle.ycor() <300):
turtle.forward(random.randint(30,100))
turtle.right(random.randint(0,360))
else:
turtle.right(180)
turtle.forward(300)