Refactor diagonal move check to separate function

This commit is contained in:
Ole Morud
2023-03-19 18:09:32 +01:00
parent 4dbd0140d0
commit 7a2f961c69

50
chess.c
View File

@@ -346,11 +346,7 @@ bool pawn_move_ok(tile_t const* board, pos_t from, pos_t to, int direction)
} }
} }
/* Returns true if move is a valid bishop move bool diagonal_move_ok(tile_t const *board, pos_t from, pos_t to)
board - array of tiles representing chess board state
from - index of board bishop is at
to - index of board bishop wants to move to */
bool bishop_move_ok(tile_t const* board, pos_t from, pos_t to)
{ {
pos_t const col_diff = column(to) - column(from); pos_t const col_diff = column(to) - column(from);
pos_t const row_diff = row(to) - row(from); pos_t const row_diff = row(to) - row(from);
@@ -359,27 +355,29 @@ bool bishop_move_ok(tile_t const* board, pos_t from, pos_t to)
pos_t const y_step = ROW * row_diff / abs_pos(row_diff); pos_t const y_step = ROW * row_diff / abs_pos(row_diff);
pos_t const step = x_step + y_step; pos_t const step = x_step + y_step;
if (abs_pos(row_diff) != abs_pos(col_diff)) { for (pos_t p = from + step; p != to; p += step) {
printf("bishops can only move diagonally"); if (!tile_empty(board[p]))
return false; return false;
} }
if (same_color(board[from], board[to])) { return true;
printf("can't take your own pieces"); }
return false;
} /* Returns true if move is a valid bishop move
board - array of tiles representing chess board state
bool flying = false; from - index of board bishop is at
to - index of board bishop wants to move to */
for (pos_t p = from + step; p != to - step; p += step) { bool bishop_move_ok(tile_t const* board, pos_t from, pos_t to)
if (!tile_empty(board[p])) { {
flying = true; pos_t const diff = to - from;
break;
} if ( diff % (ROW+COL) != 0 && diff % (ROW-COL) != 0 ) {
} printf("bishops can only move diagonally");
return false;
if (flying) { }
printf("bishops can't jump over pieces");
if (!diagonal_move_ok(board, from, to)) {
printf("cant jump over pieces");
return false; return false;
} }