Python中的机器人运动

时间:2012-04-07 00:03:18

标签: python robotics

我正在尝试编程一个机器人来移动。机器人根据当前的位置移动。有四个地方可以:

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

我正在努力想出一个好的pythonic方法来编写代码。我正在考虑定义4个不同的下一步规则,然后有一堆if语句选择正确的规则

有人做过类似的事吗......有更好的方法

3 个答案:

答案 0 :(得分:2)

我知道这可以变得更优雅(我的方法的名字很糟糕!),但也许是这样的?

>>> 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))

答案 1 :(得分:1)

大多数pythonic方式是StateMachine

答案 2 :(得分:0)

你可以这样做,你会做的是。

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


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

然后在主程序中,根据x1,y1调用各种运动方法。