【问题标题】:Robot Motion in PythonPython中的机器人运动
【发布时间】:2012-04-07 00:03:18
【问题描述】:

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

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

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

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

【问题讨论】:

  • 使用状态机设计模式

标签: python robotics


【解决方案1】:

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

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

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 1970-01-01
        • 2021-10-01
        • 1970-01-01
        • 2018-02-27
        相关资源
        最近更新 更多