I'm currently in the process of building my own chess engine and could really use some suggestions on how to make this segment of code for calculating diagonal moves more efficient. (This is obviously only for diagonals going Up-Right)
As of now I'm using "Try-Except" to iterate by 1, and then my return statement filters out any off-board values. However this seems like a very bulky way of doing things.
Any comments or advice on how to refactor this code would be greatly appreciated.
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
Copyright Notice:Content Author:「Kevin Hebert」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/51006126/how-to-optimize-diagonal-movement-code-for-chess-engine