Fixes #46 - Use red background for king and threatening piece when king is checked

Part-of: <https://gitlab.gnome.org/GNOME/gnome-chess/-/merge_requests/50>
This commit is contained in:
azibom 2023-09-29 15:22:39 +03:30
parent f6a7d76946
commit b4cd8909e7
3 changed files with 47 additions and 2 deletions

View file

@ -369,4 +369,32 @@ public class ChessGame : Object
_clock.stop ();
ended ();
}
public bool is_king_under_attack_at_position (int rank, int file)
{
if (!current_state.is_in_check (current_player))
return false;
var piece = get_piece (rank, file);
if (piece == null || piece.type != PieceType.KING)
return false;
if (piece.player.color == Color.WHITE && current_player.color == Color.WHITE)
return true;
if (piece.player.color == Color.BLACK && current_player.color == Color.BLACK)
return true;
return false;
}
public bool is_piece_at_position_threatening_check (int rank, int file)
{
int threatening_rank, threatening_file;
if (current_state.get_position_threatening_king (current_player, out threatening_rank, out threatening_file) && threatening_rank == rank && threatening_file == file)
return true;
return false;
}
}

View file

@ -595,7 +595,7 @@ public class ChessState : Object
return CheckState.NONE;
}
public bool is_in_check (ChessPlayer player)
public bool get_position_threatening_king (ChessPlayer player, out int rank, out int file)
{
var opponent = player.color == Color.WHITE ? players[Color.BLACK] : players[Color.WHITE];
@ -612,7 +612,11 @@ public class ChessState : Object
get_rank (start), get_file (start),
get_rank (king_index), get_file (king_index),
PieceType.QUEEN, false, false))
return true;
{
rank = get_rank (start);
file = get_file (start);
return true;
}
}
}
}
@ -620,6 +624,12 @@ public class ChessState : Object
return false;
}
public bool is_in_check (ChessPlayer player)
{
int rank, file;
return get_position_threatening_king (player, out rank, out file);
}
private bool is_in_checkmate (ChessPlayer player)
{
/* Is in checkmate if no pieces can move */

View file

@ -138,6 +138,13 @@ public class ChessView : Gtk.DrawingArea
c.set_source_rgb (0xba/255.0, 0xbd/255.0, 0xb6/255.0);
else
c.set_source_rgb (0xee/255.0, 0xee/255.0, 0xec/255.0);
if (!scene.animating && scene.game.is_king_under_attack_at_position (rank, file))
c.set_source_rgb (0xd4/255.0, 0x97/255.0, 0x95/255.0);
if (!scene.animating && scene.game.is_piece_at_position_threatening_check (rank, file))
c.set_source_rgb (0xd4/255.0, 0x97/255.0, 0x95/255.0);
c.fill ();
}
}