Chess: Add support for UCI engines

This commit is contained in:
Peter Elliott 2020-08-19 17:53:50 -06:00 committed by Andreas Kling
parent 7331b2b2f6
commit fb62eed058
8 changed files with 202 additions and 2 deletions

View file

@ -2,6 +2,7 @@ set(SOURCES
main.cpp
ChessWidget.cpp
PromotionDialog.cpp
Engine.cpp
)
serenity_bin(Chess)

View file

@ -175,6 +175,8 @@ void ChessWidget::mouseup_event(GUI::MouseEvent& event)
update();
GUI::MessageBox::show(window(), msg, "Game Over", GUI::MessageBox::Type::Information);
}
} else {
maybe_input_engine_move();
}
}
@ -240,7 +242,9 @@ RefPtr<Gfx::Bitmap> ChessWidget::get_piece_graphic(const Chess::Piece& piece) co
void ChessWidget::reset()
{
m_board = Chess::Board();
m_side = (arc4random() % 2) ? Chess::Colour::White : Chess::Colour::Black;
m_drag_enabled = true;
maybe_input_engine_move();
update();
}
@ -258,3 +262,19 @@ void ChessWidget::set_board_theme(const StringView& name)
set_board_theme("Beige");
}
}
void ChessWidget::maybe_input_engine_move()
{
if (!m_engine || board().turn() == side())
return;
bool drag_was_enabled = drag_enabled();
if (drag_was_enabled)
set_drag_enabled(false);
m_engine->get_best_move(board(), 500, [this, drag_was_enabled](Chess::Move move) {
set_drag_enabled(drag_was_enabled);
ASSERT(board().apply_move(move));
update();
});
}

View file

@ -26,6 +26,7 @@
#pragma once
#include "Engine.h"
#include <AK/HashMap.h>
#include <AK/NonnullRefPtr.h>
#include <AK/Optional.h>
@ -73,6 +74,10 @@ public:
void set_board_theme(const BoardTheme& theme) { m_board_theme = theme; }
void set_board_theme(const StringView& name);
void set_engine(RefPtr<Engine> engine) { m_engine = engine; }
void maybe_input_engine_move();
private:
Chess::Board m_board;
BoardTheme m_board_theme { "Beige", Color::from_rgb(0xb58863), Color::from_rgb(0xf0d9b5) };
@ -84,4 +89,5 @@ private:
Gfx::IntPoint m_drag_point;
bool m_dragging_piece { false };
bool m_drag_enabled { true };
RefPtr<Engine> m_engine;
};

88
Games/Chess/Engine.cpp Normal file
View 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::ShouldCloseFileDescription::Yes);
set_in(infile);
auto outfile = Core::File::construct();
outfile->open(wpipefds[1], Core::IODevice::WriteOnly, Core::File::ShouldCloseFileDescription::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
Games/Chess/Engine.h Normal file
View 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 };
};

View file

@ -40,7 +40,6 @@ int main(int argc, char** argv)
auto window = GUI::Window::construct();
auto& widget = window->set_main_widget<ChessWidget>();
widget.set_side(Chess::Colour::White);
RefPtr<Core::ConfigFile> config = Core::ConfigFile::get_for_app("Chess");
@ -106,6 +105,27 @@ int main(int argc, char** argv)
board_theme_menu.add_action(*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.maybe_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::Action::create("About", [&](auto&) {
GUI::AboutDialog::show("Chess", Gfx::Bitmap::load_from_file("/res/icons/32x32/app-chess.png"), window);
@ -114,6 +134,7 @@ int main(int argc, char** argv)
app->set_menubar(move(menubar));
window->show();
widget.reset();
return app->exec();
}

View file

@ -385,10 +385,13 @@ bool Board::apply_illegal_move(const Move& move, Colour colour)
{
Board clone = *this;
clone.m_previous_states = {};
clone.m_moves = {};
auto state_count = 0;
if (m_previous_states.contains(clone))
state_count = m_previous_states.get(clone).value();
m_previous_states.set(clone, state_count + 1);
m_moves.append(move);
m_turn = opposing_colour(colour);

View file

@ -31,6 +31,7 @@
#include <AK/Optional.h>
#include <AK/StringView.h>
#include <AK/Traits.h>
#include <AK/Vector.h>
namespace Chess {
@ -136,7 +137,8 @@ public:
void generate_moves(Callback callback, Colour colour = Colour::None) const;
Result game_result() const;
Colour turn() const { return m_turn; };
Colour turn() const { return m_turn; }
const Vector<Move>& moves() const { return m_moves; }
bool operator==(const Board& other) const;
@ -155,6 +157,7 @@ private:
bool m_black_can_castle_queenside { true };
HashMap<Board, int> m_previous_states;
Vector<Move> m_moves;
friend struct AK::Traits<Board>;
};