Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python turtle random walk within a boundary

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)
like image 601
MissWizify Avatar asked Oct 27 '25 02:10

MissWizify


2 Answers

In the if statement, you should first turn, then go forward:

Suppose you are at (0,299), and the turtle is facing up, you will go forward (let's say 100), then turn (let's say left). You will then be at (0, 399), facing left.

You will then go in the else loop, by going right/300, so will be at 300/399, so still out of bound (note that forward(300) might be a little too much too).

If you first turn, then go forward, you will really make a U-Turn.
But once again, 300 might be to much. I would rather save the previous distance with something like:

if (-300 < turtle.xcor() <300) and (-300 < turtle.ycor() <300):
    turtle.right(random.randint(0,360))
    distance = random.randint(30,100) 
    turtle.forward(distance)
else:
    turtle.right(180)
    turtle.forward(distance)

Imagine you are at (299,299), going 135° (diag up/left), forward 100. Then you will have y>300, and if you make a U-Turn, and forward 300, you will have x>300. Then going in a loop again.

like image 109
fredtantini Avatar answered Oct 29 '25 16:10

fredtantini


Did you try switching the turtle.forward(random.randint(30,100)) and turtle.right(random.randint(0,360)) in the if statement, the other way arround?

It feels like that you are walking out of bound, then turning. Then it goes to the else, and it turns again, and walking further into out of bounds territory

like image 22
Bruno Lubascher Avatar answered Oct 29 '25 16:10

Bruno Lubascher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!