mirror of
https://github.com/RGBCube/serenity
synced 2025-07-28 04:57:45 +00:00
Games: Move to Userland/Games/
This commit is contained in:
parent
b8d6a56fa3
commit
aa939c4b4b
49 changed files with 1 additions and 1 deletions
9
Userland/Games/Chess/CMakeLists.txt
Normal file
9
Userland/Games/Chess/CMakeLists.txt
Normal file
|
@ -0,0 +1,9 @@
|
|||
set(SOURCES
|
||||
main.cpp
|
||||
ChessWidget.cpp
|
||||
PromotionDialog.cpp
|
||||
Engine.cpp
|
||||
)
|
||||
|
||||
serenity_app(Chess ICON app-chess)
|
||||
target_link_libraries(Chess LibChess LibGUI LibCore)
|
659
Userland/Games/Chess/ChessWidget.cpp
Normal file
659
Userland/Games/Chess/ChessWidget.cpp
Normal file
|
@ -0,0 +1,659 @@
|
|||
/*
|
||||
* Copyright (c) 2020, the SerenityOS developers.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include "ChessWidget.h"
|
||||
#include "PromotionDialog.h"
|
||||
#include <AK/String.h>
|
||||
#include <LibCore/DateTime.h>
|
||||
#include <LibCore/File.h>
|
||||
#include <LibGUI/MessageBox.h>
|
||||
#include <LibGUI/Painter.h>
|
||||
#include <LibGfx/Font.h>
|
||||
#include <LibGfx/FontDatabase.h>
|
||||
#include <LibGfx/Path.h>
|
||||
#include <unistd.h>
|
||||
|
||||
ChessWidget::ChessWidget(const StringView& set)
|
||||
{
|
||||
set_piece_set(set);
|
||||
}
|
||||
|
||||
ChessWidget::ChessWidget()
|
||||
: ChessWidget("stelar7")
|
||||
{
|
||||
}
|
||||
|
||||
ChessWidget::~ChessWidget()
|
||||
{
|
||||
}
|
||||
|
||||
void ChessWidget::paint_event(GUI::PaintEvent& event)
|
||||
{
|
||||
GUI::Widget::paint_event(event);
|
||||
|
||||
GUI::Painter painter(*this);
|
||||
painter.add_clip_rect(event.rect());
|
||||
|
||||
size_t tile_width = width() / 8;
|
||||
size_t tile_height = height() / 8;
|
||||
unsigned coord_rank_file = (side() == Chess::Color::White) ? 0 : 7;
|
||||
|
||||
Chess::Board& active_board = (m_playback ? board_playback() : board());
|
||||
|
||||
Chess::Square::for_each([&](Chess::Square sq) {
|
||||
Gfx::IntRect tile_rect;
|
||||
if (side() == Chess::Color::White) {
|
||||
tile_rect = { sq.file * tile_width, (7 - sq.rank) * tile_height, tile_width, tile_height };
|
||||
} else {
|
||||
tile_rect = { (7 - sq.file) * tile_width, sq.rank * tile_height, tile_width, tile_height };
|
||||
}
|
||||
|
||||
painter.fill_rect(tile_rect, (sq.is_light()) ? board_theme().light_square_color : board_theme().dark_square_color);
|
||||
|
||||
if (active_board.last_move().has_value() && (active_board.last_move().value().to == sq || active_board.last_move().value().from == sq)) {
|
||||
painter.fill_rect(tile_rect, m_move_highlight_color);
|
||||
}
|
||||
|
||||
if (m_coordinates) {
|
||||
auto coord = sq.to_algebraic();
|
||||
auto text_color = (sq.is_light()) ? board_theme().dark_square_color : board_theme().light_square_color;
|
||||
|
||||
auto shrunken_rect = tile_rect;
|
||||
shrunken_rect.shrink(4, 4);
|
||||
if (sq.rank == coord_rank_file)
|
||||
painter.draw_text(shrunken_rect, coord.substring_view(0, 1), Gfx::FontDatabase::default_bold_font(), Gfx::TextAlignment::BottomRight, text_color);
|
||||
|
||||
if (sq.file == coord_rank_file)
|
||||
painter.draw_text(shrunken_rect, coord.substring_view(1, 1), Gfx::FontDatabase::default_bold_font(), Gfx::TextAlignment::TopLeft, text_color);
|
||||
}
|
||||
|
||||
for (auto& m : m_board_markings) {
|
||||
if (m.type() == BoardMarking::Type::Square && m.from == sq) {
|
||||
Gfx::Color color = m.secondary_color ? m_marking_secondary_color : (m.alternate_color ? m_marking_alternate_color : m_marking_primary_color);
|
||||
painter.fill_rect(tile_rect, color);
|
||||
}
|
||||
}
|
||||
|
||||
if (!(m_dragging_piece && sq == m_moving_square)) {
|
||||
auto bmp = m_pieces.get(active_board.get_piece(sq));
|
||||
if (bmp.has_value()) {
|
||||
painter.draw_scaled_bitmap(tile_rect, *bmp.value(), bmp.value()->rect());
|
||||
}
|
||||
}
|
||||
|
||||
return IterationDecision::Continue;
|
||||
});
|
||||
|
||||
auto draw_arrow = [&painter](Gfx::FloatPoint A, Gfx::FloatPoint B, float w1, float w2, float h, Gfx::Color color) {
|
||||
float dx = B.x() - A.x();
|
||||
float dy = A.y() - B.y();
|
||||
float phi = atan2f(dy, dx);
|
||||
float hdx = h * cos(phi);
|
||||
float hdy = h * sin(phi);
|
||||
|
||||
Gfx::FloatPoint A1(A.x() - (w1 / 2) * cos(M_PI_2 - phi), A.y() - (w1 / 2) * sin(M_PI_2 - phi));
|
||||
Gfx::FloatPoint B3(A.x() + (w1 / 2) * cos(M_PI_2 - phi), A.y() + (w1 / 2) * sin(M_PI_2 - phi));
|
||||
Gfx::FloatPoint A2(A1.x() + (dx - hdx), A1.y() - (dy - hdy));
|
||||
Gfx::FloatPoint B2(B3.x() + (dx - hdx), B3.y() - (dy - hdy));
|
||||
Gfx::FloatPoint A3(A2.x() - w2 * cos(M_PI_2 - phi), A2.y() - w2 * sin(M_PI_2 - phi));
|
||||
Gfx::FloatPoint B1(B2.x() + w2 * cos(M_PI_2 - phi), B2.y() + w2 * sin(M_PI_2 - phi));
|
||||
|
||||
auto path = Gfx::Path();
|
||||
path.move_to(A);
|
||||
path.line_to(A1);
|
||||
path.line_to(A2);
|
||||
path.line_to(A3);
|
||||
path.line_to(B);
|
||||
path.line_to(B1);
|
||||
path.line_to(B2);
|
||||
path.line_to(B3);
|
||||
path.line_to(A);
|
||||
path.close();
|
||||
|
||||
painter.fill_path(path, color, Gfx::Painter::WindingRule::EvenOdd);
|
||||
};
|
||||
|
||||
for (auto& m : m_board_markings) {
|
||||
if (m.type() == BoardMarking::Type::Arrow) {
|
||||
Gfx::FloatPoint arrow_start;
|
||||
Gfx::FloatPoint arrow_end;
|
||||
|
||||
if (side() == Chess::Color::White) {
|
||||
arrow_start = { m.from.file * tile_width + tile_width / 2.0f, (7 - m.from.rank) * tile_height + tile_height / 2.0f };
|
||||
arrow_end = { m.to.file * tile_width + tile_width / 2.0f, (7 - m.to.rank) * tile_height + tile_height / 2.0f };
|
||||
} else {
|
||||
arrow_start = { (7 - m.from.file) * tile_width + tile_width / 2.0f, m.from.rank * tile_height + tile_height / 2.0f };
|
||||
arrow_end = { (7 - m.to.file) * tile_width + tile_width / 2.0f, m.to.rank * tile_height + tile_height / 2.0f };
|
||||
}
|
||||
|
||||
Gfx::Color color = m.secondary_color ? m_marking_secondary_color : (m.alternate_color ? m_marking_primary_color : m_marking_alternate_color);
|
||||
draw_arrow(arrow_start, arrow_end, tile_width / 8.0f, tile_width / 10.0f, tile_height / 2.5f, color);
|
||||
}
|
||||
}
|
||||
|
||||
if (m_dragging_piece) {
|
||||
auto bmp = m_pieces.get(active_board.get_piece(m_moving_square));
|
||||
if (bmp.has_value()) {
|
||||
auto center = m_drag_point - Gfx::IntPoint(tile_width / 2, tile_height / 2);
|
||||
painter.draw_scaled_bitmap({ center, { tile_width, tile_height } }, *bmp.value(), bmp.value()->rect());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ChessWidget::mousedown_event(GUI::MouseEvent& event)
|
||||
{
|
||||
GUI::Widget::mousedown_event(event);
|
||||
|
||||
if (event.button() == GUI::MouseButton::Right) {
|
||||
m_current_marking.from = mouse_to_square(event);
|
||||
return;
|
||||
}
|
||||
m_board_markings.clear();
|
||||
|
||||
auto square = mouse_to_square(event);
|
||||
auto piece = board().get_piece(square);
|
||||
if (drag_enabled() && piece.color == board().turn() && !m_playback) {
|
||||
m_dragging_piece = true;
|
||||
m_drag_point = event.position();
|
||||
m_moving_square = square;
|
||||
}
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
void ChessWidget::mouseup_event(GUI::MouseEvent& event)
|
||||
{
|
||||
GUI::Widget::mouseup_event(event);
|
||||
|
||||
if (event.button() == GUI::MouseButton::Right) {
|
||||
m_current_marking.secondary_color = event.shift();
|
||||
m_current_marking.alternate_color = event.ctrl();
|
||||
m_current_marking.to = mouse_to_square(event);
|
||||
auto match_index = m_board_markings.find_first_index(m_current_marking);
|
||||
if (match_index.has_value()) {
|
||||
m_board_markings.remove(match_index.value());
|
||||
update();
|
||||
return;
|
||||
}
|
||||
m_board_markings.append(m_current_marking);
|
||||
update();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!m_dragging_piece)
|
||||
return;
|
||||
|
||||
m_dragging_piece = false;
|
||||
|
||||
auto target_square = mouse_to_square(event);
|
||||
|
||||
Chess::Move move = { m_moving_square, target_square };
|
||||
if (board().is_promotion_move(move)) {
|
||||
auto promotion_dialog = PromotionDialog::construct(*this);
|
||||
if (promotion_dialog->exec() == PromotionDialog::ExecOK)
|
||||
move.promote_to = promotion_dialog->selected_piece();
|
||||
}
|
||||
|
||||
if (board().apply_move(move)) {
|
||||
m_playback_move_number = board().moves().size();
|
||||
m_playback = false;
|
||||
m_board_playback = m_board;
|
||||
|
||||
if (board().game_result() != Chess::Board::Result::NotFinished) {
|
||||
bool over = true;
|
||||
String msg;
|
||||
switch (board().game_result()) {
|
||||
case Chess::Board::Result::CheckMate:
|
||||
if (board().turn() == Chess::Color::White) {
|
||||
msg = "Black wins by Checkmate.";
|
||||
} else {
|
||||
msg = "White wins by Checkmate.";
|
||||
}
|
||||
break;
|
||||
case Chess::Board::Result::StaleMate:
|
||||
msg = "Draw by Stalemate.";
|
||||
break;
|
||||
case Chess::Board::Result::FiftyMoveRule:
|
||||
update();
|
||||
if (GUI::MessageBox::show(window(), "50 moves have elapsed without a capture. Claim Draw?", "Claim Draw?",
|
||||
GUI::MessageBox::Type::Information, GUI::MessageBox::InputType::YesNo)
|
||||
== GUI::Dialog::ExecYes) {
|
||||
msg = "Draw by 50 move rule.";
|
||||
} else {
|
||||
over = false;
|
||||
}
|
||||
break;
|
||||
case Chess::Board::Result::SeventyFiveMoveRule:
|
||||
msg = "Draw by 75 move rule.";
|
||||
break;
|
||||
case Chess::Board::Result::ThreeFoldRepetition:
|
||||
update();
|
||||
if (GUI::MessageBox::show(window(), "The same board state has repeated three times. Claim Draw?", "Claim Draw?",
|
||||
GUI::MessageBox::Type::Information, GUI::MessageBox::InputType::YesNo)
|
||||
== GUI::Dialog::ExecYes) {
|
||||
msg = "Draw by threefold repetition.";
|
||||
} else {
|
||||
over = false;
|
||||
}
|
||||
break;
|
||||
case Chess::Board::Result::FiveFoldRepetition:
|
||||
msg = "Draw by fivefold repetition.";
|
||||
break;
|
||||
case Chess::Board::Result::InsufficientMaterial:
|
||||
msg = "Draw by insufficient material.";
|
||||
break;
|
||||
default:
|
||||
ASSERT_NOT_REACHED();
|
||||
}
|
||||
if (over) {
|
||||
set_drag_enabled(false);
|
||||
update();
|
||||
GUI::MessageBox::show(window(), msg, "Game Over", GUI::MessageBox::Type::Information);
|
||||
}
|
||||
} else {
|
||||
input_engine_move();
|
||||
}
|
||||
}
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
void ChessWidget::mousemove_event(GUI::MouseEvent& event)
|
||||
{
|
||||
GUI::Widget::mousemove_event(event);
|
||||
if (!m_dragging_piece)
|
||||
return;
|
||||
|
||||
m_drag_point = event.position();
|
||||
update();
|
||||
}
|
||||
|
||||
void ChessWidget::keydown_event(GUI::KeyEvent& event)
|
||||
{
|
||||
switch (event.key()) {
|
||||
case KeyCode::Key_Left:
|
||||
playback_move(PlaybackDirection::Backward);
|
||||
break;
|
||||
case KeyCode::Key_Right:
|
||||
playback_move(PlaybackDirection::Forward);
|
||||
break;
|
||||
case KeyCode::Key_Up:
|
||||
playback_move(PlaybackDirection::Last);
|
||||
break;
|
||||
case KeyCode::Key_Down:
|
||||
playback_move(PlaybackDirection::First);
|
||||
break;
|
||||
case KeyCode::Key_Home:
|
||||
playback_move(PlaybackDirection::First);
|
||||
break;
|
||||
case KeyCode::Key_End:
|
||||
playback_move(PlaybackDirection::Last);
|
||||
break;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
static String set_path = String("/res/icons/chess/sets/");
|
||||
|
||||
static RefPtr<Gfx::Bitmap> get_piece(const StringView& set, const StringView& image)
|
||||
{
|
||||
StringBuilder builder;
|
||||
builder.append(set_path);
|
||||
builder.append(set);
|
||||
builder.append('/');
|
||||
builder.append(image);
|
||||
return Gfx::Bitmap::load_from_file(builder.build());
|
||||
}
|
||||
|
||||
void ChessWidget::set_piece_set(const StringView& set)
|
||||
{
|
||||
m_piece_set = set;
|
||||
m_pieces.set({ Chess::Color::White, Chess::Type::Pawn }, get_piece(set, "white-pawn.png"));
|
||||
m_pieces.set({ Chess::Color::Black, Chess::Type::Pawn }, get_piece(set, "black-pawn.png"));
|
||||
m_pieces.set({ Chess::Color::White, Chess::Type::Knight }, get_piece(set, "white-knight.png"));
|
||||
m_pieces.set({ Chess::Color::Black, Chess::Type::Knight }, get_piece(set, "black-knight.png"));
|
||||
m_pieces.set({ Chess::Color::White, Chess::Type::Bishop }, get_piece(set, "white-bishop.png"));
|
||||
m_pieces.set({ Chess::Color::Black, Chess::Type::Bishop }, get_piece(set, "black-bishop.png"));
|
||||
m_pieces.set({ Chess::Color::White, Chess::Type::Rook }, get_piece(set, "white-rook.png"));
|
||||
m_pieces.set({ Chess::Color::Black, Chess::Type::Rook }, get_piece(set, "black-rook.png"));
|
||||
m_pieces.set({ Chess::Color::White, Chess::Type::Queen }, get_piece(set, "white-queen.png"));
|
||||
m_pieces.set({ Chess::Color::Black, Chess::Type::Queen }, get_piece(set, "black-queen.png"));
|
||||
m_pieces.set({ Chess::Color::White, Chess::Type::King }, get_piece(set, "white-king.png"));
|
||||
m_pieces.set({ Chess::Color::Black, Chess::Type::King }, get_piece(set, "black-king.png"));
|
||||
}
|
||||
|
||||
Chess::Square ChessWidget::mouse_to_square(GUI::MouseEvent& event) const
|
||||
{
|
||||
size_t tile_width = width() / 8;
|
||||
size_t tile_height = height() / 8;
|
||||
|
||||
if (side() == Chess::Color::White) {
|
||||
return { 7 - (event.y() / tile_height), event.x() / tile_width };
|
||||
} else {
|
||||
return { event.y() / tile_height, 7 - (event.x() / tile_width) };
|
||||
}
|
||||
}
|
||||
|
||||
RefPtr<Gfx::Bitmap> ChessWidget::get_piece_graphic(const Chess::Piece& piece) const
|
||||
{
|
||||
return m_pieces.get(piece).value();
|
||||
}
|
||||
|
||||
void ChessWidget::reset()
|
||||
{
|
||||
m_board_markings.clear();
|
||||
m_playback = false;
|
||||
m_playback_move_number = 0;
|
||||
m_board_playback = Chess::Board();
|
||||
m_board = Chess::Board();
|
||||
m_side = (arc4random() % 2) ? Chess::Color::White : Chess::Color::Black;
|
||||
m_drag_enabled = true;
|
||||
input_engine_move();
|
||||
update();
|
||||
}
|
||||
|
||||
void ChessWidget::set_board_theme(const StringView& name)
|
||||
{
|
||||
// FIXME: Add some kind of themes.json
|
||||
// The following Colors have been taken from lichess.org, but i'm pretty sure they took them from chess.com.
|
||||
if (name == "Beige") {
|
||||
m_board_theme = { "Beige", Color::from_rgb(0xb58863), Color::from_rgb(0xf0d9b5) };
|
||||
} else if (name == "Green") {
|
||||
m_board_theme = { "Green", Color::from_rgb(0x86a666), Color::from_rgb(0xffffdd) };
|
||||
} else if (name == "Blue") {
|
||||
m_board_theme = { "Blue", Color::from_rgb(0x8ca2ad), Color::from_rgb(0xdee3e6) };
|
||||
} else {
|
||||
set_board_theme("Beige");
|
||||
}
|
||||
}
|
||||
|
||||
bool ChessWidget::want_engine_move()
|
||||
{
|
||||
if (!m_engine)
|
||||
return false;
|
||||
if (board().turn() == side())
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
void ChessWidget::input_engine_move()
|
||||
{
|
||||
if (!want_engine_move())
|
||||
return;
|
||||
|
||||
bool drag_was_enabled = drag_enabled();
|
||||
if (drag_was_enabled)
|
||||
set_drag_enabled(false);
|
||||
|
||||
set_override_cursor(Gfx::StandardCursor::Wait);
|
||||
m_engine->get_best_move(board(), 4000, [this, drag_was_enabled](Chess::Move move) {
|
||||
set_override_cursor(Gfx::StandardCursor::None);
|
||||
if (!want_engine_move())
|
||||
return;
|
||||
set_drag_enabled(drag_was_enabled);
|
||||
ASSERT(board().apply_move(move));
|
||||
m_playback_move_number = m_board.moves().size();
|
||||
m_playback = false;
|
||||
m_board_markings.clear();
|
||||
update();
|
||||
});
|
||||
}
|
||||
|
||||
void ChessWidget::playback_move(PlaybackDirection direction)
|
||||
{
|
||||
if (m_board.moves().is_empty())
|
||||
return;
|
||||
|
||||
m_playback = true;
|
||||
m_board_markings.clear();
|
||||
|
||||
switch (direction) {
|
||||
case PlaybackDirection::Backward:
|
||||
if (m_playback_move_number == 0)
|
||||
return;
|
||||
m_board_playback = Chess::Board();
|
||||
for (size_t i = 0; i < m_playback_move_number - 1; i++)
|
||||
m_board_playback.apply_move(m_board.moves().at(i));
|
||||
m_playback_move_number--;
|
||||
break;
|
||||
case PlaybackDirection::Forward:
|
||||
if (m_playback_move_number + 1 > m_board.moves().size()) {
|
||||
m_playback = false;
|
||||
return;
|
||||
}
|
||||
m_board_playback.apply_move(m_board.moves().at(m_playback_move_number++));
|
||||
if (m_playback_move_number == m_board.moves().size())
|
||||
m_playback = false;
|
||||
break;
|
||||
case PlaybackDirection::First:
|
||||
m_board_playback = Chess::Board();
|
||||
m_playback_move_number = 0;
|
||||
break;
|
||||
case PlaybackDirection::Last:
|
||||
while (m_playback) {
|
||||
playback_move(PlaybackDirection::Forward);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
ASSERT_NOT_REACHED();
|
||||
}
|
||||
update();
|
||||
}
|
||||
|
||||
String ChessWidget::get_fen() const
|
||||
{
|
||||
return m_playback ? m_board_playback.to_fen() : m_board.to_fen();
|
||||
}
|
||||
|
||||
bool ChessWidget::import_pgn(const StringView& import_path)
|
||||
{
|
||||
auto file_or_error = Core::File::open(import_path, Core::File::OpenMode::ReadOnly);
|
||||
if (file_or_error.is_error()) {
|
||||
warnln("Couldn't open '{}': {}", import_path, file_or_error.error());
|
||||
return false;
|
||||
}
|
||||
auto& file = *file_or_error.value();
|
||||
|
||||
m_board = Chess::Board();
|
||||
|
||||
ByteBuffer bytes = file.read_all();
|
||||
StringView content = bytes;
|
||||
auto lines = content.lines();
|
||||
StringView line;
|
||||
size_t i = 0;
|
||||
|
||||
// Tag Pair Section
|
||||
// FIXME: Parse these tags when they become relevant
|
||||
do {
|
||||
line = lines.at(i++);
|
||||
} while (!line.is_empty() || i >= lines.size());
|
||||
|
||||
// Movetext Section
|
||||
bool skip = false;
|
||||
bool recursive_annotation = false;
|
||||
bool future_expansion = false;
|
||||
Chess::Color turn = Chess::Color::White;
|
||||
String movetext;
|
||||
|
||||
for (size_t j = i; j < lines.size(); j++)
|
||||
movetext = String::formatted("{}{}", movetext, lines.at(i).to_string());
|
||||
|
||||
for (auto token : movetext.split(' ')) {
|
||||
token = token.trim_whitespace();
|
||||
|
||||
// FIXME: Parse all of these tokens when we start caring about them
|
||||
if (token.ends_with("}")) {
|
||||
skip = false;
|
||||
continue;
|
||||
}
|
||||
if (skip)
|
||||
continue;
|
||||
if (token.starts_with("{")) {
|
||||
if (token.ends_with("}"))
|
||||
continue;
|
||||
skip = true;
|
||||
continue;
|
||||
}
|
||||
if (token.ends_with(")")) {
|
||||
recursive_annotation = false;
|
||||
continue;
|
||||
}
|
||||
if (recursive_annotation)
|
||||
continue;
|
||||
if (token.starts_with("(")) {
|
||||
if (token.ends_with(")"))
|
||||
continue;
|
||||
recursive_annotation = true;
|
||||
continue;
|
||||
}
|
||||
if (token.ends_with(">")) {
|
||||
future_expansion = false;
|
||||
continue;
|
||||
}
|
||||
if (future_expansion)
|
||||
continue;
|
||||
if (token.starts_with("<")) {
|
||||
if (token.ends_with(">"))
|
||||
continue;
|
||||
future_expansion = true;
|
||||
continue;
|
||||
}
|
||||
if (token.starts_with("$"))
|
||||
continue;
|
||||
if (token.contains("*"))
|
||||
break;
|
||||
// FIXME: When we become able to set more of the game state, fix these end results
|
||||
if (token.contains("1-0")) {
|
||||
m_board.set_resigned(Chess::Color::Black);
|
||||
break;
|
||||
}
|
||||
if (token.contains("0-1")) {
|
||||
m_board.set_resigned(Chess::Color::White);
|
||||
break;
|
||||
}
|
||||
if (token.contains("1/2-1/2")) {
|
||||
break;
|
||||
}
|
||||
if (!token.ends_with(".")) {
|
||||
m_board.apply_move(Chess::Move::from_algebraic(token, turn, m_board));
|
||||
turn = Chess::opposing_color(turn);
|
||||
}
|
||||
}
|
||||
|
||||
m_board_markings.clear();
|
||||
m_board_playback = m_board;
|
||||
m_playback_move_number = m_board_playback.moves().size();
|
||||
m_playback = true;
|
||||
update();
|
||||
|
||||
file.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ChessWidget::export_pgn(const StringView& export_path) const
|
||||
{
|
||||
auto file_or_error = Core::File::open(export_path, Core::File::WriteOnly);
|
||||
if (file_or_error.is_error()) {
|
||||
warnln("Couldn't open '{}': {}", export_path, file_or_error.error());
|
||||
return false;
|
||||
}
|
||||
auto& file = *file_or_error.value();
|
||||
|
||||
// Tag Pair Section
|
||||
file.write("[Event \"Casual Game\"]\n");
|
||||
file.write("[Site \"SerenityOS Chess\"]\n");
|
||||
file.write(String::formatted("[Date \"{}\"]\n", Core::DateTime::now().to_string("%Y.%m.%d")));
|
||||
file.write("[Round \"1\"]\n");
|
||||
|
||||
String username(getlogin());
|
||||
const String player1 = (!username.is_empty() ? username : "?");
|
||||
const String player2 = (!m_engine.is_null() ? "SerenityOS ChessEngine" : "?");
|
||||
file.write(String::formatted("[White \"{}\"]\n", m_side == Chess::Color::White ? player1 : player2));
|
||||
file.write(String::formatted("[Black \"{}\"]\n", m_side == Chess::Color::Black ? player1 : player2));
|
||||
|
||||
file.write(String::formatted("[Result \"{}\"]\n", Chess::Board::result_to_points(m_board.game_result(), m_board.turn())));
|
||||
file.write("[WhiteElo \"?\"]\n");
|
||||
file.write("[BlackElo \"?\"]\n");
|
||||
file.write("[Variant \"Standard\"]\n");
|
||||
file.write("[TimeControl \"-\"]\n");
|
||||
file.write("[Annotator \"SerenityOS Chess\"]\n");
|
||||
file.write("\n");
|
||||
|
||||
// Movetext Section
|
||||
for (size_t i = 0, move_no = 1; i < m_board.moves().size(); i += 2, move_no++) {
|
||||
const String white = m_board.moves().at(i).to_algebraic();
|
||||
|
||||
if (i + 1 < m_board.moves().size()) {
|
||||
const String black = m_board.moves().at(i + 1).to_algebraic();
|
||||
file.write(String::formatted("{}. {} {} ", move_no, white, black));
|
||||
} else {
|
||||
file.write(String::formatted("{}. {} ", move_no, white));
|
||||
}
|
||||
}
|
||||
|
||||
file.write("{ ");
|
||||
file.write(Chess::Board::result_to_string(m_board.game_result(), m_board.turn()));
|
||||
file.write(" } ");
|
||||
file.write(Chess::Board::result_to_points(m_board.game_result(), m_board.turn()));
|
||||
file.write("\n");
|
||||
|
||||
file.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
void ChessWidget::flip_board()
|
||||
{
|
||||
if (want_engine_move()) {
|
||||
GUI::MessageBox::show(window(), "You can only flip the board on your turn.", "Flip Board", GUI::MessageBox::Type::Information);
|
||||
return;
|
||||
}
|
||||
m_side = Chess::opposing_color(m_side);
|
||||
input_engine_move();
|
||||
update();
|
||||
}
|
||||
|
||||
int ChessWidget::resign()
|
||||
{
|
||||
if (want_engine_move()) {
|
||||
GUI::MessageBox::show(window(), "You can only resign on your turn.", "Resign", GUI::MessageBox::Type::Information);
|
||||
return -1;
|
||||
}
|
||||
|
||||
auto result = GUI::MessageBox::show(window(), "Are you sure you wish to resign?", "Resign", GUI::MessageBox::Type::Warning, GUI::MessageBox::InputType::YesNo);
|
||||
if (result != GUI::MessageBox::ExecYes)
|
||||
return -1;
|
||||
|
||||
board().set_resigned(m_board.turn());
|
||||
|
||||
set_drag_enabled(false);
|
||||
update();
|
||||
const String msg = Chess::Board::result_to_string(m_board.game_result(), m_board.turn());
|
||||
GUI::MessageBox::show(window(), msg, "Game Over", GUI::MessageBox::Type::Information);
|
||||
|
||||
return 0;
|
||||
}
|
147
Userland/Games/Chess/ChessWidget.h
Normal file
147
Userland/Games/Chess/ChessWidget.h
Normal file
|
@ -0,0 +1,147 @@
|
|||
/*
|
||||
* Copyright (c) 2020, the SerenityOS developers.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Engine.h"
|
||||
#include <AK/HashMap.h>
|
||||
#include <AK/NonnullRefPtr.h>
|
||||
#include <AK/Optional.h>
|
||||
#include <AK/StringView.h>
|
||||
#include <LibChess/Chess.h>
|
||||
#include <LibGUI/Widget.h>
|
||||
#include <LibGfx/Bitmap.h>
|
||||
|
||||
class ChessWidget final : public GUI::Widget {
|
||||
C_OBJECT(ChessWidget)
|
||||
public:
|
||||
ChessWidget();
|
||||
ChessWidget(const StringView& set);
|
||||
virtual ~ChessWidget() override;
|
||||
|
||||
virtual void paint_event(GUI::PaintEvent&) override;
|
||||
virtual void mousedown_event(GUI::MouseEvent&) override;
|
||||
virtual void mouseup_event(GUI::MouseEvent&) override;
|
||||
virtual void mousemove_event(GUI::MouseEvent&) override;
|
||||
virtual void keydown_event(GUI::KeyEvent&) override;
|
||||
|
||||
Chess::Board& board() { return m_board; };
|
||||
const Chess::Board& board() const { return m_board; };
|
||||
|
||||
Chess::Board& board_playback() { return m_board_playback; };
|
||||
const Chess::Board& board_playback() const { return m_board_playback; };
|
||||
|
||||
Chess::Color side() const { return m_side; };
|
||||
void set_side(Chess::Color side) { m_side = side; };
|
||||
|
||||
void set_piece_set(const StringView& set);
|
||||
const String& piece_set() const { return m_piece_set; };
|
||||
|
||||
Chess::Square mouse_to_square(GUI::MouseEvent& event) const;
|
||||
|
||||
bool drag_enabled() const { return m_drag_enabled; }
|
||||
void set_drag_enabled(bool e) { m_drag_enabled = e; }
|
||||
RefPtr<Gfx::Bitmap> get_piece_graphic(const Chess::Piece& piece) const;
|
||||
|
||||
String get_fen() const;
|
||||
bool import_pgn(const StringView& import_path);
|
||||
bool export_pgn(const StringView& export_path) const;
|
||||
|
||||
int resign();
|
||||
void flip_board();
|
||||
void reset();
|
||||
|
||||
struct BoardTheme {
|
||||
String name;
|
||||
Color dark_square_color;
|
||||
Color light_square_color;
|
||||
};
|
||||
|
||||
const BoardTheme& board_theme() const { return m_board_theme; }
|
||||
void set_board_theme(const BoardTheme& theme) { m_board_theme = theme; }
|
||||
void set_board_theme(const StringView& name);
|
||||
|
||||
enum class PlaybackDirection {
|
||||
First,
|
||||
Backward,
|
||||
Forward,
|
||||
Last
|
||||
};
|
||||
|
||||
void playback_move(PlaybackDirection);
|
||||
|
||||
void set_engine(RefPtr<Engine> engine) { m_engine = engine; }
|
||||
|
||||
void input_engine_move();
|
||||
bool want_engine_move();
|
||||
|
||||
void set_coordinates(bool coordinates) { m_coordinates = coordinates; }
|
||||
bool coordinates() const { return m_coordinates; }
|
||||
|
||||
struct BoardMarking {
|
||||
Chess::Square from { 50, 50 };
|
||||
Chess::Square to { 50, 50 };
|
||||
bool alternate_color { false };
|
||||
bool secondary_color { false };
|
||||
enum class Type {
|
||||
Square,
|
||||
Arrow,
|
||||
None
|
||||
};
|
||||
Type type() const
|
||||
{
|
||||
if (from.in_bounds() && to.in_bounds() && from != to)
|
||||
return Type::Arrow;
|
||||
else if ((from.in_bounds() && !to.in_bounds()) || (from.in_bounds() && to.in_bounds() && from == to))
|
||||
return Type::Square;
|
||||
|
||||
return Type::None;
|
||||
}
|
||||
bool operator==(const BoardMarking& other) const { return from == other.from && to == other.to; }
|
||||
};
|
||||
|
||||
private:
|
||||
Chess::Board m_board;
|
||||
Chess::Board m_board_playback;
|
||||
bool m_playback { false };
|
||||
size_t m_playback_move_number { 0 };
|
||||
BoardMarking m_current_marking;
|
||||
Vector<BoardMarking> m_board_markings;
|
||||
BoardTheme m_board_theme { "Beige", Color::from_rgb(0xb58863), Color::from_rgb(0xf0d9b5) };
|
||||
Color m_move_highlight_color { Color::from_rgba(0x66ccee00) };
|
||||
Color m_marking_primary_color { Color::from_rgba(0x66ff0000) };
|
||||
Color m_marking_alternate_color { Color::from_rgba(0x66ffaa00) };
|
||||
Color m_marking_secondary_color { Color::from_rgba(0x6655dd55) };
|
||||
Chess::Color m_side { Chess::Color::White };
|
||||
HashMap<Chess::Piece, RefPtr<Gfx::Bitmap>> m_pieces;
|
||||
String m_piece_set;
|
||||
Chess::Square m_moving_square { 50, 50 };
|
||||
Gfx::IntPoint m_drag_point;
|
||||
bool m_dragging_piece { false };
|
||||
bool m_drag_enabled { true };
|
||||
RefPtr<Engine> m_engine;
|
||||
bool m_coordinates { true };
|
||||
};
|
88
Userland/Games/Chess/Engine.cpp
Normal file
88
Userland/Games/Chess/Engine.cpp
Normal file
|
@ -0,0 +1,88 @@
|
|||
/*
|
||||
* Copyright (c) 2020, the SerenityOS developers.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include "Engine.h"
|
||||
#include <LibCore/File.h>
|
||||
#include <fcntl.h>
|
||||
#include <spawn.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
Engine::~Engine()
|
||||
{
|
||||
if (m_pid != -1)
|
||||
kill(m_pid, SIGINT);
|
||||
}
|
||||
|
||||
Engine::Engine(const StringView& command)
|
||||
{
|
||||
int wpipefds[2];
|
||||
int rpipefds[2];
|
||||
if (pipe2(wpipefds, O_CLOEXEC) < 0) {
|
||||
perror("pipe2");
|
||||
ASSERT_NOT_REACHED();
|
||||
}
|
||||
|
||||
if (pipe2(rpipefds, O_CLOEXEC) < 0) {
|
||||
perror("pipe2");
|
||||
ASSERT_NOT_REACHED();
|
||||
}
|
||||
|
||||
posix_spawn_file_actions_t file_actions;
|
||||
posix_spawn_file_actions_init(&file_actions);
|
||||
posix_spawn_file_actions_adddup2(&file_actions, wpipefds[0], STDIN_FILENO);
|
||||
posix_spawn_file_actions_adddup2(&file_actions, rpipefds[1], STDOUT_FILENO);
|
||||
|
||||
String cstr(command);
|
||||
const char* argv[] = { cstr.characters(), nullptr };
|
||||
if (posix_spawnp(&m_pid, cstr.characters(), &file_actions, nullptr, const_cast<char**>(argv), environ) < 0) {
|
||||
perror("posix_spawnp");
|
||||
ASSERT_NOT_REACHED();
|
||||
}
|
||||
|
||||
posix_spawn_file_actions_destroy(&file_actions);
|
||||
|
||||
close(wpipefds[0]);
|
||||
close(rpipefds[1]);
|
||||
|
||||
auto infile = Core::File::construct();
|
||||
infile->open(rpipefds[0], Core::IODevice::ReadOnly, Core::File::ShouldCloseFileDescriptor::Yes);
|
||||
set_in(infile);
|
||||
|
||||
auto outfile = Core::File::construct();
|
||||
outfile->open(wpipefds[1], Core::IODevice::WriteOnly, Core::File::ShouldCloseFileDescriptor::Yes);
|
||||
set_out(outfile);
|
||||
|
||||
send_command(Chess::UCI::UCICommand());
|
||||
}
|
||||
|
||||
void Engine::handle_bestmove(const Chess::UCI::BestMoveCommand& command)
|
||||
{
|
||||
if (m_bestmove_callback)
|
||||
m_bestmove_callback(command.move());
|
||||
|
||||
m_bestmove_callback = nullptr;
|
||||
}
|
58
Userland/Games/Chess/Engine.h
Normal file
58
Userland/Games/Chess/Engine.h
Normal file
|
@ -0,0 +1,58 @@
|
|||
/*
|
||||
* Copyright (c) 2020, the SerenityOS developers.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <AK/Function.h>
|
||||
#include <LibChess/UCIEndpoint.h>
|
||||
#include <sys/types.h>
|
||||
|
||||
class Engine : public Chess::UCI::Endpoint {
|
||||
C_OBJECT(Engine)
|
||||
public:
|
||||
virtual ~Engine() override;
|
||||
|
||||
Engine(const StringView& command);
|
||||
|
||||
Engine(const Engine&) = delete;
|
||||
Engine& operator=(const Engine&) = delete;
|
||||
|
||||
virtual void handle_bestmove(const Chess::UCI::BestMoveCommand&);
|
||||
|
||||
template<typename Callback>
|
||||
void get_best_move(const Chess::Board& board, int time_limit, Callback&& callback)
|
||||
{
|
||||
send_command(Chess::UCI::PositionCommand({}, board.moves()));
|
||||
Chess::UCI::GoCommand go_command;
|
||||
go_command.movetime = time_limit;
|
||||
send_command(go_command);
|
||||
m_bestmove_callback = move(callback);
|
||||
}
|
||||
|
||||
private:
|
||||
Function<void(Chess::Move)> m_bestmove_callback;
|
||||
pid_t m_pid { -1 };
|
||||
};
|
59
Userland/Games/Chess/PromotionDialog.cpp
Normal file
59
Userland/Games/Chess/PromotionDialog.cpp
Normal file
|
@ -0,0 +1,59 @@
|
|||
/*
|
||||
* Copyright (c) 2020, the SerenityOS developers.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include "PromotionDialog.h"
|
||||
#include <LibGUI/BoxLayout.h>
|
||||
#include <LibGUI/Button.h>
|
||||
#include <LibGUI/Frame.h>
|
||||
|
||||
PromotionDialog::PromotionDialog(ChessWidget& chess_widget)
|
||||
: Dialog(chess_widget.window())
|
||||
, m_selected_piece(Chess::Type::None)
|
||||
{
|
||||
set_title("Choose piece to promote to");
|
||||
set_icon(chess_widget.window()->icon());
|
||||
resize(70 * 4, 70);
|
||||
|
||||
auto& main_widget = set_main_widget<GUI::Frame>();
|
||||
main_widget.set_frame_shape(Gfx::FrameShape::Container);
|
||||
main_widget.set_fill_with_background_color(true);
|
||||
main_widget.set_layout<GUI::HorizontalBoxLayout>();
|
||||
|
||||
for (auto& type : Vector({ Chess::Type::Queen, Chess::Type::Knight, Chess::Type::Rook, Chess::Type::Bishop })) {
|
||||
auto& button = main_widget.add<GUI::Button>("");
|
||||
button.set_fixed_height(70);
|
||||
button.set_icon(chess_widget.get_piece_graphic({ chess_widget.board().turn(), type }));
|
||||
button.on_click = [this, type](auto) {
|
||||
m_selected_piece = type;
|
||||
done(ExecOK);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
void PromotionDialog::event(Core::Event& event)
|
||||
{
|
||||
Dialog::event(event);
|
||||
}
|
42
Userland/Games/Chess/PromotionDialog.h
Normal file
42
Userland/Games/Chess/PromotionDialog.h
Normal file
|
@ -0,0 +1,42 @@
|
|||
/*
|
||||
* Copyright (c) 2020, the SerenityOS developers.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "ChessWidget.h"
|
||||
#include <LibGUI/Dialog.h>
|
||||
|
||||
class PromotionDialog final : public GUI::Dialog {
|
||||
C_OBJECT(PromotionDialog)
|
||||
public:
|
||||
Chess::Type selected_piece() const { return m_selected_piece; }
|
||||
|
||||
private:
|
||||
explicit PromotionDialog(ChessWidget& chess_widget);
|
||||
virtual void event(Core::Event&) override;
|
||||
|
||||
Chess::Type m_selected_piece;
|
||||
};
|
231
Userland/Games/Chess/main.cpp
Normal file
231
Userland/Games/Chess/main.cpp
Normal file
|
@ -0,0 +1,231 @@
|
|||
/*
|
||||
* Copyright (c) 2020, the SerenityOS developers.
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* 1. Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* 2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#include "ChessWidget.h"
|
||||
#include <LibCore/ConfigFile.h>
|
||||
#include <LibCore/DirIterator.h>
|
||||
#include <LibGUI/ActionGroup.h>
|
||||
#include <LibGUI/Application.h>
|
||||
#include <LibGUI/Clipboard.h>
|
||||
#include <LibGUI/FilePicker.h>
|
||||
#include <LibGUI/Icon.h>
|
||||
#include <LibGUI/Menu.h>
|
||||
#include <LibGUI/MenuBar.h>
|
||||
#include <LibGUI/MessageBox.h>
|
||||
#include <LibGUI/Window.h>
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
auto app = GUI::Application::construct(argc, argv);
|
||||
auto app_icon = GUI::Icon::default_icon("app-chess");
|
||||
|
||||
auto window = GUI::Window::construct();
|
||||
auto& widget = window->set_main_widget<ChessWidget>();
|
||||
|
||||
RefPtr<Core::ConfigFile> config = Core::ConfigFile::get_for_app("Chess");
|
||||
|
||||
if (pledge("stdio rpath accept wpath cpath shared_buffer proc exec", nullptr) < 0) {
|
||||
perror("pledge");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (unveil("/res", "r") < 0) {
|
||||
perror("unveil");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (unveil(config->file_name().characters(), "crw") < 0) {
|
||||
perror("unveil");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (unveil("/bin/ChessEngine", "x") < 0) {
|
||||
perror("unveil");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (unveil("/etc/passwd", "r") < 0) {
|
||||
perror("unveil");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (unveil(Core::StandardPaths::home_directory().characters(), "wcbr") < 0) {
|
||||
perror("unveil");
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (unveil(nullptr, nullptr) < 0) {
|
||||
perror("unveil");
|
||||
return 1;
|
||||
}
|
||||
|
||||
auto size = config->read_num_entry("Display", "size", 512);
|
||||
window->set_title("Chess");
|
||||
window->resize(size, size);
|
||||
window->set_size_increment({ 8, 8 });
|
||||
window->set_resize_aspect_ratio(1, 1);
|
||||
|
||||
window->set_icon(app_icon.bitmap_for_size(16));
|
||||
|
||||
widget.set_piece_set(config->read_entry("Style", "PieceSet", "stelar7"));
|
||||
widget.set_board_theme(config->read_entry("Style", "BoardTheme", "Beige"));
|
||||
widget.set_coordinates(config->read_bool_entry("Style", "Coordinates", true));
|
||||
|
||||
auto menubar = GUI::MenuBar::construct();
|
||||
auto& app_menu = menubar->add_menu("Chess");
|
||||
|
||||
app_menu.add_action(GUI::Action::create("Resign", { Mod_None, Key_F3 }, [&](auto&) {
|
||||
widget.resign();
|
||||
}));
|
||||
app_menu.add_action(GUI::Action::create("Flip Board", { Mod_Ctrl, Key_F }, [&](auto&) {
|
||||
widget.flip_board();
|
||||
}));
|
||||
app_menu.add_separator();
|
||||
|
||||
app_menu.add_action(GUI::Action::create("Import PGN...", { Mod_Ctrl, Key_O }, [&](auto&) {
|
||||
Optional<String> import_path = GUI::FilePicker::get_open_filepath(window);
|
||||
|
||||
if (!import_path.has_value())
|
||||
return;
|
||||
|
||||
if (!widget.import_pgn(import_path.value())) {
|
||||
GUI::MessageBox::show(window, "Unable to import game.\n", "Error", GUI::MessageBox::Type::Error);
|
||||
return;
|
||||
}
|
||||
|
||||
dbgln("Imported PGN file from {}", import_path.value());
|
||||
}));
|
||||
app_menu.add_action(GUI::Action::create("Export PGN...", { Mod_Ctrl, Key_S }, [&](auto&) {
|
||||
Optional<String> export_path = GUI::FilePicker::get_save_filepath(window, "Untitled", "pgn");
|
||||
|
||||
if (!export_path.has_value())
|
||||
return;
|
||||
|
||||
if (!widget.export_pgn(export_path.value())) {
|
||||
GUI::MessageBox::show(window, "Unable to export game.\n", "Error", GUI::MessageBox::Type::Error);
|
||||
return;
|
||||
}
|
||||
|
||||
dbgln("Exported PGN file to {}", export_path.value());
|
||||
}));
|
||||
app_menu.add_action(GUI::Action::create("Copy FEN", { Mod_Ctrl, Key_C }, [&](auto&) {
|
||||
GUI::Clipboard::the().set_data(widget.get_fen().bytes());
|
||||
GUI::MessageBox::show(window, "Board state copied to clipboard as FEN.", "Copy FEN", GUI::MessageBox::Type::Information);
|
||||
}));
|
||||
app_menu.add_separator();
|
||||
|
||||
app_menu.add_action(GUI::Action::create("New game", { Mod_None, Key_F2 }, [&](auto&) {
|
||||
if (widget.board().game_result() == Chess::Board::Result::NotFinished) {
|
||||
if (widget.resign() < 0)
|
||||
return;
|
||||
}
|
||||
widget.reset();
|
||||
}));
|
||||
app_menu.add_separator();
|
||||
app_menu.add_action(GUI::CommonActions::make_quit_action([](auto&) {
|
||||
GUI::Application::the()->quit();
|
||||
}));
|
||||
|
||||
auto& style_menu = menubar->add_menu("Style");
|
||||
GUI::ActionGroup piece_set_action_group;
|
||||
piece_set_action_group.set_exclusive(true);
|
||||
auto& piece_set_menu = style_menu.add_submenu("Piece Set");
|
||||
piece_set_menu.set_icon(app_icon.bitmap_for_size(16));
|
||||
|
||||
Core::DirIterator di("/res/icons/chess/sets/", Core::DirIterator::SkipParentAndBaseDir);
|
||||
while (di.has_next()) {
|
||||
auto set = di.next_path();
|
||||
auto action = GUI::Action::create_checkable(set, [&](auto& action) {
|
||||
widget.set_piece_set(action.text());
|
||||
widget.update();
|
||||
config->write_entry("Style", "PieceSet", action.text());
|
||||
config->sync();
|
||||
});
|
||||
|
||||
piece_set_action_group.add_action(*action);
|
||||
if (widget.piece_set() == set)
|
||||
action->set_checked(true);
|
||||
piece_set_menu.add_action(*action);
|
||||
}
|
||||
|
||||
GUI::ActionGroup board_theme_action_group;
|
||||
board_theme_action_group.set_exclusive(true);
|
||||
auto& board_theme_menu = style_menu.add_submenu("Board Theme");
|
||||
board_theme_menu.set_icon(Gfx::Bitmap::load_from_file("/res/icons/chess/mini-board.png"));
|
||||
|
||||
for (auto& theme : Vector({ "Beige", "Green", "Blue" })) {
|
||||
auto action = GUI::Action::create_checkable(theme, [&](auto& action) {
|
||||
widget.set_board_theme(action.text());
|
||||
widget.update();
|
||||
config->write_entry("Style", "BoardTheme", action.text());
|
||||
config->sync();
|
||||
});
|
||||
board_theme_action_group.add_action(*action);
|
||||
if (widget.board_theme().name == theme)
|
||||
action->set_checked(true);
|
||||
board_theme_menu.add_action(*action);
|
||||
}
|
||||
|
||||
auto coordinates_action = GUI::Action::create_checkable("Coordinates", [&](auto& action) {
|
||||
widget.set_coordinates(action.is_checked());
|
||||
widget.update();
|
||||
config->write_bool_entry("Style", "Coordinates", action.is_checked());
|
||||
config->sync();
|
||||
});
|
||||
coordinates_action->set_checked(widget.coordinates());
|
||||
style_menu.add_action(coordinates_action);
|
||||
|
||||
auto& engine_menu = menubar->add_menu("Engine");
|
||||
|
||||
GUI::ActionGroup engines_action_group;
|
||||
engines_action_group.set_exclusive(true);
|
||||
auto& engine_submenu = engine_menu.add_submenu("Engine");
|
||||
for (auto& engine : Vector({ "Human", "ChessEngine" })) {
|
||||
auto action = GUI::Action::create_checkable(engine, [&](auto& action) {
|
||||
if (action.text() == "Human") {
|
||||
widget.set_engine(nullptr);
|
||||
} else {
|
||||
widget.set_engine(Engine::construct(action.text()));
|
||||
widget.input_engine_move();
|
||||
}
|
||||
});
|
||||
engines_action_group.add_action(*action);
|
||||
if (engine == String("Human"))
|
||||
action->set_checked(true);
|
||||
|
||||
engine_submenu.add_action(*action);
|
||||
}
|
||||
|
||||
auto& help_menu = menubar->add_menu("Help");
|
||||
help_menu.add_action(GUI::CommonActions::make_about_action("Chess", app_icon, window));
|
||||
|
||||
app->set_menubar(move(menubar));
|
||||
|
||||
window->show();
|
||||
widget.reset();
|
||||
|
||||
return app->exec();
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue