Python:作为一名骑士,我如何在 numpy 数组棋盘上移动?

标签 python arrays numpy

我有以下 numpy 数组代码:

import numpy as np

a = np.array([[0,1,2,3,4,5,6,7],
[8,9,10,11,12,13,14,15],
[16,17,18,19,20,21,22,23],
[24,25,26,27,28,29,30,31],
[32,33,34,35,36,37,38,39],
[40,41,42,43,44,45,46,47],
[48,49,50,51,52,53,54,55],
[56,57,58,59,60,61,62,63]])

给定一个起点,我需要像骑士在国际象棋棋盘上一样在棋盘上移动(垂直 2 个空格,水平 1 个空格,反之亦然)。

我可以使用 np.argwhere 来获取起点的坐标:

np.argwhere(a==13) 返回 [[1 5]]。

我可以做什么来离开那里?我想测试所有可能的移动,并返回所有坐标。

最佳答案

这样的可能组合有八种。我们可以将它们作为 8 x 2 数组中的偏移量,并与起始 XY 进行广播加法。此外,我们需要调整那些超出棋盘限制的内容。

因此,以元组形式给出起始 X,Y 的实现将是 -

def knight_move(start_xy):
    offset1 = np.array([[-2,-1],[-2,1],[2,-1],[2,1]])    
    idx = np.row_stack((offset1, offset1[:,::-1])) + start_xy    
    return idx[~((idx < 0) | (idx > 7)).any(1)]

示例运行 -

In [66]: a   # Chessboard as array
Out[66]: 
array([[ 0,  1,  2,  3,  4,  5,  6,  7],
       [ 8,  9, 10, 11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20, 21, 22, 23],
       [24, 25, 26, 27, 28, 29, 30, 31],
       [32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47],
       [48, 49, 50, 51, 52, 53, 54, 55],
       [56, 57, 58, 59, 60, 61, 62, 63]])

In [67]: newXYs = knight_move((1,5)) # 13

In [68]: newXYs
Out[68]: 
array([[3, 4],
       [3, 6],
       [0, 3],
       [2, 3],
       [0, 7],
       [2, 7]])

In [69]: a[newXYs[:,0], newXYs[:,1]]
Out[69]: array([28, 30,  3, 19,  7, 23])

关于Python:作为一名骑士,我如何在 numpy 数组棋盘上移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40951720/

相关文章:

python - 动态地将复选框添加到可滚动框架中

python - 通过属性与通过文档的只读属性

python - 将 N 个工作日添加到不是单位 'D' 的 Numpy datetime64

image-processing - k-means 中的聚类中心?

python - 情节 : Too many ticks on X axe

c++ - 生成多维数组而不是 cout

arrays - `Marshal.load Marshal.dump array` 和 `array.map(&:dup)` 之间的区别

javascript - 对同一页面上的多个链接使用 Javascript 灯箱效果

python - 这个算法的名称,是否有它的 numpy/scipy 实现?

python - 无法为 Python 3 安装 Python 虚拟环境