如何左右两个元素的方向元组(Snake AI)?

时间:2019-01-21 20:02:17

标签: python tuples

我正在编写蛇游戏AI,并遇到以下问题。我正在从AI课获得下一个move 1(向右转)或-1(向左转)。我需要按他们的意思转蛇。我将我的蛇的direction编码如下:

  

(1, 0) => going right

     

(-1, 0) => going left

     

(0, -1) => going up

     

(0, 1) => going down

有什么方法可以简化下面的if-elif块,这样我就不需要手动检查每个组合了吗?

if move == 1:
    if snake.direction == (1, 0):
        snake.direction = (0, 1)

    elif snake.direction == (-1, 0):
        snake.direction = (0, -1)

    elif snake.direction == (0, 1):
        snake.direction = (-1, 0)

    elif snake.direction == (0, -1):
        snake.direction = (1, 0)

elif move == -1:
    if snake.direction == (1, 0):
        snake.direction = (0, -1)

    elif snake.direction == (-1, 0):
        snake.direction = (0, 1)

    elif snake.direction == (0, 1):
        snake.direction = (1, 0)

    elif snake.direction == (0, -1):
        snake.direction = (-1, 0)

2 个答案:

答案 0 :(得分:3)

您可以使用线性代数来帮助您解决此问题。使用numpy,您可以将方向矢量乘以适当的旋转矩阵:

import numpy as np

if move == -1:
    rot_mat = np.array([[0, -1], [1, 0]])
elif move == 1:
    rot_mat = np.array([[0, 1], [-1, 0]])

这些是数学矩阵,当将点积与速度(方向)向量相乘时,将为您提供新的行进方向向量。

snake.direction = tuple(np.array(snake.direction).dot(rot_mat))

或者,如果您想进一步压缩它,则可以用一行代码完成整件事

snake.direction = tuple(np.array(snake.direction).dot(move * np.array([[0, 1], [-1, 0]])))

答案 1 :(得分:3)

解决方案

import numpy as np

def update_direction (m, move):
    return tuple(np.flip((np.array(m) * move) * np.array([1, -1]), 0))

但是,您是否打算使用更简化的方向表示?

例如,只有一个变量direction的范围可能是0到3 (0 == North, 1 == East, 2 == South, 3 == West)。这样,当您要转弯时,只需添加一个turn值为1或-1。

# Function updates direction
def update_direction(snake, turn):
    return snake.direction = (snake.direction + turn) % 4

# turn left
update_direction(snake, -1)

# turn right
update_direction(snake, 1)

然后您可以将此逻辑转变为使蛇最有效的方法。

相关问题