如何生成骑士的所有动作?

发布于 2021-01-29 14:56:28

我正在用Python编写一个Chess程序,该程序需要生成骑士的所有动作。对于那些不熟悉国际象棋的人,骑士会以L形移动。

因此,考虑的位置,(2, 4)骑士可以移动到(0, 3)(0, 5)(1, 2)(3, 2)等共(最多)八个不同的移动。

我想编写一个函数knight_moves,该函数在列表中生成这些元组。在Python中最简单的方法是什么?

def knight_moves(position):
    ''' Returns a list of new positions given a knight's current position. '''
    pass
关注者
0
被浏览
90
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    好的,感谢Niall Byrne,我想到了这个:

    from itertools import product
    def knight_moves(position):
        x, y = position
        moves = list(product([x-1, x+1],[y-2, y+2])) + list(product([x-2,x+2],[y-1,y+1]))
        moves = [(x,y) for x,y in moves if x >= 0 and y >= 0 and x < 8 and y < 8]
        return moves
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看