Refactor diagonal move check to separate function
This commit is contained in:
42
chess.c
42
chess.c
@@ -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) {
|
||||||
|
if (!tile_empty(board[p]))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Returns true if move is a valid bishop move
|
||||||
|
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 diff = to - from;
|
||||||
|
|
||||||
|
if ( diff % (ROW+COL) != 0 && diff % (ROW-COL) != 0 ) {
|
||||||
printf("bishops can only move diagonally");
|
printf("bishops can only move diagonally");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (same_color(board[from], board[to])) {
|
if (!diagonal_move_ok(board, from, to)) {
|
||||||
printf("can't take your own pieces");
|
printf("cant jump over pieces");
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool flying = false;
|
|
||||||
|
|
||||||
for (pos_t p = from + step; p != to - step; p += step) {
|
|
||||||
if (!tile_empty(board[p])) {
|
|
||||||
flying = true;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (flying) {
|
|
||||||
printf("bishops can't jump over pieces");
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user