made the thinking time of AIs common to all of them

This commit is contained in:
Karma Riuk 2025-02-06 20:38:27 +01:00
parent 74e4d596a7
commit e0a52f57b7
5 changed files with 48 additions and 7 deletions

View File

@ -5,13 +5,15 @@
#include "view/noop.hpp"
#include "view/view.hpp"
#include <chrono>
int main(int argc, char* argv[]) {
std::string pos =
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
Board b = Board::setup_fen_position(pos);
ai::v0_random ai;
ai::v0_random ai(std::chrono::milliseconds(500));
GUI gui;
HumanVsAIController manual(b, gui, ai);

23
cpp/src/model/ais/ai.cpp Normal file
View File

@ -0,0 +1,23 @@
#include "ai.hpp"
#include <thread>
Move ai::AI::search(const Board& b, bool am_white) {
Move result;
// Start computation in a separate thread
std::thread computation_thread([&]() { result = _search(b, am_white); });
// Start a timer thread to stop computation after given time
std::thread timer_thread([&]() {
std::this_thread::sleep_for(thinking_time);
stop_computation = true;
});
// Wait for computation thread to finish
computation_thread.join();
// Ensure timer thread is also stopped
timer_thread.join();
return result;
}

View File

@ -3,16 +3,28 @@
#include "../board/board.hpp"
#include <atomic>
#include <chrono>
namespace ai {
struct AI {
class AI {
protected:
std::chrono::milliseconds thinking_time;
virtual Move _search(const Board&, bool = false) = 0;
public:
AI(std::chrono::milliseconds tt): thinking_time(tt) {}
std::atomic<bool> stop_computation = false;
virtual Move search(const Board&, bool = false) = 0;
Move search(const Board& b, bool am_white = false);
virtual int eval(const Board&) = 0;
};
struct v0_random : public AI {
Move search(const Board&, bool) override;
v0_random(std::chrono::milliseconds tt): AI(tt) {}
Move _search(const Board&, bool) override;
int eval(const Board&) override {
return 0;
@ -23,7 +35,9 @@ namespace ai {
int _search(const Board&, int);
public:
Move search(const Board&, bool) override;
v1_simple(std::chrono::milliseconds tt): AI(tt) {}
Move _search(const Board&, bool) override;
int eval(const Board&) override;
};
} // namespace ai

View File

@ -1,6 +1,8 @@
#include "ai.hpp"
Move ai::v0_random::search(const Board& b, bool) {
#include <thread>
Move ai::v0_random::_search(const Board& b, bool) {
std::vector<Move> moves = b.all_legal_moves();
return moves[rand() % moves.size()];

View File

@ -7,7 +7,7 @@
static int INFINITY = std::numeric_limits<int>::max();
Move ai::v1_simple::search(const Board& b, bool am_black) {
Move ai::v1_simple::_search(const Board& b, bool am_black) {
ThreadPool pool(std::thread::hardware_concurrency());
std::vector<Move> moves = b.all_legal_moves();