5

動くロボットをプログラムしようとしています。ロボットは現在の場所に基づいて移動します。それがあり得る4つの場所があります:

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

最もPython的な方法は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 に答える