Sneh P
Sneh P

Reputation: 73

Random Turtle movement, bounce off wall

Created the program to randomize the movement of the turtle but cannot get it to bounce off the window/canvas limits. Tried a few solutions posted with similar questions but still no luck.

from turtle import Turtle, Screen
import random

def createTurtle(color, width):
    tempName = Turtle("arrow")
    tempName.speed("fastest")
    tempName.color(color)
    tempName.width(width)
    return tempName

def inScreen(screen, turt):

    x = screen.window_height() / 2
    y = screen.window_height() / 2

    min_x, max_x = -x, x
    min_y, max_y = -y, y

    turtleX, turtleY = turt.pos()

    while (min_x <= turtleX <= max_x) and (min_y <= turtleY <= max_y):
        turt.left(random.randrange(360))
        turt.fd(random.randrange(50))
        turtleX, turtleY = turt.pos()
        print(turtleX, ",", turtleY)


wn = Screen()

alpha = createTurtle("red", 3)

inScreen(wn, alpha)

wn.exitonclick()

Upvotes: 1

Views: 937

Answers (2)

9000
9000

Reputation: 40894

Something like

old_position = turtle.position()  # Assume we're good here.
turtle.move_somehow()  # Turtle computes its new position.
turtle_x, turtle_y = turtle.position()  # Maybe we're off the canvas now.
if not (min_x <= turtle_x <= max_x) or not (min_y <= turtle_y <= max_y):
   turtle.goto(*old_position)  # Back to safely.
   turtle.setheading(180 - turtle.heading())  # Reflect.

Upvotes: 1

Bobby Durrett
Bobby Durrett

Reputation: 1293

Something like this:

while true:
    if (min_x <= turtleX <= max_x) and (min_y <= turtleY <= max_y):
        turt.left(random.randrange(360))
        turt.fd(random.randrange(50))
        turtleX, turtleY = turt.pos()
        print(turtleX, ",", turtleY)
    else:
# Put code here to move the turtle to where it intersected the edge
# and then bounce off

I guess you have to figure out where the intersection point is.

Upvotes: 0

Related Questions