#include #include #include #include #include #include #include "config.h" #include "pieces.h" #include "structs.h" #define MAX(x, y) (((x) > (y)) ? (x) : (y)) #define MIN(x, y) (((x) < (y)) ? (x) : (y)) void print_board(int board[128]) { for (int rank = 7; rank >= 0; rank--) { printf("%i|", rank + 1); for (int file = 0; file < 8; file++) { int piece = board[rank * 16 + file]; printf("%s ", pieces[piece]); } printf("\n"); } printf(" a b c d e f g h\n"); } void parse_FEN(char* FEN, int board[128]) { // TODO: parse everything, not position only int rank = 7; int file = 0; size_t lenght = strlen(FEN); for (int k = 0; k < lenght; k++) { if (FEN[k] > '0' && FEN[k] <= '8') { int last_file = file + FEN[k] - '0'; for (file; file < last_file; file++) { board[rank * 16 + file] = EMPTY; } } else { switch (FEN[k]) { case 'r': board[rank * 16 + file] = BLACK | ROOK; break; case 'R': board[rank * 16 + file] = ROOK; break; case 'n': board[rank * 16 + file] = BLACK | KNIGHT; break; case 'N': board[rank * 16 + file] = KNIGHT; break; case 'b': board[rank * 16 + file] = BLACK | BISHOP; break; case 'B': board[rank * 16 + file] = BISHOP; break; case 'q': board[rank * 16 + file] = BLACK | QUEEN; break; case 'Q': board[rank * 16 + file] = QUEEN; break; case 'k': board[rank * 16 + file] = BLACK | KING; break; case 'K': board[rank * 16 + file] = KING; break; case 'p': board[rank * 16 + file] = BLACK | PAWN; break; case 'P': board[rank * 16 + file] = PAWN; break; case '/': rank--; file = -1; // so that it becomes 0 break; case ' ': return; default: board[rank * 16 + file] = KNIGHT; } file++; } } } int notation_to_index(int file, int rank) { return (rank - 1) * 16 + (file - 'a'); } void index_to_notation(int index, char notation[2]) { notation[0] = (index & FILE_MASK) + 'a'; notation[1] = (index >> 4) + '1'; } void print_move(Move move) { char move_in_notation[] = "xy XY"; index_to_notation(move.origin, move_in_notation); index_to_notation(move.destination, move_in_notation + 3); printf("%s\n", move_in_notation); }; Move input_move() { Move move; char file; int rank; char file_destination; int rank_destination; scanf(" %c%i %c%i", &file, &rank, &file_destination, &rank_destination); move.origin = notation_to_index(file, rank); move.destination = notation_to_index(file_destination, rank_destination); return move; }; int validate_move(Move move, int color, int* board) { if ((move.origin & 0x88) || (move.destination & 0x88)) return -1; int piece = board[move.origin]; int* legal_move; if (piece % 2 != color) return -3; switch (piece & NO_COLOR) { case KNIGHT: legal_move = knightMoves; break; case BISHOP: legal_move = bishopMoves; break; case ROOK: legal_move = rookMoves; break; case QUEEN: legal_move = queenMoves; break; case KING: legal_move = kingMoves; break; case PAWN: if (piece & BLACK) { if (board[move.destination] != EMPTY) legal_move = blackPawnAttackMoves; else if (move.origin >> 4 == 6) legal_move = newBlackPawnMoves; else legal_move = blackPawnMoves; } else { if (board[move.destination] != EMPTY) legal_move = pawnAttackMoves; else if (move.origin >> 4 == 1) legal_move = newPawnMoves; else legal_move = pawnMoves; } break; default: return -2; } while(*legal_move) { for (int square = move.origin + *legal_move; !(square & 0x88); square += *legal_move) { int target_piece = board[square]; if (square == move.destination) { if (target_piece != EMPTY && target_piece % 2 == color) return -4; return target_piece; } if (target_piece != EMPTY) break; if ((piece & NO_COLOR) == PAWN || (piece & NO_COLOR) == KNIGHT || (piece & NO_COLOR) == KING) break; } legal_move++; } // Handle castling if ((piece & NO_COLOR) == KING) { if (piece % 2 == WHITE && move.origin == 4) { if (move.destination == 2) { for (int i = 1; i < 4; i++) { if (board[i] != EMPTY) return -5; } return 0; } else if (move.destination == 6) { for (int i = 5; i < 7; i++) { if (board[i] != EMPTY) return -5; } return 0; } } else if (piece % 2 == BLACK && move.origin == 116) { if (move.destination == 114) { for (int i = 114; i < 116; i++) { if (board[i] != EMPTY) return -5; } return 0; } else if (move.destination == 118) { for (int i = 117; i < 119; i++) { if (board[i] != EMPTY) return -5; } return 0; } } } return -6; } char* VALIDATION_ERRORS[] = { "trying to access off-board square", "no piece on origin square", "opponent piece on origin square", "trying to capture your own piece", "move is not allowed", "castle is not allowed", }; int apply_move(Move move, int* board) { int piece = board[move.origin]; int target_piece = board[move.destination]; board[move.destination] = piece; board[move.origin] = EMPTY; if (target_piece != EMPTY) { // printf("Captured %s\n", pieces[target_piece]); } if ((piece & NO_COLOR) == KING && abs(move.destination - move.origin) == 2) { // CASTLE! if (move.destination == 2) { int rook = board[0]; board[0] = EMPTY; board[3] = rook; } else if (move.destination == 6) { int rook = board[7]; board[7] = EMPTY; board[5] = rook; } else if (move.destination == 114) { int rook = board[112]; board[112] = EMPTY; board[115] = rook; } else if (move.destination == 118) { int rook = board[119]; board[119] = EMPTY; board[117] = rook; } } return target_piece; } void reverse_move(Move move, int captured_piece, int* board) { int piece = board[move.destination]; board[move.origin] = piece; board[move.destination] = captured_piece; if ((piece & NO_COLOR) == KING && abs(move.destination - move.origin) == 2) { // CASTLE! if (move.destination == 2) { int rook = board[3]; board[3] = EMPTY; board[0] = rook; } else if (move.destination == 6) { int rook = board[5]; board[5] = EMPTY; board[7] = rook; } else if (move.destination == 114) { int rook = board[115]; board[115] = EMPTY; board[112] = rook; } else if (move.destination == 118) { int rook = board[117]; board[117] = EMPTY; board[119] = rook; } } } int evaluate_pawn(int piece, int rank) { int color = piece % 2; if (color == 0) { switch (rank) { case 7: return 9; case 6: return 5; case 5: return 3; default: return 1; } } else { switch (rank) { case 0: return 9; case 1: return 5; case 2: return 3; default: return 1; } } } /* * Compute material advantage of a player over an opponent * Returns number in range (0, 30) */ int compute_material_advantage(int* board, int color) { int counter = 0; for (int rank = 7; rank >= 0; rank--) { for (int file = 0; file < 8; file++) { int piece = board[rank * 16 + file]; if (piece != EMPTY) { int sign = (piece % 2 == color) ? 1 : -1; switch (piece & NO_COLOR) { case KING: counter += INFINITY * sign; break; case PAWN: counter += evaluate_pawn(piece, rank) * sign; break; case KNIGHT: counter += 3 * sign; break; case BISHOP: counter += 3 * sign; break; case ROOK: counter += 4 * sign; break; case QUEEN: counter += 9 * sign; break; default: counter += 1 * sign; break; } } } } return counter; } /* * Calculate amount of squares attack by players pieces * Returns number in range (0, 64) */ int compute_coverage(int* board, int color) { int hit_map[128]; for (int rank = 7; rank >= 0; rank--) { for (int file = 0; file < 8; file++) { hit_map[rank * 16 + file] = 0; } } for (int rank = 7; rank >= 0; rank--) { for (int file = 0; file < 8; file++) { int origin = rank * 16 + file; int piece = board[origin]; if (piece != EMPTY && piece % 2 == color) { int* legal_move; switch (piece & NO_COLOR) { case KNIGHT: legal_move = knightMoves; break; case BISHOP: legal_move = bishopMoves; break; case ROOK: legal_move = rookMoves; break; case QUEEN: legal_move = queenMoves; break; case KING: legal_move = kingMoves; break; case PAWN: if (piece & BLACK) legal_move = blackPawnAttackMoves; else legal_move = pawnAttackMoves; break; default: break; } while(*legal_move) { for (int square = origin + *legal_move; !(square & 0x88); square += *legal_move) { hit_map[square] = 1; int target_piece = board[square]; if (target_piece != EMPTY) break; if ((piece & NO_COLOR) == PAWN || (piece & NO_COLOR) == KNIGHT || (piece & NO_COLOR) == KING) break; } legal_move++; } } } } int counter = 0; for (int rank = 7; rank >= 0; rank--) { for (int file = 0; file < 8; file++) { counter += hit_map[rank * 16 + file]; } } return counter; } /* * Compute player pieces score depending on how * well they are positioned on the board * * Returns number in range(0, 112) */ int compute_positioning_score(int* board, int color) { int total_score = 0; double center = 3.5; for (double rank = 7; rank >= 0; rank--) { for (double file = 0; file < 8; file++) { int index = rank * 16 + file; int piece = board[index]; int score = 7 - (fabs(rank - center) + fabs(file - center)); int multiplier = 1; switch (piece & NO_COLOR) { case KNIGHT: multiplier = 4; break; case BISHOP: multiplier = 3; break; case PAWN: multiplier = 2; break; case KING: multiplier = -1; // Discourage king in center (encourage castle) // TODO: encourage king in center after opponent has low material <= 6 break; default: multiplier = 1; break; } total_score += score * multiplier; } } return total_score; } /* * Return a total board score symbolizing advantage * for WHITE, meaining WHITE tries to maximize this * value and BLACK tries to minimize it. */ int compute_score(int* board) { int material_advantage = compute_material_advantage(board, WHITE); int coverage_score = compute_coverage(board, WHITE) - compute_coverage(board, BLACK); int normalized_coverage = coverage_score / 2; int positioning_score = compute_positioning_score(board, WHITE) - compute_positioning_score(board, BLACK); int normalized_positioning = positioning_score / 7; return material_advantage + coverage_score + positioning_score; } int list_available_moves(Move* moves, int* board, int color) { int moves_count = 0; for (int rank = 7; rank >= 0; rank--) { for (int file = 0; file < 8; file++) { int index = rank * 16 + file; int piece = board[index]; if (piece != EMPTY && (piece % 2) == color) { for (int rank_destination = 7; rank_destination >= 0; rank_destination--) { for (int file_destination = 0; file_destination < 8; file_destination++) { int index_destination = rank_destination * 16 + file_destination; Move move = { index, index_destination, 0 }; if (validate_move(move, color, board) >= 0) { moves[moves_count] = move; moves_count++; } } } } } } return moves_count; } int get_piece_raw_value(int piece) { switch (piece & NO_COLOR) { case KNIGHT: return 3; case BISHOP: return 3; case ROOK: return 5; case QUEEN: return 9; case KING: return INFINITY; case PAWN: return 1; default: return 0; } } int compare_moves(const void* a, const void* b) { return ((Move*)a)->value - ((Move*)b)->value; } void sort_moves(Move* moves, int moves_count, int* board) { for (int i = 0; i < moves_count; i++) { int origin_value = get_piece_raw_value(board[moves[i].origin]); int destination_value = get_piece_raw_value(board[moves[i].destination]); moves[i].value = 10 * destination_value - origin_value; } qsort(moves, moves_count, sizeof(Move), compare_moves); } /* * Alpha-beta pruning * Value here is white material advantage over black * Alpha is the best value for maximizer (white) * Beta is the best value for minimizer (black) */ Move find_best_move(int* board, int color, int depth, int alpha, int beta, int* metrics) { int is_maximizer = (color == 0); Move best_move; best_move.value = is_maximizer ? -INFINITY : INFINITY; Move available_moves[MAX_AVAILABLE_MOVES]; int availabel_moves_count = list_available_moves(available_moves, board, color); sort_moves(available_moves, availabel_moves_count, board); for (int i = 0; i < availabel_moves_count; i++) { *metrics += 1; Move move = available_moves[i]; int captured_piece = apply_move(move, board); move.value = depth < MAX_DEPTH ? find_best_move(board, 1 - color, depth + 1, alpha, beta, metrics).value : compute_score(board); reverse_move(move, captured_piece, board); if (is_maximizer) { if (move.value > best_move.value) best_move = move; alpha = MAX(best_move.value, alpha); } else { if (move.value < best_move.value) best_move = move; beta = MIN(best_move.value, beta); } if (beta <= alpha) break; } return best_move; } int main() { int board[128]; parse_FEN(DEFAULT_FEN, board); print_board(board); Move move; int color = WHITE; while (1) { if (color == PLAYER) { printf("Current score is %i\n", compute_score(board)); printf("White coverage: %i, black coverage: %i\n", compute_coverage(board, WHITE), compute_coverage(board, BLACK)); printf("Enter a move for %s:\n", COLORS[color]); move = input_move(); } else { printf("Evaluating move for %s...\n", COLORS[color]); clock_t start, end; int metrics = 0; start = clock(); move = find_best_move(board, color, 0, -INFINITY, +INFINITY, &metrics); end = clock(); char move_in_notation[] = "xy XY"; index_to_notation(move.origin, move_in_notation); index_to_notation(move.destination, move_in_notation + 3); printf("[%i positions analyzed in %f seconds]\n", metrics, (double)(end - start) / CLOCKS_PER_SEC); printf("Best move for black is %s with score %i in #%i moves\n", move_in_notation, move.value, MAX_DEPTH); } int error = validate_move(move, color, board); if (error < 0) { printf("Invalid move: %s!\n", VALIDATION_ERRORS[-1 - error]); } else { apply_move(move, board); print_board(board); color ^= 1; } } return 0; }