我目前正在构建自己的国际象棋引擎,并且可以就如何使此段代码对角线移动更有效地使用一些建议。 (这显然仅适用于对角线向右走)
到目前为止,我正在使用“ Try-Except”进行1的迭代,然后我的return语句过滤掉了所有非常规值。但是,这似乎是一种非常庞大的处理方式。
对于如何重构此代码的任何评论或建议,将不胜感激。
import argparse, json
chessBoard = [[1, 1, 1, 1, 1, 1, 1, 1] for i in range(8)]
chess_map_from_alpha_to_index = {
"a" : 0,
"b" : 1,
"c" : 2,
"d" : 3,
"e" : 4,
"f" : 5,
"g" : 6,
"h" : 7
}
chess_map_from_index_to_alpha = {
0: "a",
1: "b",
2: "c",
3: "d",
4: "e",
5: "f",
6: "g",
7: "h"
}
def getBishopMoves(pos, chessBoard):
column, row = list(pos.strip().lower())
row = int(row) - 1
column = chess_map_from_alpha_to_index[column]
i,j = row, column
solutionMoves = []
#Up-Right Diagonal
try:
temp = chessBoard[i + 1][j + 1]
solutionMoves.append([i + 1, j + 1])
except:
pass
try:
temp = chessBoard[i + 2][j + 2]
solutionMoves.append([i + 2, j + 2])
except:
pass
try:
temp = chessBoard[i + 3][j + 3]
solutionMoves.append([i + 3, j + 3])
except:
pass
try:
temp = chessBoard[i + 4][j + 4]
solutionMoves.append([i + 4, j + 4])
except:
pass
try:
temp = chessBoard[i + 5][j + 5]
solutionMoves.append([i + 5, j + 5])
except:
pass
try:
temp = chessBoard[i + 6][j + 6]
solutionMoves.append([i + 6, j + 6])
except:
pass
try:
temp = chessBoard[i + 7][j + 7]
solutionMoves.append([i + 7, j + 7])
except:
pass
try:
temp = chessBoard[i + 7][j + 7]
solutionMoves.append([i + 7, j + 7])
except:
pass
temp = [i for i in solutionMoves if i[0] >=0 and i[1] >=0]
solutionMoves = ["".join([chess_map_from_index_to_alpha[i[1]], str(i[0] + 1)]) for i in temp]
solutionMoves.sort()
return solutionMoves
答案 0 :(得分:0)
对于主教,必须考虑四个不同的方向:右上,右下,左下,左上。对于所有四个选项,您可以找到每个选项的最大投影坐标,然后对所有选项进行迭代。如果在迭代过程中遇到另一个片段,循环将停止。该算法的可能实现如下:
board = [['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', 'b', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-']]
options = [lambda x, y:(x+1, y+1), lambda x, y:(x+1, y-1), lambda x, y:(x-1, y-1), lambda x, y:(x-1, y+1)]
projected = [lambda x, y:(x+min([x,y]), y+min([x,y])), lambda x, y:(x+min([x,y]), y-min([x,y])), lambda x, y:(x-min([x,y]), y-min([x,y])), lambda x, y:(x-min([x,y]), y+min([x,y]))]
def iterate_towards(current, to, func):
while current != to:
current = list(func(*current))
if board[current[0]][current[-1]] != '-':
break
yield current
yield to
def get_bishop_moves(current:list):
for a, b in zip(options, projected):
yield list(iterate_towards([3, 4], list(b(*current)), a))
print(list(get_bishop_moves([3, 4])))
输出:
[[[4, 5], [5, 6], [6, 7]], [[4, 3], [5, 2], [6, 1]], [[2, 3], [1, 2], [0, 1]], [[2, 5], [1, 6], [0, 7]]]