blob: 1b28ed34d382e2f9e7c9cdf8829125cd1352eaf6 (
plain)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "vector.h"
#include "chesshelpers.h"
board_t init_board(int** pieces) {
board_t board;
board.pieces = pieces;
board.blackKingHasMoved = 0;
board.whiteKingHasMoved = 0;
board.lastPawnMove = 0;
return board;
}
//function applies side effects to board values like king move state
board_t make_move(board_t board, vector_t origin, vector_t end) {
int piece = board.pieces[origin.mx][origin.my];
board.pieces[origin.mx][origin.my] = 0;
board.pieces[end.mx][end.my] = piece;
return board;
}
board_t clone_board(board_t board) {
board_t newBoard;
newBoard.blackKingHasMoved = board.blackKingHasMoved;
newBoard.whiteKingHasMoved = board.whiteKingHasMoved;
newBoard.lastPawnMove = board.lastPawnMove;
int** pieces = malloc(8 * sizeof(int*));
for(int r = 0; r < 8; r++) {
pieces[r] = malloc(8 * sizeof(int));
for(int c = 0; c < 8; c++) {
pieces[r][c] = board.pieces[r][c];
}
}
newBoard.pieces = pieces;
return newBoard;
}
int in_board(vector_t position) {
return position.mx < 8 && position.mx >= 0 && position.my < 8 && position.my >= 0;
}
int is_empty(board_t board, vector_t position) {
return board.pieces[position.mx][position.my] == 0;
}
int is_color(board_t board, vector_t position, int color) {
if(color == 0) {
return board.pieces[position.mx][position.my] >= 1 && board.pieces[position.mx][position.my] <= 6;
}
else {
return board.pieces[position.mx][position.my] >= 7;
}
}
//converts board coordinates into algebraic notation
char* get_readable_coords(vector_t position) {
char* output = malloc(3 * sizeof(char));
output[0] = 'a' + position.mx;
output[1] = '8' - position.my;
output[2] = '\0';
return output;
}
//gets the proper algebraic notation for the move
char* get_move_name(board_t board, vector_t origin, vector_t end) {
int piece = board.pieces[origin.mx][origin.my];
if(piece > 6) {
piece -= 6;
}
if(piece != 1) {
char cPiece = piece == pawn ? 'P' : piece == knight ? 'N' : piece == bishop ? 'B' : piece == rook ? 'R' : piece == queen ? 'Q' : 'K';
int isCapture = board.pieces[end.mx][end.my] != 0;
char* output = calloc(isCapture ? 5 : 4, sizeof(char));
output[0] = cPiece;
if(isCapture) {
output[1] = 'x';
}
char* rEnd = get_readable_coords(end);
strcat(output, rEnd);
free(rEnd);
output[isCapture ? 4 : 3] = '\0';
return output;
}
else {
int isCapture = board.pieces[end.mx][end.my] != 0;
char* output = calloc(isCapture ? 5 : 3, sizeof(char));
if(isCapture) {
output[0] = 'a' + origin.mx;
output[1] = 'x';
}
char* rEnd = get_readable_coords(end);
strcat(output, rEnd);
free(rEnd);
output[isCapture ? 4 : 2] = '\0';
return output;
}
}
|