我正在尝试编程一个机器人来移动.机器人根据当前的位置移动.有四个地方可以:
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
Run Code Online (Sandbox Code Playgroud)
我正在努力想出一个好的pythonic方法来编写代码.我正在考虑定义4个不同的下一步规则,然后使用一堆if语句来选择正确的规则
有人做过类似的事吗......有没有更好的方法
我知道这可以做得更优雅(而且我的方法的名称很糟糕!),但也许是这样的?
>>> 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')
Run Code Online (Sandbox Code Playgroud)
我不确定您需要多少灵活性,如果您想消除一些灵活性,您可以进一步降低复杂性。此外,您几乎肯定不会为此使用字符串,我只是认为这是演示该想法的最简单方法。如果你使用数字,那么像这样:
>>> 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)
Run Code Online (Sandbox Code Playgroud)
应该非常清楚地对应于此:
LOCATION4 Motion Plan is like so,
6 4 2
5 3 1
Run Code Online (Sandbox Code Playgroud)
我认为动议计划如下:
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))
Run Code Online (Sandbox Code Playgroud)