Python: How To Make A Turtle Never Cross Over A Line
Solution 1:
Below is my attempt to solve your autonomous turtle problem. I chose a set()
to track visited positions but also coerced the turtle onto a grid to make sure that only a limited set of points could be visited. I didn't like your approach of doing a 180 when you hit a wall as that just makes you retrace your path and fail -- instead my turtle tries to avoid hitting the walls.
I use an invisible turtle clone to "test the waters" to see if a move is good or bad. If there are no good moves, it gives up, resets, and starts again. You have to close the window to kill the program:
import turtle
from random import shuffle
WIDTH, HEIGHT = 600, 500
INCREMENT = 50
TURTLE_WIDTH = 20
X, Y = 0, 1
def dot_round(x, base=INCREMENT):
returnint(base * round(float(x) / base))
turtle.setup(WIDTH, HEIGHT)
turtle.shape("turtle")
whileTrue:
positions = set()
whileTrue:
position = (dot_round(turtle.xcor()), dot_round(turtle.ycor())) # coerce position to gridif position in positions:
break# collision with line
positions.add(position)
turtle.setposition(position) # coerce turtle back onto our grid
moves = list(range(3))
shuffle(moves)
clone = None
for move in moves:
clone = turtle.clone() # use an invisible clone to test the watersclone.hideturtle()
clone.penup()
if move == 1:
clone.right(90)
elif move == 2:
clone.left(90)
clone.forward(INCREMENT)
position = (dot_round(clone.xcor()), dot_round(clone.ycor()))
if position[X] <= TURTLE_WIDTH//2 - WIDTH//2 or position[X] > WIDTH//2 - TURTLE_WIDTH//2:continue# avoid collision with wallif position[Y] <= TURTLE_WIDTH//2 - HEIGHT//2 or position[Y] > HEIGHT//2 - TURTLE_WIDTH//2:continue# avoid collision with wallif position not in positions:
breakelse: # no breakbreak# accept the inevitable, there's no good move
turtle.setheading(clone.heading())
turtle.forward(INCREMENT)
turtle.reset()
# close the turtle window to get out of this program
This turtle only looks one move ahead -- he easily gets himself into jams he can't get himself out of.
This hopefully gives you some ideas how to design your own turtle automaton.
Post a Comment for "Python: How To Make A Turtle Never Cross Over A Line"