I want to make a program where I can input a:
- chess board size (w and h)
- max number of moves the knight can make to reach any square
- knight's starting position
I want it in this format:
Size: 10 Moves: 2 Knight: 2,4
2 . . 1 2 1 . . 2 .
. 2 1 2 . 2 1 2 . .
2 . 2 . 0 . 2 . 2 .
. 2 1 2 . 2 1 2 . .
2 . . 1 2 1 . . 2 .
. 2 . 2 . 2 . 2 . .
. . 2 . 2 . 2 . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
The numbers above are the number of moves made to come to the area. My problem is that I don't know how to write down the corresponding number on the board for how many moves each square took and am having trouble limiting it to a specific value so that the program won't keep looking for squares even after reaching the specified limit.
The code below for now uses 'X' in place of the numbers and '.' in place of the knight's position. The 0's are a place holder for the '.' used to indicate an empty spot.
Here is my code:
chess_board = []
size = 10
for i in range(size):
row = []
for j in range(size):
row.append(0)
chess_board.append(row)
def print_board():
for i in range(size):
for j in range(size):
print(chess_board[i][j], end=" ")
print("\n")
def get_possibilities(x, y):
pos_x = (2, 1, 2, 1, -2, -1, -2, -1)
pos_y = (1, 2, -1, -2, 1, 2, -1, -2)
possibilities = []
for i in range(len(pos_x)):
if x+pos_x[i] >= 0 and x+pos_x[i] <= (size-1) and y+pos_y[i] >= 0 and y+pos_y[i] <= (size-1) and chess_board[x+pos_x[i]][y+pos_y[i]] == 0:
possibilities.append([x+pos_x[i], y+pos_y[i]])
return possibilities
def solve():
counter = 2
x = 2
y = 4
chess_board[x][y] = '.'
for i in range((size*2)-1):
pos = get_possibilities(x, y)
minimum = pos[0]
for p in pos:
if len(get_possibilities(p[0], p[1])) <= len(get_possibilities(minimum[0], minimum[1])):
minimum = p
x = minimum[0]
y = minimum[1]
chess_board[x][y] = 'x'
counter += 1
solve()
print_board()