5

我正在尝试对机器人进行编程以使其移动。机器人根据当前位置移动。有四个地方可以:

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 语句来选择正确的规则

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

4

3 回答 3

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))
于 2012-04-07T00:57:59.503 回答
1

最pythonic的方式是StateMachine

于 2012-04-07T07:37:03.520 回答
0

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

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


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

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

于 2012-04-07T00:08:17.743 回答