Python Robot Engine

I am trying to program a robot to move. The robot moves depending on where it is now. There are four places where this could be:

LOCATION1 Motion Plan is like so,
5 6
3 4
1 2
Initial positon is (x1,y1)
This gets coded as (x1,y1)->(x1+dx,y1)->(x1,y1+dy)->(x1+dx,y1+dy) ... and so on

LOCATION2 Motion Plan is like so,
5 3 1
6 4 2
The initial position is (x1,y1)
This gets coded as (x1,y1)->(x1,y1-dy)->(x1-dx,y1)->(x1-dx,y1-dy) ... and so on

LOCATION3 Motion Plan is like so,
6 5
4 3
2 1
Initial positon is (x1,y1)
This gets coded as (x1,y1)->(x1-dx,y1)->(x1,y1+dy)->(x1-dx,y1+dy) ... and so on

LOCATION4 Motion Plan is like so,
6 4 2
5 3 1
The initial position is (x1,y1)
This gets coded as (x1,y1)->(x1,y1+dy)->(x1-dx,y1)->(x1-dx,y1+dy) ... and so on

I am struggling to come up with a good pythonic way of coding this. I think of the definition lines of 4 different rules for the next move, and then have a bunch of if statements that select the correct rules.

Someone did something like this ... Is there a better way

+5
source share
3 answers

I know this can be made more elegant (and the names of my methods are terrible!), But maybe something like this?

>>> import itertools
>>> def alternator(*values):
...     return itertools.cycle(values)
... 
>>> def increasor(value_1, dvalue_1, steps=2):
...     counter = itertools.count(value_1, dvalue_1)
...     while True:
...             repeater = itertools.repeat(counter.next(), steps)
...             for item in repeater:
...                 yield item
... 
>>> def motion_plan(x_plan, y_plan, steps=6):
...     while steps > 0:
...         yield (x_plan.next(), y_plan.next())
...         steps -= 1
... 
>>> for pos in motion_plan(alternator('x1', 'x1+dx'), increaser('y1', '+dy'): #Location 1 motion plan
...     print pos
... 
('x1', 'y1')
('x1+dx', 'y1')
('x1', 'y1+dy')
('x1+dx', 'y1+dy')
('x1', 'y1+dy+dy')
('x1+dx', 'y1+dy+dy')

, , , . , , , . , - :

>>> count = 0
>>> for pos in motion_plan(increaser(0, -1), alternator(0, 1)): #location 4 motion plan
...     print "%d %r" % (count, pos)
...     count += 1
1 (0, 0)
2 (0, 1)
3 (-1, 0)
4 (-1, 1)
5 (-2, 0)
6 (-2, 1)

:

LOCATION4 Motion Plan is like so,
6 4 2
5 3 1

, :

Location1 = motion_plan(alternator(0, 1), increasor(0, 1))
Location2 = motion_plan(increasor(0, -1), alternator(0, -1))
Location3 = motion_plan(alternator(0, -1), increasor(0, 1))
Location4 = motion_plan(increasor(0, -1), alternator(0, 1))
+2

pythonic StateMachine

+1

You could do it, what would you do.

def motion_loc1(x1,y1,dx,dy):
     # your operation


def motion_loc2(x1,y1,dx,dy):
     # your operation

And then in the main program, depending on x1, y1, call the various movement methods.

0
source

All Articles