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

sda*_*das 5 python chess

我正在用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
Run Code Online (Sandbox Code Playgroud)

Nia*_*rne 7

为什么不存储它可以移动的相对对?所以采取你的起点,并添加一组可能的移动远离它,然后你只需要一个完整性检查,以确保它们仍然在边界,或不在另一块.

即给定你的(2,4)起点,选项是(-2,-1),( - 2,+ 1),( - 1,+ 2),(+ 2,+ 1)因此相对位置总是一样的.


sda*_*das 5

好的,因此感谢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
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是不正确的。例如,当它应为(1,2)和(2,1)时,`knight_moves((0,0))`会产生[[(1,1),(2,1)]]` (2认同)

xia*_*owl 5

不熟悉国际象棋...

deltas = [(-2, -1), (-2, +1), (+2, -1), (+2, +1), (-1, -2), (-1, +2), (+1, -2), (+1, +2)]
def knight_moves(position):
    valid_position = lambda (x, y): x >= 0 and y >= 0 and ???
    return filter(valid_position, map(lambda (x, y): (position[0] + x, position[1] + y), deltas))
Run Code Online (Sandbox Code Playgroud)