coordinates = [(0, 2), (0, 1), (1, 2), (1, 1), (0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]
I have created a Python array stated above. It contains tuples of points (x,y). I will assume I start at the first point (not the orgin). I want to move to the points in the order given. The only movement functions I have are rotate90Degrees(direction)
where direction is 1 or -1 for left and right, respectively. And forward(time)
where time is how long to move. I will assume time = 1 is equivalent to one unit in the coordinate system. Is there a clever way to easily change the this into movement instructions without a huge if/else if/else? What I have so far:
start = coordinates[0]
for x in range(1,len(coordinates)):
finish = coordinates[x]
change.append((finish[0] - start[0],finish[1] - start[1]))
start = coordinates[x]
Okay, so your robot is facing in some known cardinal direction and is at some known location, and you want it to move to another location.
First you need a list of tuples that map directions to displacements. I’ll use the standard unit circle, with angles as multiples of 90 degrees:
So moving when facing in direction
0
means your x-coordinate increases by 1 per unit time and your y-coordinate is unchanged, and so forth. The directions are integers from 0 to 3 inclusive.Now the code needs to figure out how to proceed. I’d start with whatever direction the robot’s currently facing. Say the desired displacement is
(-2, 1)
anddir
is0
.atod[dir]
is(1, 0)
. Ignore the one that’s zero; divide-2
by1
and you get-2
, so this direction is no good, we have to rotate. Which way? Check each one, see which way helps. If neither way helps, you need to do a 180, do it in whichever direction you like.So we did our rotation and now we’re in direction
1
andatod[dir]
is(0, 1)
. So we want to move forward by1
. Do so. Now you have to rotate again, move again, and you’re done.