This kind of problem usually requires you to "simulate" all possible combinations of moves that king can make and get the best move that results in the highest number of jumps.
The simplest way to do it is to recursively call a function to simulate all possible moves (similar to what you did) and return a move that results in the highest number of jumps.
With no optimization, this algorithm is very expensive. I used it to implement Tic Tac Toe AI and because the board is only 3X3, it was pretty quick, but try something like this on a larger board and you will see it lagging.
I'm quite new to this as well, so I don't have good optimized code, but you can try implementing this. I will only provide the pseudocode, so you will have to do the bulk of the work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
struct Move
{
int direction
// 4 1
// K
// 3 2
int numberOfJumps;
// Add any other attributes/operations such as constructors and overloaded operator<
}
Move getBestMove( Board board )
{
// This is the base case for this recursion
if( king is stuck ) {
// In this case, direction doesn't matter since king can't jump
return Move with 0 numberOfJumps;
}
// This container will store all 4 moves simulated on the current board
std::vector<Move> moves;
// This is where you will simulate all 4 moves recursively. i is the direction
for( int i = 1 ; i <= 4 ; i++ ) {
if( king can jump in i direction ) {
// Create Move instance with direction initialized to i
Move move( i );
// Move the king in the i direction on the board
board.makeMove( i );
// Call this function recursively, storing the number of jumps king has made
move.numberOfJumps = 1 + getBestMove( board ).numberOfJumps;
// Undo the jump. Remember, we shouldn't change the actual board
board.undoMove( opposite i );
// Store this move in moves
moves.push_back( move );
}
}
// Now, look in the moves and return the move with the highest number of jumps
return *max_element( moves.begin() , moves.end() );
}
|
Eventually, the function will return Move that has the direction which will eventually yield the highest number of jumps and also it specifies the highest number of jumps.
Like I said, this isn't the best algorithm, but it is easy to implement and understand IMO and if the board is small enough, you can use it.
EDIT: Completely overlooked the fact that this is for checker. Changed the code accordingly