C_chess/move.c

140 lines
3.3 KiB
C

#include "move.h"
#include <stdio.h>
#include <stdlib.h>
#define PAWN 1
#define KNIGHT 2
#define BISHOP 3
#define ROOK 4
#define QUEEN 5
#define KING 6
struct Location PAWN_MOVES[] = {
{0,1},
{-1,1},
{1,1},
{0,2} };
struct Location KNIGHT_MOVES[] = {
{1,-2},
{1,2},
{2,-1},
{2,1},
{-1,-2},
{-1,2},
{-2,-1},
{-2,1} };
struct Location BISHOP_MOVES_MIN[] = {
{-1,-1},
{-1,1},
{1,-1},
{1,1} };
struct Location ROOK_MOVES_MIN[] = {
{0,-1},
{0,1},
{-1,0},
{1,0} };
struct Location QUEEN_MOVES_MIN[] = {
{-1,-1},
{-1,0},
{-1,1},
{0,-1},
{0,1},
{1,-1},
{1,0},
{1,1} };
struct Location KING_MOVES[] = {
{-1,-1},
{-1,0},
{-1,1},
{0,-1},
{0,1},
{1,-1},
{1,0},
{1,1} };
struct LocationNode {
struct Location location;
struct LocationNode* next;
};
struct LocationNode* newNode(struct Location location) {
struct LocationNode* locationNode = (struct LocationNode*) malloc(sizeof(struct LocationNode));
locationNode->location = location;
locationNode->next = NULL;
return locationNode;
};
void append(struct LocationNode** head_ref, struct Location location) {
struct LocationNode* new_node = newNode(location);
struct LocationNode* last = *head_ref;
if (*head_ref == NULL) {
*head_ref = new_node;
return;
}
while (last->next != NULL) {
last = last->next;
}
last->next = new_node;
};
// helper functions
unsigned long sizeofarr(struct Location* arr) {
ulong out = sizeof(BISHOP_MOVES_MIN)/sizeof(BISHOP_MOVES_MIN[0]);
return out;
};
unsigned long sizeofsll(struct LocationNode* head) {
/* Counts the number of nodes in a linked list */
ulong out = 0;
while(head != NULL){
++out;
head = head->next;
};
return out;
};
// converters
struct Location* ll_to_arr(struct LocationNode* head) {
ulong head_size = sizeofsll(head);
struct Location* out[head_size];
for(int i = 0; i < head_size; i++){
out[i] = &head->location;
head = head->next;
};
return *out;
};
struct LocationNode* expand_directions(struct Location* directions) {
struct LocationNode* head = NULL;
for( // expand to all borders
int direction_number = 0;
direction_number < sizeofarr(BISHOP_MOVES_MIN);
direction_number++){
struct Location direction = BISHOP_MOVES_MIN[direction_number];
for(int mult = 1; mult <= 8; mult++){
struct Location extension = {direction.x*mult, direction.y*mult};
append(&head, extension);
};
};
return head;
};
struct Location* getPossibleMoves(struct Location pieceLocation, unsigned int chessPiece) {
struct Location* possibleMoves;
struct LocationNode* head = NULL;
switch(chessPiece) {
{case PAWN:
possibleMoves = PAWN_MOVES;
break;
}{case KNIGHT:
possibleMoves = KNIGHT_MOVES;
break;
}{case BISHOP:
return ll_to_arr(expand_directions(BISHOP_MOVES_MIN));
}{case ROOK:
return ll_to_arr(expand_directions(ROOK_MOVES_MIN));
}{case QUEEN:
return ll_to_arr(expand_directions(QUEEN_MOVES_MIN));
}{case KING:
possibleMoves = KING_MOVES;
break;
}};
return possibleMoves;
};