Compare commits
55 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
ef25455ac0 | ||
|
4aa3d4ba33 | ||
|
cb1a1274a0 | ||
|
1ff9b33bda | ||
|
f7733c1317 | ||
|
0aa8b7a16f | ||
|
ebf5934909 | ||
|
ecba8e3c6e | ||
|
1834b3b8ce | ||
|
ec4cc85ca3 | ||
|
97f9def306 | ||
|
f68dedeb20 | ||
|
4eae988999 | ||
|
62a35ecafd | ||
|
5cbe57dc55 | ||
|
0145664567 | ||
|
959ecdeb7d | ||
|
adf21ee021 | ||
|
989225c2d7 | ||
|
aef6fc39e3 | ||
|
2260cd918a | ||
|
3bc5b75f1e | ||
|
377e5dfdcc | ||
|
10de9828be | ||
|
9942832b18 | ||
|
5b45fc32c0 | ||
|
d28008d913 | ||
|
86beb9cc85 | ||
|
8edde1a8b1 | ||
|
182d183247 | ||
|
1b14ed693d | ||
|
a80fc9482d | ||
|
88b2d01cf8 | ||
|
979d44fad0 | ||
|
db87c2ec8b | ||
|
f3e28d2646 | ||
|
7e888bba61 | ||
|
1d83c066f6 | ||
|
2764787e63 | ||
|
c71cabb3cd | ||
|
0525bd565e | ||
|
695cef33df | ||
|
75b6c35cc5 | ||
|
74fa99fe7b | ||
|
0274f44647 | ||
|
a5abe39aa4 | ||
|
e056ef0805 | ||
|
dc6631f79c | ||
|
d6aa977a15 | ||
|
6e567f2f11 | ||
|
fced9757c2 | ||
|
04134f013c | ||
|
47cf8b3539 | ||
|
a47130e5d0 | ||
|
e0a52f57b7 |
198
.gitignore
vendored
@ -1,174 +1,34 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
# Prerequisites
|
||||
*.d
|
||||
|
||||
# C extensions
|
||||
# Compiled Object files
|
||||
*.slo
|
||||
*.lo
|
||||
*.o
|
||||
*.obj
|
||||
|
||||
# Precompiled Headers
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Compiled Dynamic libraries
|
||||
*.so
|
||||
*.dylib
|
||||
*.dll
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
# Fortran module files
|
||||
*.mod
|
||||
*.smod
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
# Compiled Static libraries
|
||||
*.lai
|
||||
*.la
|
||||
*.a
|
||||
*.lib
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
#uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
||||
.pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
# Executables
|
||||
*.exe
|
||||
*.out
|
||||
*.appobj/
|
||||
test_bin/
|
||||
main
|
||||
|
@ -1,4 +1,5 @@
|
||||
CXXFLAGS += -O3 -Wall
|
||||
# CXXFLAGS += -pg
|
||||
|
||||
# Add .d to Make's recognized suffixes.
|
||||
SUFFIXES += .d
|
||||
@ -27,8 +28,8 @@ obj/%.o:
|
||||
@mkdir -p $(dir $@)
|
||||
$(CXX) $(CXXFLAGS) -o $@ -c $<
|
||||
|
||||
main: $(OBJFILES)
|
||||
$(CXX) $(LDFLAGS) $(OBJFILES) $(LOADLIBES) $(LDLIBS) -o main -lsfml-graphics -lsfml-window -lsfml-system
|
||||
stickfosh: $(OBJFILES)
|
||||
$(CXX) $(CXXFLAGS) $(OBJFILES) $(LOADLIBES) $(LDLIBS) -o stickfosh -lsfml-graphics -lsfml-window -lsfml-system
|
||||
|
||||
clean:
|
||||
rm -rf obj/* $(DEPFILES) test_bin/
|
||||
@ -46,7 +47,7 @@ LIBS := $(filter-out obj/main.o,$(OBJFILES))
|
||||
test_bin/%: tests/%.cpp $(LIBS)
|
||||
@echo $(LIBS)
|
||||
@mkdir -p $(dir $@)
|
||||
$(CXX) $(CXXFLAGS) -o $@ $< $(LIBS)
|
||||
$(CXX) $(CXXFLAGS) -o $@ $< $(LIBS) -lsfml-graphics -lsfml-window -lsfml-system
|
||||
|
||||
# The 'test' target builds all tests and then runs each one.
|
||||
.PHONY: test
|
85
README.md
@ -1,3 +1,86 @@
|
||||
# Stickfosh
|
||||
|
||||
> Stockfish, but worse :)
|
||||
> [Stockfish](https://stockfishchess.org), but worse :)
|
||||
|
||||
## Overview
|
||||
|
||||
This project is a **Chess AI** built using the **Model-View-Controller (MVC)
|
||||
pattern**. It provides a modular framework for playing chess, allowing both
|
||||
**human vs AI** and **AI vs AI** matches. The AI has undergone several
|
||||
iterations, improving its decision-making capabilities through enhancements like
|
||||
**alpha-beta pruning**, **move ordering**, **iterative deepening**, and
|
||||
**transposition tables**.
|
||||
|
||||
## Features
|
||||
|
||||
- **MVC Architecture**: The project follows the MVC pattern for clean separation of concerns:
|
||||
- **Model**: Handles chess rules, board state, and AI logic.
|
||||
- **View**: GUI and NoOp (that shows nothing, but is useful for debugging the AIs) rendering options.
|
||||
- **Controller**: Manages interactions between players and the game.
|
||||
- **Multiple AI Versions**: Several AI versions with increasing complexity have been implemented.
|
||||
- **AI vs AI Matches**: A dedicated mode to watch different AI versions compete.
|
||||
- **Human vs AI Mode**: Play against the AI using a graphical interface.
|
||||
- **FEN Support**: Load chess positions using FEN notation.
|
||||
- **Performance Testing (Perft)**: Built-in performance testing for move generation.
|
||||
|
||||
## AI Iterations
|
||||
|
||||
This project has undergone multiple AI improvements, including:
|
||||
|
||||
1. **v0 Random AI**: Selects moves randomly.
|
||||
1. **v1 Pure Minimax**: Implements basic minimax search.
|
||||
1. **v2 Alpha-Beta Pruning**: Optimizes minimax with pruning.
|
||||
1. **v3 Move Ordering**: Prioritizes moves to improve search efficiency.
|
||||
1. **v4 Search Captures**: Enhances move ordering by focusing on captures.
|
||||
1. **v5 Better Endgame**: Introduces heuristics for endgame play.
|
||||
1. **v6 Iterative Deepening**: Dynamically adjusts search depth for better performance.
|
||||
1. **v7 Transposition Tables**: Caches board states to reduce redundant computations.
|
||||
|
||||
## Installation & Usage
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- C++ Compiler (C++17 or later)
|
||||
- `make`
|
||||
- SFML (for GUI rendering)
|
||||
|
||||
### Build Instructions
|
||||
|
||||
1. Clone the repository:
|
||||
```sh
|
||||
git clone https://github.com/karma-riuk/stickfosh.git
|
||||
cd stickfosh
|
||||
```
|
||||
1. Create a build directory and compile:
|
||||
```sh
|
||||
make stickfosh
|
||||
```
|
||||
1. Run the program:
|
||||
```sh
|
||||
./stickfosh
|
||||
```
|
||||
|
||||
## Running the Application
|
||||
|
||||
Stickfosh provides multiple execution modes, selectable via command-line arguments:
|
||||
|
||||
| Mode | Description | Example Command |
|
||||
|------|------------|----------------|
|
||||
| **Human vs AI** | Play against the AI | `./stickfosh --mode human_vs_ai` |
|
||||
| **AI vs AI** | Watch two AI versions compete | `./stickfosh --mode ai_vs_ai --ai1 v3_AB_ordering --ai2 v6_iterative_deepening` |
|
||||
| **Human vs Human** | Manually input moves for both sides | `./stickfosh --mode human_vs_human` |
|
||||
| **Perft Testing** | Performance test move generation | `./stickfosh --mode perft` |
|
||||
| **Custom FEN** | Start from a custom position | `./stickfosh --mode ai_vs_ai --fen "rnbqkb1r/pppppppp/8/8/8/8/PPPPPPPP/RNBQKB1R w KQkq - 0 1"` |
|
||||
|
||||
## Video Demo
|
||||
|
||||
<!-- [](https://www.youtube.com/watch?v=XXXXXXXXXX) -->
|
||||
|
||||
<!-- *Click the image above to watch a video of two AI versions competing!* -->
|
||||
|
||||
## Future Improvements
|
||||
|
||||
- Implement **opening book** for better early-game decisions.
|
||||
- Enhance **evaluation function** with more advanced heuristics.
|
||||
- Introduce **neural network-based AI** for machine-learning-driven play.
|
||||
- Introduce **Monte-Carlo Tree Search** for stochastic driven play.
|
||||
|
34
cpp/.gitignore
vendored
@ -1,34 +0,0 @@
|
||||
# Prerequisites
|
||||
*.d
|
||||
|
||||
# Compiled Object files
|
||||
*.slo
|
||||
*.lo
|
||||
*.o
|
||||
*.obj
|
||||
|
||||
# Precompiled Headers
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Compiled Dynamic libraries
|
||||
*.so
|
||||
*.dylib
|
||||
*.dll
|
||||
|
||||
# Fortran module files
|
||||
*.mod
|
||||
*.smod
|
||||
|
||||
# Compiled Static libraries
|
||||
*.lai
|
||||
*.la
|
||||
*.a
|
||||
*.lib
|
||||
|
||||
# Executables
|
||||
*.exe
|
||||
*.out
|
||||
*.appobj/
|
||||
test_bin/
|
||||
main
|
@ -1,32 +0,0 @@
|
||||
#include "controller/controller.hpp"
|
||||
#include "controller/human_vs_ai.hpp"
|
||||
#include "controller/manual.hpp"
|
||||
#include "view/gui.hpp"
|
||||
#include "view/noop.hpp"
|
||||
#include "view/view.hpp"
|
||||
|
||||
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;
|
||||
|
||||
GUI gui;
|
||||
HumanVsAIController manual(b, gui, ai);
|
||||
|
||||
|
||||
View& view = gui;
|
||||
Controller& controller = manual;
|
||||
|
||||
view.show();
|
||||
|
||||
// perft();
|
||||
// ai::v1_simple ai;
|
||||
//
|
||||
// Board b = Board::setup_fen_position(pos);
|
||||
// Move move = ai.search(b, true);
|
||||
// std::cout << move << std::endl;
|
||||
return 0;
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "../board/board.hpp"
|
||||
|
||||
#include <atomic>
|
||||
|
||||
namespace ai {
|
||||
struct AI {
|
||||
std::atomic<bool> stop_computation = false;
|
||||
virtual Move search(const Board&, bool = false) = 0;
|
||||
virtual int eval(const Board&) = 0;
|
||||
};
|
||||
|
||||
struct v0_random : public AI {
|
||||
Move search(const Board&, bool) override;
|
||||
|
||||
int eval(const Board&) override {
|
||||
return 0;
|
||||
};
|
||||
};
|
||||
|
||||
class v1_simple : public AI {
|
||||
int _search(const Board&, int);
|
||||
|
||||
public:
|
||||
Move search(const Board&, bool) override;
|
||||
int eval(const Board&) override;
|
||||
};
|
||||
} // namespace ai
|
@ -1,7 +0,0 @@
|
||||
#include "ai.hpp"
|
||||
|
||||
Move ai::v0_random::search(const Board& b, bool) {
|
||||
std::vector<Move> moves = b.all_legal_moves();
|
||||
|
||||
return moves[rand() % moves.size()];
|
||||
}
|
@ -1,95 +0,0 @@
|
||||
#include "../pieces/piece.hpp"
|
||||
#include "../utils/threadpool.hpp"
|
||||
#include "ai.hpp"
|
||||
|
||||
#include <future>
|
||||
#include <map>
|
||||
|
||||
static int INFINITY = std::numeric_limits<int>::max();
|
||||
|
||||
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();
|
||||
std::map<Move, std::future<int>> futures;
|
||||
for (int depth = 1; !stop_computation; depth++) {
|
||||
for (const Move& move : moves) {
|
||||
Board tmp_board = b.make_move(move);
|
||||
futures.insert({move, pool.enqueue([&]() {
|
||||
return _search(tmp_board, depth - 1);
|
||||
})});
|
||||
}
|
||||
}
|
||||
|
||||
Move best_move;
|
||||
int best_eval = -INFINITY;
|
||||
for (auto& [move, future] : futures) {
|
||||
int eval = future.get();
|
||||
if (eval > best_eval) {
|
||||
best_eval = eval;
|
||||
best_move = move;
|
||||
}
|
||||
}
|
||||
|
||||
return best_move;
|
||||
}
|
||||
|
||||
int ai::v1_simple::_search(const Board& b, int depth) {
|
||||
if (b.is_checkmate_for(b.white_to_play ? White : Black))
|
||||
return -INFINITY;
|
||||
|
||||
if (depth == 0 || stop_computation)
|
||||
return eval(b);
|
||||
|
||||
std::vector<Move> moves = b.all_legal_moves();
|
||||
int best_evaluation = 0;
|
||||
Move best_move;
|
||||
for (const Move& move : moves) {
|
||||
Board tmp_board = b.make_move(move);
|
||||
int tmp_eval = -_search(tmp_board, depth - 1);
|
||||
best_evaluation = std::max(best_evaluation, tmp_eval);
|
||||
}
|
||||
return best_evaluation;
|
||||
}
|
||||
|
||||
static int PawnValue = 100;
|
||||
static int KnightValue = 300;
|
||||
static int BishopValue = 320;
|
||||
static int RookValue = 500;
|
||||
static int QueenValue = 900;
|
||||
|
||||
int count_material(const Board& b, int8_t colour) {
|
||||
int ret = 0;
|
||||
for (int i = 0; i < 64; i++) {
|
||||
if (b.colour_at(i) == colour)
|
||||
switch (b.piece_at(i)) {
|
||||
case Piece::Pawn:
|
||||
ret += PawnValue;
|
||||
break;
|
||||
case Piece::Knigt:
|
||||
ret += KnightValue;
|
||||
break;
|
||||
case Piece::Bishop:
|
||||
ret += BishopValue;
|
||||
break;
|
||||
case Piece::Rook:
|
||||
ret += RookValue;
|
||||
break;
|
||||
case Piece::Queen:
|
||||
ret += QueenValue;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
int ai::v1_simple::eval(const Board& b) {
|
||||
int white_eval = count_material(b, Colour::White);
|
||||
int black_eval = count_material(b, Colour::Black);
|
||||
|
||||
int evaluation = white_eval - black_eval;
|
||||
|
||||
int perspective = b.white_to_play ? 1 : -1;
|
||||
|
||||
return perspective * evaluation;
|
||||
}
|
@ -1,8 +0,0 @@
|
||||
#include "utils.hpp"
|
||||
|
||||
std::vector<int8_t> to_target_square(std::vector<Move> moves) {
|
||||
std::vector<int8_t> ret;
|
||||
for (Move move : moves)
|
||||
ret.push_back(move.target_square);
|
||||
return ret;
|
||||
}
|
@ -1,8 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "move.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
std::vector<int8_t> to_target_square(std::vector<Move>);
|
Before Width: | Height: | Size: 1.4 KiB |
Before Width: | Height: | Size: 3.5 KiB |
Before Width: | Height: | Size: 1.8 KiB |
Before Width: | Height: | Size: 734 B |
Before Width: | Height: | Size: 2.7 KiB |
Before Width: | Height: | Size: 1014 B |
Before Width: | Height: | Size: 4.2 KiB |
Before Width: | Height: | Size: 2.5 KiB |
Before Width: | Height: | Size: 3.0 KiB |
Before Width: | Height: | Size: 2.2 KiB |
Before Width: | Height: | Size: 1.4 KiB |
Before Width: | Height: | Size: 3.8 KiB |
Before Width: | Height: | Size: 1.3 KiB |
@ -1,169 +0,0 @@
|
||||
from collections import defaultdict
|
||||
import time
|
||||
|
||||
from tqdm import tqdm
|
||||
from logic.board import INITIAL_BOARD, Board
|
||||
from logic.move import Move
|
||||
from logic.pieces.piece import Colour
|
||||
|
||||
pos2expected = {
|
||||
# -- Position 1
|
||||
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1": {
|
||||
1: 20,
|
||||
2: 400,
|
||||
3: 8_902,
|
||||
4: 197_281,
|
||||
},
|
||||
|
||||
# -- Position 2
|
||||
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1": {
|
||||
1: 48,
|
||||
2: 2_039,
|
||||
3: 97_862,
|
||||
4: 4_085_603,
|
||||
},
|
||||
|
||||
# -- Position 3
|
||||
"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1": {
|
||||
1: 14,
|
||||
2: 191,
|
||||
3: 2_812,
|
||||
4: 43_238,
|
||||
5: 674_624,
|
||||
},
|
||||
|
||||
# -- Position 4
|
||||
"r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1": {
|
||||
1: 6,
|
||||
2: 264,
|
||||
3: 9467,
|
||||
4: 422_333,
|
||||
},
|
||||
|
||||
# -- Position 5
|
||||
"rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8": {
|
||||
1: 44,
|
||||
2: 1486,
|
||||
3: 62379,
|
||||
4: 2103487,
|
||||
},
|
||||
|
||||
# -- Position 6
|
||||
"r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - - 0 10": {
|
||||
1: 46,
|
||||
2: 2079,
|
||||
3: 89890,
|
||||
4: 3894594,
|
||||
},
|
||||
}
|
||||
|
||||
tick = "\033[92m✔️\033[0m" # Green Tick
|
||||
cross = "\033[91m❌\033[0m" # Red Cross
|
||||
|
||||
res = defaultdict(lambda : 0)
|
||||
|
||||
def peft(pos: str):
|
||||
global res
|
||||
expected = pos2expected[pos]
|
||||
board = Board.setup_FEN_position(pos)
|
||||
for depth in expected:
|
||||
with tqdm(total=expected[depth], desc=f"Depth: {depth}") as bar:
|
||||
start = time.process_time()
|
||||
moves = move_generation_test(bar, board, depth, depth)
|
||||
bar.close()
|
||||
elapsed = time.process_time() - start
|
||||
elapsed *= 1_000
|
||||
|
||||
print("Depth:", depth, end=" ")
|
||||
print("Result:", moves, end=" ")
|
||||
if moves == expected[depth]:
|
||||
print(f"{tick}", end=" ")
|
||||
else:
|
||||
print(f"{cross} (expected {expected[depth]})", end=" ")
|
||||
print("positions Time:", int(elapsed), "milliseconds")
|
||||
|
||||
if moves != expected[depth]:
|
||||
print()
|
||||
for key, value in res.items():
|
||||
print(f"{key}: {value}")
|
||||
|
||||
|
||||
|
||||
def move_generation_test(bar, board: Board, depth: int, max_depth, first = None):
|
||||
global res
|
||||
if first is None:
|
||||
res = defaultdict(lambda : 0)
|
||||
|
||||
if board.is_terminal():
|
||||
# bar.update(1)
|
||||
# res[first] += 1
|
||||
return 0
|
||||
|
||||
if depth == 0:
|
||||
res[first] += 1
|
||||
bar.update(1)
|
||||
return 1
|
||||
|
||||
moves = board.legal_moves()
|
||||
if depth == 1:
|
||||
res[first] += len(moves)
|
||||
bar.update(len(moves))
|
||||
return len(moves)
|
||||
|
||||
num_pos = 0
|
||||
for move in moves:
|
||||
tmp_board = board.make_move(move)
|
||||
if first is None:
|
||||
first = move.piece.pos.to_algebraic() + move.pos.to_algebraic()
|
||||
|
||||
if first == "f7h8":
|
||||
print(tmp_board.legal_moves())
|
||||
num_pos += move_generation_test(bar, tmp_board, depth - 1, max_depth, first = first)
|
||||
|
||||
if depth == max_depth:
|
||||
first = None
|
||||
|
||||
return num_pos
|
||||
|
||||
|
||||
|
||||
def play_game(board: Board, strategies: dict, verbose: bool = False) -> Board:
|
||||
"""Play a turn-taking game. `strategies` is a {player_name: function} dict,
|
||||
where function(state) is used to get the player's move."""
|
||||
state = board
|
||||
move_counter = 1
|
||||
while not (board.is_checkmate_for(board._turn) or board.is_stalemate_for(board._turn)):
|
||||
player = board._turn
|
||||
move = strategies[player](state)
|
||||
state = board.make_move(move)
|
||||
if verbose:
|
||||
if player == Colour.WHITE:
|
||||
print(str(move_counter) + ".", move, end=" ")
|
||||
else:
|
||||
print(move)
|
||||
|
||||
return state
|
||||
|
||||
def minmax_search(state: Board) -> tuple[float, Move]:
|
||||
"""Search game tree to determine best move; return (value, move) pair."""
|
||||
return _max_value(state) if state._turn == Colour.WHITE else _min_value(state)
|
||||
|
||||
def _max_value(state: Board) -> tuple[float, Move]:
|
||||
if state.is_terminal():
|
||||
return state.utility(), None
|
||||
v, move = -float("inf"), None
|
||||
for a in state.legal_moves():
|
||||
v2, _ = _min_value(state.make_move(a))
|
||||
if v2 > v:
|
||||
v, move = v2, a
|
||||
return v, move
|
||||
|
||||
def _min_value(state: Board) -> tuple[float, Move]:
|
||||
if state.is_terminal():
|
||||
return state.utility(), None
|
||||
v, move = float("inf"), None
|
||||
for a in state.legal_moves():
|
||||
v2, _ = _min_value(state.make_move(a))
|
||||
if v2 < v:
|
||||
v, move = v2, a
|
||||
return v, move
|
@ -1,63 +0,0 @@
|
||||
from logic.board import Board
|
||||
from logic.move import Move
|
||||
from logic.pieces.piece import Piece
|
||||
from logic.position import Position
|
||||
from view.view import View
|
||||
|
||||
|
||||
class Controller:
|
||||
def __init__(self, board: Board, view: View) -> None:
|
||||
self._board = board
|
||||
self._view = view
|
||||
|
||||
self._view.set_controller(self)
|
||||
self._reset_selection()
|
||||
|
||||
self._selected_piece: Piece = None
|
||||
self._legal_moves: list[Move] = []
|
||||
|
||||
def _reset_selection(self):
|
||||
self._selected_piece = None
|
||||
self._legal_moves = []
|
||||
self._view.update_board(self._board, self._selected_piece, self._legal_moves)
|
||||
|
||||
|
||||
def _show_legal_moves(self, pos: Position):
|
||||
piece = self._board.piece_at(pos.x, pos.y)
|
||||
|
||||
if piece:
|
||||
if piece.colour != self._board._turn:
|
||||
return
|
||||
self._selected_piece = piece
|
||||
self._legal_moves = piece.legal_moves(self._board)
|
||||
self._view.update_board(self._board, self._selected_piece, self._legal_moves)
|
||||
else:
|
||||
self._reset_selection()
|
||||
|
||||
def _make_move(self, move: Move) -> None:
|
||||
self._board = self._board.make_move(move)
|
||||
self._reset_selection()
|
||||
|
||||
def on_tile_selected(self, x: int, y: int) -> None:
|
||||
pos = Position(x, y)
|
||||
|
||||
piece = self._board.piece_at(x, y)
|
||||
|
||||
if self._selected_piece is None \
|
||||
or (piece is not None and piece != self._selected_piece and piece.colour == self._selected_piece.colour):
|
||||
self._show_legal_moves(pos)
|
||||
else:
|
||||
legal_moves_positions = [move for move in self._legal_moves if move.pos == pos]
|
||||
assert len(legal_moves_positions) <= 1, f"Apparently we can make multiple moves towards {pos.to_algebraic()} with {type(self._selected_piece)}, which doesn't make sense..."
|
||||
|
||||
if len(legal_moves_positions) == 0: # click on a square outside of the possible moves
|
||||
self._reset_selection()
|
||||
else:
|
||||
move = legal_moves_positions[0]
|
||||
self._make_move(move)
|
||||
|
||||
if self._board.is_checkmate_for(self._board._turn):
|
||||
self._view.notify_checkmate(self._board._turn)
|
||||
|
||||
if self._board.is_stalemate_for(self._board._turn):
|
||||
self._view.notify_stalemate(self._board._turn)
|
@ -1,360 +0,0 @@
|
||||
from logic.move import CastleSide, Move
|
||||
from logic.pieces.bishop import Bishop
|
||||
from logic.pieces.king import King
|
||||
from logic.pieces.knight import Knight
|
||||
from logic.pieces.queen import Queen
|
||||
from logic.pieces.rook import Rook
|
||||
from logic.pieces.pawn import Pawn
|
||||
from logic.pieces.piece import Colour, Piece
|
||||
from logic.position import Position
|
||||
|
||||
from typing import Type
|
||||
|
||||
class Board:
|
||||
def __init__(self) -> None:
|
||||
self._white: dict[Position, Piece] = {}
|
||||
self._black: dict[Position, Piece] = {}
|
||||
self._turn = None
|
||||
self._white_castling_rights = set()
|
||||
self._black_castling_rights = set()
|
||||
self._en_passant_target = None
|
||||
self._n_moves = 0
|
||||
self._n_half_moves = 0
|
||||
|
||||
@staticmethod
|
||||
def _piece_class_from_char(c: str) -> Type[Piece]:
|
||||
assert len(c) == 1, f"The piece {c} isn't denoted by 1 character"
|
||||
c = c.lower()
|
||||
if c == "p":
|
||||
return Pawn
|
||||
if c == "r":
|
||||
return Rook
|
||||
if c == "n":
|
||||
return Knight
|
||||
if c == "b":
|
||||
return Bishop
|
||||
if c == "q":
|
||||
return Queen
|
||||
if c == "k":
|
||||
return King
|
||||
raise ValueError(f"Unknown piece '{c}'")
|
||||
|
||||
@staticmethod
|
||||
def setup_FEN_position(position: str) -> "Board":
|
||||
ret = Board()
|
||||
index = 0
|
||||
|
||||
# -- Pieces
|
||||
pieces = "prnbqk" # possible pieces
|
||||
numbers = "12345678" # possible number of empty squares
|
||||
|
||||
x = 0
|
||||
y = 7 # FEN starts from the top left, so 8th rank
|
||||
for c in position:
|
||||
index += 1
|
||||
if c == " ":
|
||||
break
|
||||
if c in pieces or c in pieces.upper():
|
||||
pos = Position(x, y)
|
||||
piece = Board._piece_class_from_char(c)
|
||||
if c.isupper():
|
||||
ret._white[pos] = piece(pos, Colour.WHITE)
|
||||
else:
|
||||
ret._black[pos] = piece(pos, Colour.BLACK)
|
||||
|
||||
x += 1
|
||||
continue
|
||||
if c in numbers:
|
||||
x += int(c)
|
||||
if c == '/':
|
||||
x = 0
|
||||
y -= 1
|
||||
|
||||
|
||||
# -- Active colour
|
||||
if position[index] == "w":
|
||||
ret._turn = Colour.WHITE
|
||||
elif position[index] == "b":
|
||||
ret._turn = Colour.BLACK
|
||||
else:
|
||||
raise ValueError(f"The FEN position is malformed, the active colour should be either 'w' or 'b', but is '{position[index]}'")
|
||||
index += 2
|
||||
|
||||
|
||||
# -- Castling Rights
|
||||
for c in position[index:]:
|
||||
index += 1
|
||||
if c == "-" or c == " ":
|
||||
if c == "-":
|
||||
index += 1
|
||||
break
|
||||
|
||||
sides = "kq"
|
||||
assert c in sides or c in sides.upper(), f"The FEN position is malformed, the castling rights should be either k or q (both either lower- or upper-case), instead is '{c}'"
|
||||
if c == "K":
|
||||
ret._white_castling_rights.add(CastleSide.King)
|
||||
if c == "Q":
|
||||
ret._white_castling_rights.add(CastleSide.Queen)
|
||||
if c == "k":
|
||||
ret._black_castling_rights.add(CastleSide.King)
|
||||
if c == "q":
|
||||
ret._black_castling_rights.add(CastleSide.Queen)
|
||||
|
||||
# -- En passant target
|
||||
if position[index] != "-":
|
||||
pos = Position.from_algebraic(position[index:index+2])
|
||||
index += 2
|
||||
if pos.y == 2:
|
||||
pos.y += 1
|
||||
assert pos in ret._white, "En passant target is not in the position"
|
||||
ret._en_passant_target = ret._white[pos]
|
||||
elif pos.y == 5:
|
||||
pos.y -= 1
|
||||
assert pos in ret._black, "En passant target is not in the position"
|
||||
ret._en_passant_target = ret._black[pos]
|
||||
else:
|
||||
raise ValueError("You can't have a en passant target that is not on the third or sixth rank")
|
||||
else:
|
||||
index += 1
|
||||
index += 1
|
||||
|
||||
ret._n_half_moves = int(position[index:position.find(" ", index + 1)])
|
||||
ret._n_moves = int(position[position.find(" ", index)+1:])
|
||||
|
||||
return ret
|
||||
|
||||
def piece_at(self, x: int, y: int) -> Piece | None:
|
||||
pos = Position(x, y)
|
||||
white_piece = self._white.get(pos, None)
|
||||
black_piece = self._black.get(pos, None)
|
||||
|
||||
assert white_piece == None or black_piece == None, f"There are two pieces at the same position {pos}, this shouldn't happen!"
|
||||
|
||||
if white_piece != None:
|
||||
return white_piece
|
||||
return black_piece
|
||||
|
||||
def is_check_for(self, colour: Colour) -> bool:
|
||||
""" Is it check for the defending colour passed as parameter """
|
||||
defending_pieces, attacking_pieces = (self._white, self._black) if colour == Colour.WHITE else (self._black, self._white)
|
||||
|
||||
kings = [piece for piece in defending_pieces.values() if type(piece) == King]
|
||||
assert len(kings) == 1, f"We have more than one king for {colour}, that is no buono..."
|
||||
king = kings[0]
|
||||
|
||||
for piece in attacking_pieces.values():
|
||||
possible_pos = []
|
||||
if type(piece) == King:
|
||||
# special case for the king, because it creates infinite recursion (since he looks if he's walking into a check)
|
||||
for dx in [-1, 0, 1]:
|
||||
for dy in [-1, 0, 1]:
|
||||
x, y = piece.pos.x + dx, piece.pos.y + dy
|
||||
if Position.is_within_bounds(x, y):
|
||||
possible_pos.append(Position(x, y))
|
||||
else:
|
||||
possible_pos += [move.pos for move in piece.legal_moves(self, looking_for_check=True)]
|
||||
if king.pos in possible_pos:
|
||||
return True
|
||||
return False
|
||||
|
||||
def is_checkmate_for(self, colour: Colour) -> bool:
|
||||
""" Is it checkmate for the defending colour passed as parameter """
|
||||
return self.is_check_for(colour) and self._no_legal_moves_for(colour)
|
||||
|
||||
def is_stalemate_for(self, colour: Colour) -> bool:
|
||||
""" Is it stalemate for the defending colour passed as parameter """
|
||||
return not self.is_check_for(colour) and self._no_legal_moves_for(colour)
|
||||
|
||||
def _no_legal_moves_for(self, colour: Colour) -> bool:
|
||||
""" Return true if there are indeed no legal moves for the given colour (for checkmate or stalemate)"""
|
||||
pieces = self._white if colour == Colour.WHITE else self._black
|
||||
for piece in pieces.values():
|
||||
if len(piece.legal_moves(self)) > 0:
|
||||
return False
|
||||
return True
|
||||
|
||||
def castling_rights_for(self, colour: Colour) -> set[CastleSide]:
|
||||
return self._white_castling_rights if colour == Colour.WHITE else self._black_castling_rights
|
||||
|
||||
def make_move(self, move: Move) -> "Board":
|
||||
dest_piece = self.piece_at(move.pos.x, move.pos.y)
|
||||
|
||||
if dest_piece:
|
||||
assert dest_piece.colour != move.piece.colour, "A piece cannot cannot eat another piece of the same colour"
|
||||
|
||||
# -- Copy current state
|
||||
ret = Board()
|
||||
ret._white = self._white.copy()
|
||||
ret._black = self._black.copy()
|
||||
ret._turn = Colour.WHITE if self._turn == Colour.BLACK else Colour.BLACK
|
||||
ret._white_castling_rights = self._white_castling_rights.copy()
|
||||
ret._black_castling_rights = self._black_castling_rights.copy()
|
||||
|
||||
|
||||
piece = move.piece
|
||||
|
||||
# -- Actually make the move
|
||||
pieces_moving, other_pieces = (ret._white, ret._black) if piece.colour == Colour.WHITE else (ret._black, ret._white)
|
||||
|
||||
del pieces_moving[piece.pos]
|
||||
pieces_moving[move.pos] = piece.move_to(move.pos)
|
||||
if move.pos in other_pieces:
|
||||
del other_pieces[move.pos]
|
||||
|
||||
if piece.colour == Colour.BLACK:
|
||||
ret._n_moves = self._n_moves + 1
|
||||
|
||||
if move.is_capturing or type(piece) == Pawn:
|
||||
ret._n_half_moves = 0
|
||||
else:
|
||||
ret._n_half_moves = self._n_half_moves + 1
|
||||
|
||||
if move.en_passant:
|
||||
pos_to_remove = Position(move.pos.x, move.pos.y + (1 if self._turn == Colour.BLACK else -1))
|
||||
del other_pieces[pos_to_remove]
|
||||
|
||||
if move.promotes_to is not None:
|
||||
assert type(piece) == Pawn, "Trying to promote something that is not a pawn: not good!"
|
||||
pieces_moving[move.pos] = move.promotes_to(move.pos, piece.colour)
|
||||
|
||||
# -- Set en passant target if needed
|
||||
if move.becomes_en_passant_target:
|
||||
ret._en_passant_target = pieces_moving[move.pos]
|
||||
else:
|
||||
ret._en_passant_target = None
|
||||
|
||||
# -- Handle castling (just move the rook over)
|
||||
if move.castle_side == CastleSide.King:
|
||||
rook_pos = Position(7, piece.pos.y)
|
||||
assert rook_pos in pieces_moving and type(pieces_moving[rook_pos]) == Rook, "Either rook is absent from the king side or you are trying to castle with something else than a rook..."
|
||||
del pieces_moving[rook_pos]
|
||||
new_rook_pos = Position(5, piece.pos.y)
|
||||
pieces_moving[new_rook_pos] = Rook(new_rook_pos, piece.colour)
|
||||
|
||||
elif move.castle_side == CastleSide.Queen:
|
||||
rook_pos = Position(0, piece.pos.y)
|
||||
assert rook_pos in pieces_moving and type(pieces_moving[rook_pos]) == Rook, "Either rook is absent from the queen side or you are trying to castle with something else than a rook..."
|
||||
del pieces_moving[rook_pos]
|
||||
new_rook_pos = Position(3, piece.pos.y)
|
||||
pieces_moving[new_rook_pos] = Rook(new_rook_pos, piece.colour)
|
||||
|
||||
# -- Check for castling rights
|
||||
if piece.colour == Colour.WHITE:
|
||||
if type(piece) == King:
|
||||
ret._white_castling_rights = set()
|
||||
|
||||
if type(piece) == Rook:
|
||||
if piece.pos.x == 0 and CastleSide.Queen in ret._white_castling_rights:
|
||||
ret._white_castling_rights.remove(CastleSide.Queen)
|
||||
elif piece.pos.x == 7 and CastleSide.King in ret._white_castling_rights:
|
||||
ret._white_castling_rights.remove(CastleSide.King)
|
||||
|
||||
if move.is_capturing and move.pos.y == 7 and move.pos in self._black and type(self._black[move.pos]) == Rook:
|
||||
if move.pos.x == 0 and CastleSide.Queen in ret._black_castling_rights:
|
||||
ret._black_castling_rights.remove(CastleSide.Queen)
|
||||
elif move.pos.x == 7 and CastleSide.King in ret._black_castling_rights:
|
||||
ret._black_castling_rights.remove(CastleSide.King)
|
||||
else:
|
||||
if type(piece) == King:
|
||||
ret._black_castling_rights = set()
|
||||
|
||||
if type(piece) == Rook:
|
||||
if piece.pos.x == 0 and CastleSide.Queen in ret._black_castling_rights:
|
||||
ret._black_castling_rights.remove(CastleSide.Queen)
|
||||
elif piece.pos.x == 7 and CastleSide.King in ret._black_castling_rights:
|
||||
ret._black_castling_rights.remove(CastleSide.King)
|
||||
|
||||
if move.is_capturing and move.pos.y == 0 and move.pos in self._white and type(self._white[move.pos]) == Rook:
|
||||
if move.pos.x == 0 and CastleSide.Queen in ret._white_castling_rights:
|
||||
ret._white_castling_rights.remove(CastleSide.Queen)
|
||||
elif move.pos.x == 7 and CastleSide.King in ret._white_castling_rights:
|
||||
ret._white_castling_rights.remove(CastleSide.King)
|
||||
|
||||
return ret
|
||||
|
||||
def to_fen_string(self):
|
||||
ret = ""
|
||||
for y in range(7, -1, -1):
|
||||
empty_cell_counter = 0
|
||||
for x in range(8):
|
||||
pos = Position(x, y)
|
||||
|
||||
piece = None
|
||||
if pos in self._white:
|
||||
piece = self._white[pos]
|
||||
elif pos in self._black:
|
||||
piece = self._black[pos]
|
||||
|
||||
if piece is None:
|
||||
empty_cell_counter += 1
|
||||
continue
|
||||
|
||||
if empty_cell_counter > 0:
|
||||
ret += str(empty_cell_counter)
|
||||
empty_cell_counter = 0
|
||||
letter = piece.letter()
|
||||
ret += letter.lower() if piece.colour == Colour.BLACK else letter.upper()
|
||||
|
||||
if empty_cell_counter > 0:
|
||||
ret += str(empty_cell_counter)
|
||||
|
||||
if y > 0:
|
||||
ret += "/"
|
||||
ret += " "
|
||||
|
||||
ret += "w" if self._turn == Colour.WHITE else "b"
|
||||
ret += " "
|
||||
|
||||
if len(self._white_castling_rights) == 0 and len(self._black_castling_rights) == 0:
|
||||
ret += "-"
|
||||
else:
|
||||
if CastleSide.King in self._white_castling_rights:
|
||||
ret += "K"
|
||||
if CastleSide.Queen in self._white_castling_rights:
|
||||
ret += "Q"
|
||||
|
||||
if CastleSide.King in self._black_castling_rights:
|
||||
ret += "k"
|
||||
if CastleSide.Queen in self._black_castling_rights:
|
||||
ret += "q"
|
||||
ret += " "
|
||||
|
||||
if self._en_passant_target is not None:
|
||||
pos = Position(self._en_passant_target.pos.x, self._en_passant_target.pos.y)
|
||||
pos.y += -1 if self._en_passant_target.colour == Colour.WHITE else 1
|
||||
ret += pos.to_algebraic()
|
||||
else:
|
||||
ret += "-"
|
||||
ret += " "
|
||||
|
||||
ret += str(self._n_half_moves)
|
||||
ret += " "
|
||||
ret += str(self._n_moves)
|
||||
|
||||
return ret
|
||||
|
||||
|
||||
def legal_moves(self) -> list[Move]:
|
||||
ret = []
|
||||
pieces = self._white if self._turn == Colour.WHITE else self._black
|
||||
for piece in pieces.values():
|
||||
ret += piece.legal_moves(self)
|
||||
return ret
|
||||
|
||||
def is_terminal(self) -> bool:
|
||||
return self.is_stalemate_for(Colour.WHITE) or self.is_stalemate_for(Colour.BLACK) or self.is_checkmate_for(Colour.WHITE) or self.is_checkmate_for(Colour.BLACK)
|
||||
|
||||
def utility(self) -> int:
|
||||
if self.is_stalemate_for(Colour.WHITE) or self.is_stalemate_for(Colour.BLACK):
|
||||
return 0
|
||||
|
||||
if self.is_checkmate_for(Colour.WHITE):
|
||||
return 1
|
||||
|
||||
if self.is_checkmate_for(Colour.BLACK):
|
||||
return -1
|
||||
|
||||
raise ValueError("Cannot determine the utility of board become it neither checkmate nor stalemate for either players")
|
||||
|
||||
_fen_pos = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
|
||||
INITIAL_BOARD = Board.setup_FEN_position(_fen_pos)
|
@ -1,51 +0,0 @@
|
||||
# from logic.pieces.piece import Piece
|
||||
from typing import Type
|
||||
from logic.position import Position
|
||||
from enum import Enum
|
||||
|
||||
class CastleSide(Enum):
|
||||
Neither = ""
|
||||
King = "O-O"
|
||||
Queen = "O-O-O"
|
||||
|
||||
class Move:
|
||||
def __init__(self, piece: "Piece", pos: Position,/, is_capturing: bool = False, castle_side: CastleSide = CastleSide.Neither, en_passant: bool = False, becomes_en_passant_target: bool = False, promotes_to: Type["Piece"] = None) -> None:
|
||||
self.piece = piece
|
||||
self.pos = pos
|
||||
self.is_capturing = is_capturing
|
||||
self.castle_side = castle_side
|
||||
self.becomes_en_passant_target = becomes_en_passant_target
|
||||
self.en_passant = en_passant
|
||||
self.promotes_to = promotes_to
|
||||
|
||||
def to_algebraic(self) -> str:
|
||||
raise NotImplementedError("The move can't be translated to algbraic notation, as it was not implemented")
|
||||
|
||||
@staticmethod
|
||||
def from_algebraic(move: str) -> "Move":
|
||||
raise NotImplementedError("The move can't be translated from algbraic notation, as it was not implemented")
|
||||
|
||||
def __str__(self) -> str:
|
||||
if self.castle_side == CastleSide.King:
|
||||
return "O-O"
|
||||
if self.castle_side == CastleSide.Queen:
|
||||
return "O-O-O"
|
||||
|
||||
ret = ""
|
||||
if type(self.piece).__name__ == "Pawn":
|
||||
if self.is_capturing:
|
||||
ret += self.piece.pos.to_algebraic()[0]
|
||||
ret += "x"
|
||||
ret += self.pos.to_algebraic()
|
||||
else:
|
||||
ret += self.pos.to_algebraic()
|
||||
else:
|
||||
ret += self.piece.letter().upper()
|
||||
if self.is_capturing:
|
||||
ret += "x"
|
||||
ret += str(self.pos)
|
||||
|
||||
return ret
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return str(self)
|
@ -1,24 +0,0 @@
|
||||
from logic.move import Move
|
||||
from .piece import Piece
|
||||
|
||||
class Bishop(Piece):
|
||||
def legal_moves(self, board: "Board", / , looking_for_check = False) -> list[Move]:
|
||||
ret = []
|
||||
|
||||
# looking north east
|
||||
ret.extend(self._look_direction(board, 1, 1))
|
||||
|
||||
# looking south east
|
||||
ret.extend(self._look_direction(board, 1, -1))
|
||||
|
||||
# looking south west
|
||||
ret.extend(self._look_direction(board, -1, -1))
|
||||
|
||||
# looking north west
|
||||
ret.extend(self._look_direction(board, -1, 1))
|
||||
|
||||
if not looking_for_check:# and board.is_check_for(self.colour):
|
||||
return self.keep_only_blocking(ret, board)
|
||||
|
||||
return ret
|
||||
|
@ -1,69 +0,0 @@
|
||||
from logic.move import CastleSide, Move
|
||||
from logic.position import Position
|
||||
from .piece import Piece
|
||||
|
||||
class King(Piece):
|
||||
def legal_moves(self, board: "Board") -> list[Move]:
|
||||
ret = []
|
||||
|
||||
# -- Regular moves
|
||||
for dx in [-1, 0, 1]:
|
||||
for dy in [-1, 0, 1]:
|
||||
if dx == 0 and dy == 0: # skip current position
|
||||
continue
|
||||
x = self.pos.x + dx
|
||||
y = self.pos.y + dy
|
||||
move = self._move_for_position(board, x, y)
|
||||
if move:
|
||||
board_after_move = board.make_move(move)
|
||||
if not board_after_move.is_check_for(self.colour):
|
||||
ret.append(move)
|
||||
|
||||
if board.is_check_for(self.colour):
|
||||
return self.keep_only_blocking(ret, board)
|
||||
|
||||
# -- Castles
|
||||
castling_rights = board.castling_rights_for(self.colour)
|
||||
if len(castling_rights) == 0:
|
||||
return ret
|
||||
|
||||
if CastleSide.King in castling_rights:
|
||||
clear = True
|
||||
for dx in range(1, 3):
|
||||
x = self.pos.x + dx
|
||||
y = self.pos.y
|
||||
if board.piece_at(x, y) is not None:
|
||||
clear = False
|
||||
break
|
||||
|
||||
move = self._move_for_position(board, x, y)
|
||||
board_after_move = board.make_move(move)
|
||||
if board_after_move.is_check_for(self.colour):
|
||||
clear = False
|
||||
break
|
||||
|
||||
if clear:
|
||||
ret.append(Move(self, Position(6, self.pos.y), castle_side=CastleSide.King))
|
||||
|
||||
if CastleSide.Queen in castling_rights:
|
||||
clear = True
|
||||
for dx in range(1, 4):
|
||||
x = self.pos.x - dx
|
||||
y = self.pos.y
|
||||
|
||||
if board.piece_at(x, y) is not None:
|
||||
clear = False
|
||||
break
|
||||
|
||||
move = self._move_for_position(board, x, y)
|
||||
board_after_move = board.make_move(move)
|
||||
if dx < 3 and board_after_move.is_check_for(self.colour):
|
||||
clear = False
|
||||
break
|
||||
|
||||
if clear:
|
||||
ret.append(Move(self, Position(2, self.pos.y), castle_side=CastleSide.Queen))
|
||||
|
||||
return ret
|
||||
|
||||
|
@ -1,23 +0,0 @@
|
||||
from .piece import Piece
|
||||
|
||||
class Knight(Piece):
|
||||
def letter(self):
|
||||
return "n"
|
||||
|
||||
def legal_moves(self, board: "Board", / , looking_for_check = False) -> list["Move"]:
|
||||
ret = []
|
||||
for dx, dy in [
|
||||
(+2, +1), (+1, +2), # north east
|
||||
(+2, -1), (+1, -2), # south east
|
||||
(-2, -1), (-1, -2), # south west
|
||||
(-2, +1), (-1, +2), # north west
|
||||
]:
|
||||
move = self._move_for_position(board, self.pos.x + dx, self.pos.y + dy)
|
||||
if move is not None:
|
||||
ret.append(move)
|
||||
|
||||
if not looking_for_check:# and board.is_check_for(self.colour):
|
||||
return self.keep_only_blocking(ret, board)
|
||||
|
||||
return ret
|
||||
|
@ -1,80 +0,0 @@
|
||||
from logic.move import Move
|
||||
from logic.pieces.bishop import Bishop
|
||||
from logic.pieces.knight import Knight
|
||||
from logic.pieces.piece import Colour, Piece
|
||||
from logic.pieces.queen import Queen
|
||||
from logic.pieces.rook import Rook
|
||||
from logic.position import Position
|
||||
|
||||
class Pawn(Piece):
|
||||
def legal_moves(self, board, / , looking_for_check = False) -> list[Move]:
|
||||
ret = []
|
||||
|
||||
# can we capture to the left?
|
||||
if self.pos.x > 0 and (
|
||||
(self.colour == Colour.WHITE and (capturable_piece := board.piece_at(self.pos.x - 1, self.pos.y + 1)))
|
||||
or
|
||||
(self.colour == Colour.BLACK and (capturable_piece := board.piece_at(self.pos.x - 1, self.pos.y - 1)))
|
||||
):
|
||||
if capturable_piece.colour != self.colour:
|
||||
if (self.colour == Colour.WHITE and capturable_piece.pos.y == 7) or (self.colour == Colour.BLACK and capturable_piece.pos.y == 0):
|
||||
for piece in [Queen, Knight, Bishop, Rook]:
|
||||
ret.append(Move(self, capturable_piece.pos, is_capturing=True, promotes_to=piece))
|
||||
else:
|
||||
ret.append(Move(self, capturable_piece.pos, is_capturing = True))
|
||||
|
||||
# can we capture to the right?
|
||||
if self.pos.x < 7 and (
|
||||
(self.colour == Colour.WHITE and (capturable_piece := board.piece_at(self.pos.x + 1, self.pos.y + 1)))
|
||||
or
|
||||
(self.colour == Colour.BLACK and (capturable_piece := board.piece_at(self.pos.x + 1, self.pos.y - 1)))
|
||||
):
|
||||
if capturable_piece.colour != self.colour:
|
||||
if (self.colour == Colour.WHITE and capturable_piece.pos.y == 7) or (self.colour == Colour.BLACK and capturable_piece.pos.y == 0):
|
||||
for piece in [Queen, Knight, Bishop, Rook]:
|
||||
ret.append(Move(self, capturable_piece.pos, is_capturing=True, promotes_to=piece))
|
||||
else:
|
||||
ret.append(Move(self, capturable_piece.pos, is_capturing = True))
|
||||
|
||||
# -- Can we capture en passant?
|
||||
if board._en_passant_target is not None and \
|
||||
board._en_passant_target.pos.y == self.pos.y and (
|
||||
board._en_passant_target.pos.x == self.pos.x - 1
|
||||
or board._en_passant_target.pos.x == self.pos.x + 1
|
||||
):
|
||||
if board._en_passant_target.colour != self.colour:
|
||||
old_pos = board._en_passant_target.pos
|
||||
new_pos = Position(old_pos.x, old_pos.y + (1 if self.colour == Colour.WHITE else -1))
|
||||
ret.append(Move(self, new_pos, is_capturing = True, en_passant = True))
|
||||
|
||||
# -- Normal moves
|
||||
if self.colour == Colour.WHITE:
|
||||
for dy in range(1, 3 if self.pos.y == 1 else 2):
|
||||
y = self.pos.y + dy
|
||||
if y > 7 or board.piece_at(self.pos.x, y):
|
||||
break
|
||||
pos = Position(self.pos.x, y)
|
||||
if y == 7:
|
||||
for piece in [Queen, Knight, Bishop, Rook]:
|
||||
ret.append(Move(self, pos, promotes_to=piece))
|
||||
else:
|
||||
ret.append(Move(self, pos, becomes_en_passant_target=dy==2))
|
||||
else:
|
||||
for dy in range(1, 3 if self.pos.y == 6 else 2):
|
||||
y = self.pos.y - dy
|
||||
if y < 0 or board.piece_at(self.pos.x, y):
|
||||
break
|
||||
pos = Position(self.pos.x, y)
|
||||
if y == 0:
|
||||
for piece in [Queen, Knight, Bishop, Rook]:
|
||||
ret.append(Move(self, pos, promotes_to=piece))
|
||||
else:
|
||||
ret.append(Move(self, pos, becomes_en_passant_target=dy==2))
|
||||
|
||||
if not looking_for_check:# and board.is_check_for(self.colour):
|
||||
return self.keep_only_blocking(ret, board)
|
||||
|
||||
return ret
|
||||
|
||||
def letter(self):
|
||||
return "p"
|
@ -1,65 +0,0 @@
|
||||
from logic.move import Move
|
||||
from logic.position import Position
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class Colour(Enum):
|
||||
WHITE = "white"
|
||||
BLACK = "black"
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.value
|
||||
|
||||
class Piece:
|
||||
def __init__(self, pos: Position, colour: Colour) -> None:
|
||||
self.pos = pos
|
||||
assert colour == Colour.WHITE or colour == Colour.BLACK, "The colour of the piece must be either Piece.WHITE or Piece.BLACK"
|
||||
self.colour = colour
|
||||
|
||||
def letter(self):
|
||||
return type(self).__name__[0].lower()
|
||||
|
||||
def keep_only_blocking(self, candidates: list[Move], board: "Board") -> list[Move]:
|
||||
ret = []
|
||||
for move in candidates:
|
||||
board_after_move = board.make_move(move)
|
||||
if not board_after_move.is_check_for(self.colour):
|
||||
ret.append(move)
|
||||
return ret
|
||||
|
||||
def _look_direction(self, board: "Board", mult_dx: int, mult_dy: int):
|
||||
ret = []
|
||||
for d in range(1, 8):
|
||||
dx = mult_dx * d
|
||||
dy = mult_dy * d
|
||||
|
||||
move = self._move_for_position(board, self.pos.x + dx, self.pos.y + dy)
|
||||
if move is None:
|
||||
break
|
||||
ret.append(move)
|
||||
if move.is_capturing:
|
||||
break
|
||||
|
||||
return ret
|
||||
|
||||
def _move_for_position(self, board: "Board", x: int, y: int) -> Move | None:
|
||||
if not Position.is_within_bounds(x, y):
|
||||
return None
|
||||
piece = board.piece_at(x, y)
|
||||
|
||||
if piece is None:
|
||||
return Move(self, Position(x, y))
|
||||
|
||||
if piece.colour != self.colour:
|
||||
return Move(self, Position(x, y), is_capturing=True)
|
||||
return None
|
||||
|
||||
def position(self) -> Position:
|
||||
return self.pos
|
||||
|
||||
def move_to(self, pos: Position) -> "Piece":
|
||||
ret = type(self)(pos, self.colour)
|
||||
return ret
|
||||
|
||||
def legal_moves(self, board: "Board", / , looking_for_check = False) -> list["Move"]:
|
||||
raise NotImplementedError(f"Can't say what the legal moves are for {type(self).__name__}, the method hasn't been implemented yet")
|
@ -1,35 +0,0 @@
|
||||
from logic.move import Move
|
||||
from .piece import Piece
|
||||
|
||||
class Queen(Piece):
|
||||
def legal_moves(self, board: "Board", / , looking_for_check = False) -> list[Move]:
|
||||
ret = []
|
||||
|
||||
# looking north east
|
||||
ret.extend(self._look_direction(board, 1, 1))
|
||||
|
||||
# looking south east
|
||||
ret.extend(self._look_direction(board, 1, -1))
|
||||
|
||||
# looking south west
|
||||
ret.extend(self._look_direction(board, -1, -1))
|
||||
|
||||
# looking north west
|
||||
ret.extend(self._look_direction(board, -1, 1))
|
||||
|
||||
# looking east
|
||||
ret.extend(self._look_direction(board, 1, 0))
|
||||
|
||||
# looking south
|
||||
ret.extend(self._look_direction(board, 0, -1))
|
||||
|
||||
# looking west
|
||||
ret.extend(self._look_direction(board, -1, 0))
|
||||
|
||||
# looking north
|
||||
ret.extend(self._look_direction(board, 0, 1))
|
||||
|
||||
if not looking_for_check:# and board.is_check_for(self.colour):
|
||||
return self.keep_only_blocking(ret, board)
|
||||
|
||||
return ret
|
@ -1,23 +0,0 @@
|
||||
from logic.move import Move
|
||||
from .piece import Piece
|
||||
|
||||
class Rook(Piece):
|
||||
def legal_moves(self, board: "Board", / , looking_for_check = False) -> list[Move]:
|
||||
ret = []
|
||||
|
||||
# looking east
|
||||
ret.extend(self._look_direction(board, 1, 0))
|
||||
|
||||
# looking south
|
||||
ret.extend(self._look_direction(board, 0, -1))
|
||||
|
||||
# looking west
|
||||
ret.extend(self._look_direction(board, -1, 0))
|
||||
|
||||
# looking north
|
||||
ret.extend(self._look_direction(board, 0, 1))
|
||||
|
||||
if not looking_for_check:# and board.is_check_for(self.colour):
|
||||
return self.keep_only_blocking(ret, board)
|
||||
|
||||
return ret
|
@ -1,43 +0,0 @@
|
||||
class Position:
|
||||
_RANKS = range(1, 9)
|
||||
_FILES = "abcdefgh"
|
||||
|
||||
_MIN_POS = 0
|
||||
_MAX_POS = 7
|
||||
|
||||
def __init__(self, x, y) -> None:
|
||||
assert x >= self._MIN_POS and x <= self._MAX_POS, f"Invalid argument: x should be between {self._MIN_POS} and {self._MAX_POS}, but is {x}"
|
||||
assert y >= self._MIN_POS and y <= self._MAX_POS, f"Invalid argument: y should be between {self._MIN_POS} and {self._MAX_POS}, but is {y}"
|
||||
|
||||
self.x = x
|
||||
self.y = y
|
||||
|
||||
@staticmethod
|
||||
def is_within_bounds(x: int, y: int) -> bool:
|
||||
return x >= Position._MIN_POS and x <= Position._MAX_POS \
|
||||
and y >= Position._MIN_POS and y <= Position._MAX_POS
|
||||
|
||||
@staticmethod
|
||||
def from_algebraic(square: str) -> "Position":
|
||||
assert len(square) == 2, f"'{square}' is malformed"
|
||||
x = Position._FILES.index(square[0])
|
||||
y = Position._RANKS.index(int(square[1]))
|
||||
|
||||
return Position(x, y)
|
||||
|
||||
def to_algebraic(self) -> str:
|
||||
return f"{Position._FILES[self.x]}{Position._RANKS[self.y]}"
|
||||
|
||||
def __eq__(self, value: object, /) -> bool:
|
||||
if type(value) != type(self):
|
||||
return False
|
||||
return value.x == self.x and value.y == self.y
|
||||
|
||||
def __hash__(self) -> int:
|
||||
return hash((self.x, self.y))
|
||||
|
||||
def __str__(self) -> str:
|
||||
return f"{Position._FILES[self.x]}{Position._RANKS[self.y]}"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return str(self)
|
@ -1,27 +0,0 @@
|
||||
import time
|
||||
from pprint import pprint
|
||||
from tqdm import tqdm
|
||||
|
||||
from ai.ai import move_generation_test
|
||||
from controller.controller import Controller
|
||||
from logic.board import INITIAL_BOARD, Board
|
||||
from logic.position import Position
|
||||
from view.gui import GUI
|
||||
from view.tui import TUI
|
||||
|
||||
from ai.ai import peft
|
||||
|
||||
if __name__ == "__main__":
|
||||
board = INITIAL_BOARD
|
||||
|
||||
pos = "rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8"
|
||||
board = Board.setup_FEN_position(pos)
|
||||
|
||||
view = GUI()
|
||||
|
||||
controller = Controller(board, view)
|
||||
|
||||
# view.show()
|
||||
# exit()
|
||||
|
||||
peft(pos)
|
@ -1,155 +0,0 @@
|
||||
import tkinter as tk
|
||||
from tkinter import messagebox
|
||||
from typing import Type
|
||||
from PIL import ImageTk, Image
|
||||
import os
|
||||
|
||||
from logic.board import Board
|
||||
from logic.move import Move
|
||||
from logic.pieces.bishop import Bishop
|
||||
from logic.pieces.king import King
|
||||
from logic.pieces.knight import Knight
|
||||
from logic.pieces.pawn import Pawn
|
||||
from logic.pieces.piece import Colour, Piece
|
||||
from logic.pieces.queen import Queen
|
||||
from logic.pieces.rook import Rook
|
||||
from logic.position import Position
|
||||
from view.view import View
|
||||
|
||||
class GUI(View):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
|
||||
self.root = tk.Tk()
|
||||
self.root.title("Chess Board")
|
||||
|
||||
self.tile_size = 80
|
||||
board_size = self.tile_size * 8
|
||||
|
||||
self.canvas = tk.Canvas(self.root, width=board_size, height=board_size)
|
||||
self.canvas.pack()
|
||||
|
||||
self.canvas.bind("<Button-1>", self._on_canvas_click)
|
||||
|
||||
self._piece_images = self._load_piece_images("res/")
|
||||
|
||||
def _piece_svg(self, root: str, piece: Type[Piece], colour: Colour) -> ImageTk.PhotoImage:
|
||||
piece_name = piece.__name__.lower()
|
||||
|
||||
path = os.path.join(root, f"{"white" if colour == Colour.WHITE else "black"}-{piece_name}.png")
|
||||
img = Image.open(path)
|
||||
|
||||
if img.mode == "LA":
|
||||
img = img.convert(mode="RGBA")
|
||||
img.save(path)
|
||||
|
||||
return ImageTk.PhotoImage(img)
|
||||
|
||||
def _load_piece_images(self, root: str) -> dict[Type[Piece], dict[Colour, ImageTk.PhotoImage]]:
|
||||
ret = {}
|
||||
for piece in [Pawn, Rook, Knight, Bishop, Queen, King]:
|
||||
if piece not in ret:
|
||||
ret[piece] = {}
|
||||
ret[piece][Colour.WHITE] = self._piece_svg(root, piece, Colour.WHITE)
|
||||
ret[piece][Colour.BLACK] = self._piece_svg(root, piece, Colour.BLACK)
|
||||
|
||||
return ret
|
||||
|
||||
def _on_canvas_click(self, event):
|
||||
x, y = event.x // self.tile_size, event.y // self.tile_size
|
||||
y = 7 - y
|
||||
|
||||
self._controller.on_tile_selected(x, y)
|
||||
|
||||
def notify_checkmate(self, colour: Colour) -> None:
|
||||
messagebox.showinfo("Checkmate", f"{colour} is currently checkmated")
|
||||
|
||||
def notify_stalemate(self, colour: Colour) -> None:
|
||||
messagebox.showinfo("Stalemate", f"{colour} is currently stalemated")
|
||||
|
||||
|
||||
def update_board(self, board: Board, selected_piece: Piece, legal_moves: list[Move]) -> None:
|
||||
self.canvas.delete("all")
|
||||
self._draw_chess_board(board, selected_piece, legal_moves)
|
||||
|
||||
|
||||
def _draw_chess_board(self, board: Board, selected_piece = None, legal_moves = []):
|
||||
colours = ["#EDD6B0", "#B88762"] # Light and dark squares
|
||||
alt_colours = ["#F6EB72", "#DCC34B"] # Light and dark squares, when selected
|
||||
circle_colours = ["#CCB897", "#9E7454"] # circles to show legal moves
|
||||
|
||||
for y in range(8):
|
||||
for x in range(8):
|
||||
colour = colours[(x + y) % 2]
|
||||
pos = Position(x, 7-y)
|
||||
if selected_piece is not None and pos == selected_piece.pos:
|
||||
colour = alt_colours[(x + y) % 2]
|
||||
|
||||
self.canvas.create_rectangle(
|
||||
x * self.tile_size,
|
||||
y * self.tile_size,
|
||||
(x + 1) * self.tile_size,
|
||||
(y + 1) * self.tile_size,
|
||||
fill=colour,
|
||||
outline=colour,
|
||||
)
|
||||
|
||||
if selected_piece is not None:
|
||||
possible_positions = [move.pos for move in legal_moves]
|
||||
if pos in possible_positions:
|
||||
colour = circle_colours[(x + y) % 2]
|
||||
move = [move for move in legal_moves if move.pos == pos][0]
|
||||
if move.is_capturing:
|
||||
radius = .40 * self.tile_size
|
||||
self.canvas.create_oval(
|
||||
(x + .5) * self.tile_size - radius,
|
||||
(y + .5) * self.tile_size - radius,
|
||||
(x + .5) * self.tile_size + radius,
|
||||
(y + .5) * self.tile_size + radius,
|
||||
fill="",
|
||||
outline=colour,
|
||||
width=.075 * self.tile_size,
|
||||
)
|
||||
else:
|
||||
radius = .15 * self.tile_size
|
||||
self.canvas.create_oval(
|
||||
(x + .5) * self.tile_size - radius,
|
||||
(y + .5) * self.tile_size - radius,
|
||||
(x + .5) * self.tile_size + radius,
|
||||
(y + .5) * self.tile_size + radius,
|
||||
fill=colour,
|
||||
outline=colour,
|
||||
)
|
||||
|
||||
piece = board.piece_at(x, 7-y)
|
||||
|
||||
if piece:
|
||||
self.canvas.create_image(
|
||||
(x + 0.5) * self.tile_size,
|
||||
(y + 0.9) * self.tile_size,
|
||||
image=self._piece_images[type(piece)][piece.colour],
|
||||
anchor=tk.S,
|
||||
)
|
||||
|
||||
# Cell annotations
|
||||
text_colour = colours[(x + y + 1) % 2] # the other colour
|
||||
|
||||
if x == 0: # numbers in the top left of the first column
|
||||
self.canvas.create_text(
|
||||
(x + .15) * self.tile_size,
|
||||
(y + .15) * self.tile_size,
|
||||
text=8-y,
|
||||
fill=text_colour,
|
||||
font=("Arial", 12, "bold")
|
||||
)
|
||||
if y == 7: # numbers in the top left of the first column
|
||||
self.canvas.create_text(
|
||||
(x + .85) * self.tile_size,
|
||||
(y + .85) * self.tile_size,
|
||||
text="abcdefgh"[x],
|
||||
fill=text_colour,
|
||||
font=("Arial", 12, "bold")
|
||||
)
|
||||
|
||||
def show(self) -> None:
|
||||
self.root.mainloop()
|
@ -1,57 +0,0 @@
|
||||
from logic.board import Board
|
||||
from logic.pieces.bishop import Bishop
|
||||
from logic.pieces.king import King
|
||||
from logic.pieces.knight import Knight
|
||||
from logic.pieces.pawn import Pawn
|
||||
from logic.pieces.piece import Piece
|
||||
from logic.pieces.queen import Queen
|
||||
from logic.pieces.rook import Rook
|
||||
from view.view import View
|
||||
|
||||
class TUI(View):
|
||||
def __init__(self, board: Board) -> None:
|
||||
super().__init__(board)
|
||||
|
||||
def show(self) -> None:
|
||||
board_view = [
|
||||
[" " for _ in range(0, 8)]
|
||||
for _ in range(0, 8)
|
||||
]
|
||||
|
||||
for pos, piece in self.board._white.items():
|
||||
board_view[pos.y][pos.x] = self.string_of(piece).upper()
|
||||
|
||||
for pos, piece in self.board._black.items():
|
||||
board_view[pos.y][pos.x] = self.string_of(piece)
|
||||
|
||||
# we reverse the board because (0, 0) in in the bottom left, not top left
|
||||
board_view.reverse()
|
||||
print(self.to_string(board_view))
|
||||
|
||||
def to_string(self, board_view: list[list[str]]) -> str:
|
||||
VER_SEP = "|"
|
||||
HOR_SEP = "-"
|
||||
ROW_SEP = HOR_SEP * (2*len(board_view[0]) + 1)
|
||||
ret = ROW_SEP + "\n"
|
||||
for row_view in board_view:
|
||||
row_str = VER_SEP + VER_SEP.join(row_view) + VER_SEP
|
||||
ret += row_str + "\n"
|
||||
ret += ROW_SEP + "\n"
|
||||
|
||||
return ret
|
||||
|
||||
def string_of(self, piece: Piece) -> str:
|
||||
type_ = type(piece)
|
||||
if type_ == Pawn:
|
||||
return "p"
|
||||
if type_ == Queen:
|
||||
return "q"
|
||||
if type_ == Bishop:
|
||||
return "b"
|
||||
if type_ == Knight:
|
||||
return "n"
|
||||
if type_ == Rook:
|
||||
return "r"
|
||||
if type_ == King:
|
||||
return "k"
|
||||
raise ValueError(f"Unknown piece type {type(piece)}")
|
@ -1,24 +0,0 @@
|
||||
from logic.board import Board
|
||||
from logic.move import Move
|
||||
from logic.pieces.piece import Colour, Piece
|
||||
|
||||
|
||||
class View:
|
||||
def __init__(self) -> None:
|
||||
self._controller: "Controller" = None
|
||||
|
||||
def show(self) -> None:
|
||||
raise NotImplementedError(f"Can't show the board, the show() method of {type(self)} is not implemented")
|
||||
|
||||
def update_board(self, board: Board, selected_piece: Piece, legal_moves: list[Move]) -> None:
|
||||
raise NotImplementedError(f"Can't update the board, the update_board() method of {type(self)} is not implemented")
|
||||
|
||||
def notify_checkmate(self, colour: Colour) -> None:
|
||||
raise NotImplementedError(f"Can't notify of the checkmate, the notify_checkmate() method of {type(self)} is not implemented")
|
||||
|
||||
def notify_stalemate(self, colour: Colour) -> None:
|
||||
raise NotImplementedError(f"Can't notify of the stalemate, the notify_stalemate() method of {type(self)} is not implemented")
|
||||
|
||||
def set_controller(self, controller: "Controller") -> None:
|
||||
self._controller = controller
|
||||
|
@ -1,30 +0,0 @@
|
||||
import unittest
|
||||
|
||||
import sys
|
||||
sys.path.append('src') # you must execute pytest from the stickfosh dir for this to work
|
||||
|
||||
from logic.board import Board
|
||||
|
||||
class FENTests(unittest.TestCase):
|
||||
def testInitialPosition(self):
|
||||
pos = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
|
||||
self.assertEqual(pos, Board.setup_FEN_position(pos).to_fen_string())
|
||||
|
||||
def testRandomPositions(self):
|
||||
pos = "r1bk3r/p2pBpNp/n4n2/1p1NP2P/6P1/3P4/P1P1K3/q5b1 b Qk - 0 1"
|
||||
self.assertEqual(pos, Board.setup_FEN_position(pos).to_fen_string())
|
||||
|
||||
pos = "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1"
|
||||
self.assertEqual(pos, Board.setup_FEN_position(pos).to_fen_string())
|
||||
|
||||
pos = "4k2r/6r1/8/8/8/8/3R4/R3K3 w Qk - 0 1"
|
||||
self.assertEqual(pos, Board.setup_FEN_position(pos).to_fen_string())
|
||||
|
||||
pos = "8/8/8/4p1K1/2k1P3/8/8/8 b - - 0 1"
|
||||
self.assertEqual(pos, Board.setup_FEN_position(pos).to_fen_string())
|
||||
|
||||
pos = "8/5k2/3p4/1p1Pp2p/pP2Pp1P/P4P1K/8/8 b - - 99 50"
|
||||
self.assertEqual(pos, Board.setup_FEN_position(pos).to_fen_string())
|
||||
|
||||
|
||||
|
@ -1,30 +0,0 @@
|
||||
import unittest
|
||||
|
||||
import sys
|
||||
sys.path.append('src') # you must execute pytest from the stickfosh dir for this to work
|
||||
|
||||
from logic.position import Position
|
||||
|
||||
class PositionTests(unittest.TestCase):
|
||||
def testXY2Algebraic(self):
|
||||
self.assertEqual(Position(0, 0).to_algebraic(), "a1")
|
||||
self.assertEqual(Position(1, 0).to_algebraic(), "b1")
|
||||
|
||||
self.assertEqual(Position(2, 1).to_algebraic(), "c2")
|
||||
self.assertEqual(Position(4, 2).to_algebraic(), "e3")
|
||||
|
||||
self.assertEqual(Position(7, 7).to_algebraic(), "h8")
|
||||
|
||||
def testAlgebraic2XY(self):
|
||||
self.assertEqual(Position.from_algebraic("a1"), Position(0, 0))
|
||||
self.assertEqual(Position.from_algebraic("b1"), Position(1, 0))
|
||||
|
||||
self.assertEqual(Position.from_algebraic("c2"), Position(2, 1))
|
||||
self.assertEqual(Position.from_algebraic("e3"), Position(4, 2))
|
||||
|
||||
self.assertEqual(Position.from_algebraic("h8"), Position(7, 7))
|
||||
|
||||
self.assertRaises(AssertionError, lambda : Position.from_algebraic("a11"))
|
||||
|
||||
self.assertRaises(ValueError, lambda : Position.from_algebraic("j1"))
|
||||
self.assertRaises(ValueError, lambda : Position.from_algebraic("a9"))
|
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
Before Width: | Height: | Size: 3.5 KiB After Width: | Height: | Size: 3.5 KiB |
Before Width: | Height: | Size: 1.8 KiB After Width: | Height: | Size: 1.8 KiB |
Before Width: | Height: | Size: 734 B After Width: | Height: | Size: 734 B |
Before Width: | Height: | Size: 2.7 KiB After Width: | Height: | Size: 2.7 KiB |
Before Width: | Height: | Size: 1014 B After Width: | Height: | Size: 1014 B |
Before Width: | Height: | Size: 4.2 KiB After Width: | Height: | Size: 4.2 KiB |
Before Width: | Height: | Size: 2.5 KiB After Width: | Height: | Size: 2.5 KiB |
Before Width: | Height: | Size: 3.0 KiB After Width: | Height: | Size: 3.0 KiB |
Before Width: | Height: | Size: 2.2 KiB After Width: | Height: | Size: 2.2 KiB |
Before Width: | Height: | Size: 1.4 KiB After Width: | Height: | Size: 1.4 KiB |
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 3.8 KiB |
Before Width: | Height: | Size: 1.3 KiB After Width: | Height: | Size: 1.3 KiB |
BIN
res/stickfosh.gif
Normal file
After Width: | Height: | Size: 3.8 MiB |
38
src/controller/ai_vs_ai.cpp
Normal file
@ -0,0 +1,38 @@
|
||||
#include "ai_vs_ai.hpp"
|
||||
|
||||
#include "controller.hpp"
|
||||
|
||||
#include <thread>
|
||||
|
||||
AIvsAIController::AIvsAIController(Board b, View& v, ai::AI& p1, ai::AI& p2)
|
||||
: Controller(b, v),
|
||||
p1(p1),
|
||||
p2(p2) {}
|
||||
|
||||
void AIvsAIController::start() {
|
||||
std::thread view_thread([&]() { view.show(); });
|
||||
ai::AI* current_player;
|
||||
while (!board.is_terminal()) {
|
||||
current_player = board.white_to_play ? &p1 : &p2;
|
||||
std::cout << typeid(*current_player).name() << " to play" << std::endl;
|
||||
Move move = current_player->search(board);
|
||||
make_move(move);
|
||||
}
|
||||
|
||||
view_thread.join();
|
||||
}
|
||||
|
||||
void AIvsAIController::make_move(Move move) {
|
||||
board = board.make_move(move);
|
||||
std::cout << "Made move: " << move << std::endl;
|
||||
view.update_board(board, -1, {});
|
||||
|
||||
Colour current_colour = board.white_to_play ? White : Black;
|
||||
if (board.is_checkmate())
|
||||
view.notify_checkmate(current_colour);
|
||||
|
||||
if (board.is_stalemate())
|
||||
view.notify_stalemate(current_colour);
|
||||
}
|
||||
|
||||
void AIvsAIController::on_tile_selected(int, int) {}
|
19
src/controller/ai_vs_ai.hpp
Normal file
@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include "../model/ais/ai.hpp"
|
||||
#include "../model/utils/coords.hpp"
|
||||
#include "../model/utils/move.hpp"
|
||||
#include "../view/view.hpp"
|
||||
#include "controller.hpp"
|
||||
|
||||
class AIvsAIController : public Controller {
|
||||
ai::AI &p1, &p2;
|
||||
|
||||
protected:
|
||||
void make_move(Move) override;
|
||||
|
||||
public:
|
||||
AIvsAIController(Board, View&, ai::AI&, ai::AI&);
|
||||
void on_tile_selected(int, int) override;
|
||||
void start() override;
|
||||
};
|
7
src/controller/controller.cpp
Normal file
@ -0,0 +1,7 @@
|
||||
#include "controller.hpp"
|
||||
|
||||
#include "../view/view.hpp"
|
||||
|
||||
Controller::Controller(Board b, View& v): board(b), view(v) {
|
||||
v.set_controller(this);
|
||||
}
|
@ -7,8 +7,11 @@ class View;
|
||||
class Controller {
|
||||
protected:
|
||||
Board board;
|
||||
View& view;
|
||||
virtual void make_move(Move) = 0;
|
||||
|
||||
public:
|
||||
// Controller(Board, View);
|
||||
Controller(Board, View&);
|
||||
virtual void start() = 0;
|
||||
virtual void on_tile_selected(int, int) = 0;
|
||||
};
|
@ -4,10 +4,7 @@
|
||||
|
||||
HumanVsAIController::HumanVsAIController(Board b, View& v, ai::AI& ai)
|
||||
: ManualController(b, v),
|
||||
ai(ai) {
|
||||
view.set_controller(this);
|
||||
reset_selection();
|
||||
}
|
||||
ai(ai) {}
|
||||
|
||||
void HumanVsAIController::on_tile_selected(int x, int y) {
|
||||
Coords c{x, y};
|
@ -4,12 +4,15 @@
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
ManualController::ManualController(Board b, View& view): view(view) {
|
||||
board = b;
|
||||
view.set_controller(this);
|
||||
ManualController::ManualController(Board b, View& v): Controller(b, v) {
|
||||
reset_selection();
|
||||
}
|
||||
|
||||
void ManualController::start() {
|
||||
reset_selection();
|
||||
view.show();
|
||||
}
|
||||
|
||||
void ManualController::on_tile_selected(int x, int y) {
|
||||
Coords c{x, y};
|
||||
Piece piece = board.piece_at(c);
|
||||
@ -48,13 +51,24 @@ void ManualController::show_legal_moves(Coords xy) {
|
||||
}
|
||||
|
||||
void ManualController::make_move(Move move) {
|
||||
// handle promotion before making the move
|
||||
Colour colour = board.white_to_play ? White : Black;
|
||||
Coords source = Coords::from_index(move.source_square);
|
||||
if (board.piece_at(move.source_square) == Piece::Pawn
|
||||
&& board.colour_at(move.source_square) == White && source.y == 6) {
|
||||
Piece promotion_piece = (Piece) (colour | view.ask_about_promotion());
|
||||
move.promoting_to = promotion_piece;
|
||||
}
|
||||
|
||||
std::cout << "Move made: " << move << std::endl;
|
||||
|
||||
board = board.make_move(move);
|
||||
reset_selection();
|
||||
|
||||
Colour current_colour = board.white_to_play ? White : Black;
|
||||
if (board.is_checkmate_for(current_colour))
|
||||
if (board.is_checkmate())
|
||||
view.notify_checkmate(current_colour);
|
||||
|
||||
if (board.is_stalemate_for(current_colour))
|
||||
if (board.is_stalemate())
|
||||
view.notify_stalemate(current_colour);
|
||||
}
|
@ -7,16 +7,16 @@
|
||||
|
||||
class ManualController : public Controller {
|
||||
protected:
|
||||
View& view;
|
||||
int8_t selected_index;
|
||||
Piece selected_piece;
|
||||
std::vector<int8_t> targets;
|
||||
|
||||
void reset_selection();
|
||||
void show_legal_moves(Coords);
|
||||
void make_move(Move);
|
||||
void make_move(Move) override;
|
||||
|
||||
public:
|
||||
ManualController(Board, View&);
|
||||
void on_tile_selected(int, int) override;
|
||||
void start() override;
|
||||
};
|
81
src/main.cpp
Normal file
@ -0,0 +1,81 @@
|
||||
#include "controller/ai_vs_ai.hpp"
|
||||
#include "controller/controller.hpp"
|
||||
#include "controller/human_vs_ai.hpp"
|
||||
#include "controller/manual.hpp"
|
||||
#include "model/ais/ai.hpp"
|
||||
#include "model/perft/perft.hpp"
|
||||
#include "view/gui.hpp"
|
||||
#include "view/noop.hpp"
|
||||
#include "view/view.hpp"
|
||||
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
void print_usage() {
|
||||
std::cout << "Usage: chess_ai [OPTIONS]\n";
|
||||
std::cout << "Options:\n";
|
||||
std::cout
|
||||
<< " --mode <human_vs_ai|ai_vs_ai|human_vs_human|perft> Choose the "
|
||||
"game mode.\n";
|
||||
std::cout << " --ai1 <version> Choose the first AI version (for ai_vs_ai "
|
||||
"mode).\n";
|
||||
std::cout << " --ai2 <version> Choose the second AI version (for "
|
||||
"ai_vs_ai mode).\n";
|
||||
std::cout << " --fen <FEN_STRING> Set a custom FEN position.\n";
|
||||
std::cout << " --help Show this help message.\n";
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
std::string mode = "human_vs_ai";
|
||||
std::string ai1_version = "v0_random";
|
||||
std::string ai2_version = "v6_iterative_deepening";
|
||||
std::string fen =
|
||||
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
|
||||
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
std::string arg = argv[i];
|
||||
if (arg == "--mode" && i + 1 < argc) {
|
||||
mode = argv[++i];
|
||||
} else if (arg == "--ai1" && i + 1 < argc) {
|
||||
ai1_version = argv[++i];
|
||||
} else if (arg == "--ai2" && i + 1 < argc) {
|
||||
ai2_version = argv[++i];
|
||||
} else if (arg == "--fen" && i + 1 < argc) {
|
||||
fen = argv[++i];
|
||||
} else if (arg == "--help") {
|
||||
print_usage();
|
||||
return 0;
|
||||
} else {
|
||||
std::cerr << "Unknown option: " << arg << "\n";
|
||||
print_usage();
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
Board board = Board::setup_fen_position(fen);
|
||||
GUI gui;
|
||||
Controller* controller = nullptr;
|
||||
|
||||
if (mode == "human_vs_ai") {
|
||||
ai::v6_iterative_deepening ai(false, std::chrono::milliseconds(2000));
|
||||
controller = new HumanVsAIController(board, gui, ai);
|
||||
} else if (mode == "ai_vs_ai") {
|
||||
ai::v0_random p1(true, std::chrono::milliseconds(1000));
|
||||
ai::v6_iterative_deepening p2(false, std::chrono::milliseconds(2000));
|
||||
controller = new AIvsAIController(board, gui, p1, p2);
|
||||
} else if (mode == "human_vs_human") {
|
||||
controller = new ManualController(board, gui);
|
||||
} else if (mode == "perft") {
|
||||
perft();
|
||||
return 0;
|
||||
} else {
|
||||
std::cerr << "Invalid mode selected!\n";
|
||||
print_usage();
|
||||
return 1;
|
||||
}
|
||||
|
||||
controller->start();
|
||||
delete controller;
|
||||
return 0;
|
||||
}
|
62
src/model/ais/ai.cpp
Normal file
@ -0,0 +1,62 @@
|
||||
#include "ai.hpp"
|
||||
|
||||
#include <condition_variable>
|
||||
#include <ostream>
|
||||
#include <thread>
|
||||
|
||||
static long int position_counter = 0;
|
||||
|
||||
Move ai::AI::search(const Board& b) {
|
||||
position_counter = 0;
|
||||
Move result;
|
||||
|
||||
std::condition_variable cv;
|
||||
std::mutex cv_mutex;
|
||||
double elapsed;
|
||||
stop_computation = false;
|
||||
|
||||
|
||||
// Start computation in a separate thread
|
||||
std::thread computation_thread([&]() {
|
||||
auto start = std::chrono::steady_clock::now();
|
||||
result = _search(b);
|
||||
auto end = std::chrono::steady_clock::now();
|
||||
elapsed =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
|
||||
.count();
|
||||
|
||||
// Notify the timer thread that computation is done
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(cv_mutex);
|
||||
stop_computation = true;
|
||||
cv.notify_one();
|
||||
}
|
||||
});
|
||||
|
||||
// Start a timer thread to stop computation after given time
|
||||
std::thread timer_thread([&]() {
|
||||
std::unique_lock<std::mutex> lock(cv_mutex);
|
||||
if (!cv.wait_for(lock, thinking_time, [&] {
|
||||
return stop_computation.load();
|
||||
})) {
|
||||
// Timeout reached; set stop flag
|
||||
stop_computation = true;
|
||||
}
|
||||
});
|
||||
|
||||
// Wait for computation thread to finish
|
||||
computation_thread.join();
|
||||
|
||||
// Ensure timer thread is also stopped
|
||||
timer_thread.join();
|
||||
|
||||
std::cout << "Took " << elapsed << " ms, " << "Looked at "
|
||||
<< position_counter << " positions" << std::endl;
|
||||
return result;
|
||||
}
|
||||
|
||||
int ai::AI::eval(const Board& b) {
|
||||
int ret = _eval(b);
|
||||
position_counter++;
|
||||
return ret;
|
||||
}
|
104
src/model/ais/ai.hpp
Normal file
@ -0,0 +1,104 @@
|
||||
#pragma once
|
||||
|
||||
#include "../board/board.hpp"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
|
||||
namespace ai {
|
||||
class AI {
|
||||
protected:
|
||||
bool am_white;
|
||||
std::chrono::milliseconds thinking_time;
|
||||
virtual Move _search(const Board&) = 0;
|
||||
|
||||
public:
|
||||
AI(bool am_white, std::chrono::milliseconds tt)
|
||||
: am_white(am_white),
|
||||
thinking_time(tt) {}
|
||||
|
||||
std::atomic<bool> stop_computation = false;
|
||||
|
||||
Move search(const Board& b);
|
||||
int eval(const Board&);
|
||||
|
||||
virtual int _eval(const Board&) = 0;
|
||||
};
|
||||
|
||||
struct v0_random : public AI {
|
||||
v0_random(bool w, std::chrono::milliseconds tt): AI(w, tt) {}
|
||||
|
||||
Move _search(const Board&) override;
|
||||
|
||||
int _eval(const Board&) override {
|
||||
return 0;
|
||||
};
|
||||
};
|
||||
|
||||
class v1_pure_minimax : public AI { // looks two moves ahead
|
||||
int _search(const Board&, int);
|
||||
|
||||
public:
|
||||
v1_pure_minimax(bool w, std::chrono::milliseconds tt): AI(w, tt) {}
|
||||
|
||||
Move _search(const Board&) override;
|
||||
int _eval(const Board&) override;
|
||||
};
|
||||
|
||||
class v2_alpha_beta : public AI {
|
||||
// looks two moves ahead, with alpha-beta pruning (no move ordering)
|
||||
virtual int _search(const Board&, int, int, int);
|
||||
|
||||
public:
|
||||
v2_alpha_beta(bool w, std::chrono::milliseconds tt): AI(w, tt) {}
|
||||
|
||||
virtual Move _search(const Board&) override;
|
||||
virtual int _eval(const Board&) override;
|
||||
};
|
||||
|
||||
class v3_AB_ordering : public AI {
|
||||
// looks two moves ahead, with alpha-beta pruning, with move ordering
|
||||
virtual int _ab_search(const Board&, int, int, int);
|
||||
|
||||
public:
|
||||
v3_AB_ordering(bool w, std::chrono::milliseconds tt): AI(w, tt) {}
|
||||
|
||||
virtual Move _search(const Board&) override;
|
||||
virtual int _eval(const Board&) override;
|
||||
};
|
||||
|
||||
class v4_search_captures : public v3_AB_ordering {
|
||||
protected:
|
||||
// same as v3, but looking at only at captures when leaf is reached,
|
||||
// until no captures are left
|
||||
virtual int _ab_search(const Board&, int, int, int) override;
|
||||
virtual int _search_captures(const Board&, int, int);
|
||||
|
||||
public:
|
||||
v4_search_captures(bool w, std::chrono::milliseconds tt)
|
||||
: v3_AB_ordering(w, tt) {}
|
||||
};
|
||||
|
||||
class v5_better_endgame : public v4_search_captures {
|
||||
// same as v4, but with a better evaluation function, that forces the
|
||||
// king towards the corner of the board for endgames
|
||||
|
||||
public:
|
||||
v5_better_endgame(bool w, std::chrono::milliseconds tt)
|
||||
: v4_search_captures(w, tt) {}
|
||||
|
||||
virtual int _eval(const Board&) override;
|
||||
};
|
||||
|
||||
class v6_iterative_deepening : public v5_better_endgame {
|
||||
// same as v5, but instead of just looking 2 moves ahead, it does
|
||||
// iterative depening until and keeps on searching until the thinking
|
||||
// time runs out
|
||||
|
||||
public:
|
||||
v6_iterative_deepening(bool w, std::chrono::milliseconds tt)
|
||||
: v5_better_endgame(w, tt) {}
|
||||
|
||||
virtual Move _search(const Board&) override;
|
||||
};
|
||||
} // namespace ai
|
13
src/model/ais/v0_random.cpp
Normal file
@ -0,0 +1,13 @@
|
||||
#include "ai.hpp"
|
||||
|
||||
#include <thread>
|
||||
|
||||
Move ai::v0_random::_search(const Board& b) {
|
||||
std::vector<Move> moves = b.all_legal_moves();
|
||||
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(thinking_time)
|
||||
); // Simulate work
|
||||
|
||||
return moves[rand() % moves.size()];
|
||||
}
|
86
src/model/ais/v1_pure_minimax.cpp
Normal file
@ -0,0 +1,86 @@
|
||||
#include "../pieces/piece.hpp"
|
||||
#include "../utils/threadpool.hpp"
|
||||
#include "../utils/utils.hpp"
|
||||
#include "ai.hpp"
|
||||
|
||||
#include <map>
|
||||
|
||||
#define MULTITHREADED 1
|
||||
|
||||
Move ai::v1_pure_minimax::_search(const Board& b) {
|
||||
std::vector<Move> moves = b.all_legal_moves();
|
||||
|
||||
Move best_move;
|
||||
int best_eval = -INFINITY;
|
||||
#if MULTITHREADED
|
||||
ThreadPool pool(std::thread::hardware_concurrency());
|
||||
|
||||
std::cout << "Have to look at " << moves.size() << " moves" << std::endl;
|
||||
|
||||
std::map<Move, std::future<int>> futures;
|
||||
for (const Move& move : moves) {
|
||||
Board tmp_board = b.make_move(move);
|
||||
futures.insert({move, pool.enqueue([&, tmp_board]() {
|
||||
return _search(tmp_board, 3);
|
||||
})});
|
||||
}
|
||||
|
||||
int counter = 0;
|
||||
for (auto& [move, future] : futures) {
|
||||
int eval = future.get();
|
||||
counter++;
|
||||
if (!am_white)
|
||||
eval *= -1;
|
||||
if (eval > best_eval) {
|
||||
best_eval = eval;
|
||||
best_move = move;
|
||||
}
|
||||
}
|
||||
#else
|
||||
for (const Move& move : moves) {
|
||||
Board tmp_board = b.make_move(move);
|
||||
std::cout << "Looking at " << move << std::endl;
|
||||
int eval = _search(tmp_board, 3);
|
||||
if (!am_white)
|
||||
eval *= -1;
|
||||
if (eval > best_eval) {
|
||||
best_eval = eval;
|
||||
best_move = move;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return best_move;
|
||||
}
|
||||
|
||||
int ai::v1_pure_minimax::_search(const Board& b, int depth) {
|
||||
if (depth == 0 || stop_computation)
|
||||
return eval(b);
|
||||
|
||||
if (b.no_legal_moves()) {
|
||||
if (b.is_check())
|
||||
return -INFINITY;
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::vector<Move> moves = b.all_legal_moves();
|
||||
|
||||
int best_evaluation = -INFINITY;
|
||||
Move best_move;
|
||||
for (const Move& move : moves) {
|
||||
Board tmp_board = b.make_move(move);
|
||||
int tmp_eval = -_search(tmp_board, depth - 1);
|
||||
best_evaluation = std::max(best_evaluation, tmp_eval);
|
||||
}
|
||||
return best_evaluation;
|
||||
}
|
||||
|
||||
int ai::v1_pure_minimax::_eval(const Board& b) {
|
||||
int white_eval = count_material(b, Colour::White);
|
||||
int black_eval = count_material(b, Colour::Black);
|
||||
|
||||
int evaluation = white_eval - black_eval;
|
||||
|
||||
int perspective = b.white_to_play ? 1 : -1;
|
||||
|
||||
return perspective * evaluation;
|
||||
}
|
86
src/model/ais/v2_alpha_beta.cpp
Normal file
@ -0,0 +1,86 @@
|
||||
#include "../pieces/piece.hpp"
|
||||
#include "../utils/threadpool.hpp"
|
||||
#include "../utils/utils.hpp"
|
||||
#include "ai.hpp"
|
||||
|
||||
#include <map>
|
||||
|
||||
#define MULTITHREADED 1
|
||||
|
||||
Move ai::v2_alpha_beta::_search(const Board& b) {
|
||||
std::vector<Move> moves = b.all_legal_moves();
|
||||
|
||||
Move best_move;
|
||||
int best_eval = -INFINITY;
|
||||
#if MULTITHREADED
|
||||
ThreadPool pool(std::thread::hardware_concurrency());
|
||||
|
||||
std::cout << "Have to look at " << moves.size() << " moves" << std::endl;
|
||||
|
||||
std::map<Move, std::future<int>> futures;
|
||||
for (const Move& move : moves) {
|
||||
Board tmp_board = b.make_move(move);
|
||||
futures.insert({move, pool.enqueue([&, tmp_board]() {
|
||||
return _search(tmp_board, 3, -INFINITY, INFINITY);
|
||||
})});
|
||||
}
|
||||
|
||||
int counter = 0;
|
||||
for (auto& [move, future] : futures) {
|
||||
int eval = future.get();
|
||||
counter++;
|
||||
if (!am_white)
|
||||
eval *= -1;
|
||||
if (eval > best_eval) {
|
||||
best_eval = eval;
|
||||
best_move = move;
|
||||
}
|
||||
}
|
||||
#else
|
||||
for (const Move& move : moves) {
|
||||
Board tmp_board = b.make_move(move);
|
||||
std::cout << "Looking at " << move << std::endl;
|
||||
int eval = _search(tmp_board, 3);
|
||||
if (!am_white)
|
||||
eval *= -1;
|
||||
if (eval > best_eval) {
|
||||
best_eval = eval;
|
||||
best_move = move;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return best_move;
|
||||
}
|
||||
|
||||
int ai::v2_alpha_beta::_search(const Board& b, int depth, int alpha, int beta) {
|
||||
if (depth == 0 || stop_computation)
|
||||
return eval(b);
|
||||
|
||||
if (b.no_legal_moves()) {
|
||||
if (b.is_check())
|
||||
return -INFINITY;
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::vector<Move> moves = b.all_legal_moves();
|
||||
|
||||
for (const Move& move : moves) {
|
||||
Board tmp_board = b.make_move(move);
|
||||
int tmp_eval = -_search(tmp_board, depth - 1, -beta, -alpha);
|
||||
if (tmp_eval >= beta)
|
||||
return beta;
|
||||
alpha = std::max(alpha, tmp_eval);
|
||||
}
|
||||
return alpha;
|
||||
}
|
||||
|
||||
int ai::v2_alpha_beta::_eval(const Board& b) {
|
||||
int white_eval = count_material(b, Colour::White);
|
||||
int black_eval = count_material(b, Colour::Black);
|
||||
|
||||
int evaluation = white_eval - black_eval;
|
||||
|
||||
int perspective = b.white_to_play ? 1 : -1;
|
||||
|
||||
return perspective * evaluation;
|
||||
}
|
104
src/model/ais/v3_AB_ordering.cpp
Normal file
@ -0,0 +1,104 @@
|
||||
#include "../pieces/piece.hpp"
|
||||
#include "../utils/threadpool.hpp"
|
||||
#include "../utils/utils.hpp"
|
||||
#include "ai.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
|
||||
#define MULTITHREADED 1
|
||||
|
||||
Move ai::v3_AB_ordering::_search(const Board& b) {
|
||||
std::vector<Move> moves = b.all_legal_moves();
|
||||
std::sort(moves.begin(), moves.end(), [&](Move& m1, Move& m2) {
|
||||
int score = m1.score_guess(b) - m2.score_guess(b);
|
||||
if (!am_white)
|
||||
score *= -1;
|
||||
return score < 0;
|
||||
});
|
||||
|
||||
Move best_move;
|
||||
int best_eval = -INFINITY;
|
||||
#if MULTITHREADED
|
||||
ThreadPool pool(std::thread::hardware_concurrency());
|
||||
|
||||
std::cout << "Have to look at " << moves.size() << " moves" << std::endl;
|
||||
|
||||
std::map<Move, std::future<int>> futures;
|
||||
for (const Move& move : moves) {
|
||||
Board tmp_board = b.make_move(move);
|
||||
futures.insert(
|
||||
{move, pool.enqueue([&, tmp_board]() {
|
||||
return _ab_search(tmp_board, 3, -INFINITY, INFINITY);
|
||||
})}
|
||||
);
|
||||
}
|
||||
|
||||
int counter = 0;
|
||||
for (auto& [move, future] : futures) {
|
||||
int eval = future.get();
|
||||
counter++;
|
||||
if (!am_white)
|
||||
eval *= -1;
|
||||
if (eval > best_eval) {
|
||||
best_eval = eval;
|
||||
best_move = move;
|
||||
}
|
||||
}
|
||||
#else
|
||||
for (const Move& move : moves) {
|
||||
Board tmp_board = b.make_move(move);
|
||||
std::cout << "Looking at " << move << std::endl;
|
||||
int eval = _search(tmp_board, 3);
|
||||
if (!am_white)
|
||||
eval *= -1;
|
||||
if (eval > best_eval) {
|
||||
best_eval = eval;
|
||||
best_move = move;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return best_move;
|
||||
}
|
||||
|
||||
int ai::v3_AB_ordering::_ab_search(
|
||||
const Board& b, int depth, int alpha, int beta
|
||||
) {
|
||||
if (depth == 0 || stop_computation)
|
||||
return eval(b);
|
||||
|
||||
if (b.no_legal_moves()) {
|
||||
if (b.is_check())
|
||||
return -INFINITY;
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::vector<Move> moves = b.all_legal_moves();
|
||||
std::sort(moves.begin(), moves.end(), [&](Move& m1, Move& m2) {
|
||||
int score = m1.score_guess(b) - m2.score_guess(b);
|
||||
if (!am_white)
|
||||
score *= -1;
|
||||
return score < 0;
|
||||
});
|
||||
|
||||
Move best_move;
|
||||
for (const Move& move : moves) {
|
||||
Board tmp_board = b.make_move(move);
|
||||
int tmp_eval = -_ab_search(tmp_board, depth - 1, -beta, -alpha);
|
||||
if (tmp_eval >= beta)
|
||||
return beta;
|
||||
alpha = std::max(alpha, tmp_eval);
|
||||
}
|
||||
return alpha;
|
||||
}
|
||||
|
||||
int ai::v3_AB_ordering::_eval(const Board& b) {
|
||||
int white_eval = count_material(b, Colour::White);
|
||||
int black_eval = count_material(b, Colour::Black);
|
||||
|
||||
int evaluation = white_eval - black_eval;
|
||||
|
||||
int perspective = b.white_to_play ? 1 : -1;
|
||||
|
||||
return perspective * evaluation;
|
||||
}
|
58
src/model/ais/v4_search_captures.cpp
Normal file
@ -0,0 +1,58 @@
|
||||
#include "../pieces/piece.hpp"
|
||||
#include "../utils/utils.hpp"
|
||||
#include "ai.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#define MULTITHREADED 1
|
||||
|
||||
int ai::v4_search_captures::_ab_search(
|
||||
const Board& b, int depth, int alpha, int beta
|
||||
) {
|
||||
if (depth == 0 || stop_computation)
|
||||
return _search_captures(b, alpha, beta);
|
||||
|
||||
if (b.no_legal_moves()) {
|
||||
if (b.is_check())
|
||||
return -INFINITY;
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::vector<Move> moves = b.all_legal_moves();
|
||||
std::sort(moves.begin(), moves.end(), [&](Move& m1, Move& m2) {
|
||||
return m1.score_guess(b) > m2.score_guess(b);
|
||||
});
|
||||
|
||||
Move best_move;
|
||||
for (const Move& move : moves) {
|
||||
Board tmp_board = b.make_move(move);
|
||||
int tmp_eval = -_ab_search(tmp_board, depth - 1, -beta, -alpha);
|
||||
if (tmp_eval >= beta)
|
||||
return beta;
|
||||
alpha = std::max(alpha, tmp_eval);
|
||||
}
|
||||
return alpha;
|
||||
}
|
||||
|
||||
int ai::v4_search_captures::_search_captures(
|
||||
const Board& b, int alpha, int beta
|
||||
) {
|
||||
int evaluation = eval(b);
|
||||
if (evaluation >= beta)
|
||||
return beta;
|
||||
alpha = std::max(evaluation, alpha);
|
||||
|
||||
std::vector<Move> moves = b.all_capturing_moves();
|
||||
std::sort(moves.begin(), moves.end(), [&](Move& m1, Move& m2) {
|
||||
return m1.score_guess(b) > m2.score_guess(b);
|
||||
});
|
||||
|
||||
for (const Move& move : moves) {
|
||||
Board tmp_board = b.make_move(move);
|
||||
int tmp_eval = -_search_captures(tmp_board, -beta, -alpha);
|
||||
if (tmp_eval >= beta)
|
||||
return beta;
|
||||
alpha = std::max(alpha, tmp_eval);
|
||||
}
|
||||
return alpha;
|
||||
}
|
52
src/model/ais/v5_better_endgames.cpp
Normal file
@ -0,0 +1,52 @@
|
||||
#include "../pieces/piece.hpp"
|
||||
#include "../utils/utils.hpp"
|
||||
#include "ai.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
static int force_king_to_corner(
|
||||
int8_t attacking_king, int8_t defending_king, float endgame_weight
|
||||
) {
|
||||
int eval = 0;
|
||||
Coords def_xy = Coords::from_index(defending_king);
|
||||
|
||||
Coords def_dist_to_center{
|
||||
std::max(3 - def_xy.x, def_xy.x - 4),
|
||||
std::max(3 - def_xy.y, def_xy.y - 4)
|
||||
};
|
||||
eval += def_dist_to_center.x + def_dist_to_center.y;
|
||||
|
||||
// make attacking king go closer to defending king to cut off escape routes
|
||||
Coords attack_xy = Coords::from_index(attacking_king);
|
||||
Coords dist_between_kings{
|
||||
std::abs(attack_xy.x - def_xy.x),
|
||||
std::abs(attack_xy.y - def_xy.y)
|
||||
};
|
||||
int distance = dist_between_kings.x + dist_between_kings.y;
|
||||
eval += 14 - distance;
|
||||
|
||||
return (int) (eval * 10 * endgame_weight);
|
||||
}
|
||||
|
||||
static float endgame_phase_weight(int material_count_no_pawns) {
|
||||
static int endgame_material_start =
|
||||
RookValue * 2 + BishopValue + KnightValue;
|
||||
|
||||
float multiplier = 1.f / endgame_material_start;
|
||||
return 1.f - std::min(1.f, material_count_no_pawns * multiplier);
|
||||
}
|
||||
|
||||
int ai::v5_better_endgame::_eval(const Board& b) {
|
||||
int old_eval = v4_search_captures::_eval(b);
|
||||
Colour attacking_colour = b.white_to_play ? White : Black;
|
||||
Colour defending_colour = b.white_to_play ? Black : White;
|
||||
return old_eval
|
||||
+ force_king_to_corner(
|
||||
b.get_king_of(attacking_colour),
|
||||
b.get_king_of(defending_colour),
|
||||
endgame_phase_weight(
|
||||
count_material(b, attacking_colour, false)
|
||||
+ count_material(b, defending_colour, false)
|
||||
)
|
||||
);
|
||||
}
|
43
src/model/ais/v6_iterative_deepening.cpp
Normal file
@ -0,0 +1,43 @@
|
||||
#include "../pieces/piece.hpp"
|
||||
#include "../utils/threadpool.hpp"
|
||||
#include "../utils/utils.hpp"
|
||||
#include "ai.hpp"
|
||||
|
||||
#include <map>
|
||||
|
||||
Move ai::v6_iterative_deepening::_search(const Board& b) {
|
||||
ThreadPool pool(std::thread::hardware_concurrency());
|
||||
std::vector<Move> moves = b.all_legal_moves();
|
||||
|
||||
Move best_move;
|
||||
int best_eval = -INFINITY;
|
||||
|
||||
std::map<Move, std::future<int>> futures;
|
||||
int depth;
|
||||
for (depth = 1; !stop_computation; depth++) {
|
||||
for (const Move& move : moves) {
|
||||
Board tmp_board = b.make_move(move);
|
||||
futures.insert(
|
||||
{move, pool.enqueue([&, tmp_board]() {
|
||||
return _ab_search(tmp_board, depth, -INFINITY, INFINITY);
|
||||
})}
|
||||
);
|
||||
}
|
||||
|
||||
int counter = 0;
|
||||
for (auto& [move, future] : futures) {
|
||||
int eval = future.get();
|
||||
counter++;
|
||||
if (!am_white)
|
||||
eval *= -1;
|
||||
if (eval > best_eval) {
|
||||
best_eval = eval;
|
||||
best_move = move;
|
||||
}
|
||||
}
|
||||
futures.clear();
|
||||
}
|
||||
|
||||
std::cout << "Went up until depth: " << depth << std::endl;
|
||||
return best_move;
|
||||
}
|
@ -5,9 +5,11 @@
|
||||
#include "../utils/move.hpp"
|
||||
#include "../utils/utils.hpp"
|
||||
|
||||
#include <SFML/Graphics/BlendMode.hpp>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
Board Board::setup_fen_position(std::string fen) {
|
||||
@ -92,6 +94,8 @@ Board Board::setup_fen_position(std::string fen) {
|
||||
index = fen.find(' ', index) + 1;
|
||||
board.n_full_moves = std::stoi(fen.substr(index));
|
||||
|
||||
board.check = board._is_check_for(board.white_to_play ? White : Black);
|
||||
board.nlm = board._no_legal_moves_for(board.white_to_play ? White : Black);
|
||||
|
||||
return board;
|
||||
}
|
||||
@ -111,7 +115,7 @@ std::string Board::to_fen() const {
|
||||
for (int rank = 7; rank >= 0; rank--) {
|
||||
int empty_cell_counter = 0;
|
||||
for (int file = 0; file < 8; file++) {
|
||||
if (squares[rank * 8 + file] == Piece::None) {
|
||||
if (piece_at({file, rank}) == Piece::None) {
|
||||
empty_cell_counter++;
|
||||
continue;
|
||||
}
|
||||
@ -169,7 +173,14 @@ std::string Board::to_fen() const {
|
||||
return ret;
|
||||
}
|
||||
|
||||
Board Board::make_move(Move move) const {
|
||||
Board Board::skip_turn() const {
|
||||
Board ret = *this;
|
||||
ret.white_to_play = !ret.white_to_play;
|
||||
ret.check = ret._is_check_for(ret.white_to_play ? White : Black);
|
||||
return ret;
|
||||
}
|
||||
|
||||
Board Board::make_move(Move move, bool recurse_call) const {
|
||||
Board ret;
|
||||
std::copy(
|
||||
std::begin(this->squares),
|
||||
@ -266,24 +277,64 @@ Board Board::make_move(Move move) const {
|
||||
}
|
||||
}
|
||||
|
||||
ret.n_half_moves = n_half_moves + 1;
|
||||
if (is_capturing || piece_at(move.source_square) == Piece::Pawn)
|
||||
ret.n_half_moves = 0;
|
||||
if (!white_to_play)
|
||||
ret.n_full_moves = n_full_moves + 1;
|
||||
|
||||
if (ret.n_half_moves > 150) {
|
||||
std::cerr << "too many recursions" << std::endl;
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (recurse_call) {
|
||||
ret.check = ret._is_check_for(ret.white_to_play ? White : Black);
|
||||
ret.nlm = ret._no_legal_moves_for(ret.white_to_play ? White : Black);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool Board::insufficient_material_for(Colour current_colour) const {
|
||||
int n_bishop = 0, n_knight = 0;
|
||||
|
||||
for (int i = 0; i < 64; i++) {
|
||||
Colour colour = colour_at(i);
|
||||
if (colour != current_colour)
|
||||
continue;
|
||||
|
||||
Piece piece = piece_at(i);
|
||||
if (piece == Piece::Pawn || piece == Piece::Queen
|
||||
|| piece == Piece::Rook)
|
||||
return false;
|
||||
|
||||
if (piece == Piece::Bishop)
|
||||
n_bishop++;
|
||||
if (piece == Piece::Knigt && colour == Colour::White)
|
||||
n_knight++;
|
||||
}
|
||||
return (n_bishop == 0 && n_knight == 0) || (n_bishop == 1 && n_knight == 0)
|
||||
|| (n_bishop == 0 && n_knight == 1);
|
||||
}
|
||||
|
||||
int8_t Board::get_king_of(int8_t colour) const {
|
||||
for (int i = 0; i < 64; i++)
|
||||
if (squares[i] == (colour | Piece::King))
|
||||
return i;
|
||||
throw std::domain_error(
|
||||
"Apparently there no kings of the such color in this board"
|
||||
);
|
||||
std::stringstream ss;
|
||||
ss << "Apparently there no kings of the such color in this board: "
|
||||
<< std::endl;
|
||||
ss << to_fen();
|
||||
throw std::domain_error(ss.str());
|
||||
}
|
||||
|
||||
bool Board::is_check_for(int8_t colour) const {
|
||||
bool Board::_is_check_for(Colour colour) const {
|
||||
int8_t king_idx = this->get_king_of(colour);
|
||||
for (int i = 0; i < 64; i++) {
|
||||
std::vector<Move> all_moves;
|
||||
all_moves.reserve(50);
|
||||
for (int8_t i = 0; i < 64; i++) {
|
||||
if (this->squares[i] == Piece::None || colour_at(i) == colour)
|
||||
continue;
|
||||
std::vector<int8_t> targets;
|
||||
if (piece_at(i) == King) {
|
||||
// special case for the king, because it creates infinite recursion
|
||||
// (since he looks if he's walking into a check)
|
||||
@ -292,7 +343,7 @@ bool Board::is_check_for(int8_t colour) const {
|
||||
for (int dy = -1; dy <= 1; dy++) {
|
||||
Coords c{king_pos.x + dx, king_pos.y + dy};
|
||||
if (c.is_within_bounds())
|
||||
targets.push_back(c.to_index());
|
||||
all_moves.push_back(Move{i, c.to_index()});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@ -302,27 +353,51 @@ bool Board::is_check_for(int8_t colour) const {
|
||||
Coords::from_index(i),
|
||||
true
|
||||
);
|
||||
targets = to_target_square(moves);
|
||||
|
||||
all_moves.insert(all_moves.end(), moves.begin(), moves.end());
|
||||
}
|
||||
if (std::find(targets.begin(), targets.end(), king_idx)
|
||||
!= targets.end())
|
||||
|
||||
for (const Move& move : all_moves)
|
||||
if (move.target_square == king_idx)
|
||||
return true;
|
||||
all_moves.clear();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool Board::no_legal_moves_for(int8_t colour) const {
|
||||
bool Board::_no_legal_moves_for(Colour colour) const {
|
||||
for (int i = 0; i < 64; i++) {
|
||||
if (colour_at(i) == colour) {
|
||||
std::vector<Move> moves =
|
||||
legal_moves(squares[i], *this, Coords::from_index(i));
|
||||
if (squares[i] == Piece::None || colour_at(i) != colour)
|
||||
continue;
|
||||
std::vector<Move> moves;
|
||||
moves = legal_moves(squares[i], *this, Coords::from_index(i));
|
||||
if (moves.size() > 0)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Board::no_legal_moves() const {
|
||||
return nlm;
|
||||
}
|
||||
|
||||
bool Board::is_check() const {
|
||||
return check;
|
||||
}
|
||||
|
||||
bool Board::is_checkmate() const {
|
||||
return check && nlm;
|
||||
}
|
||||
|
||||
bool Board::is_stalemate() const {
|
||||
return !check && nlm;
|
||||
}
|
||||
|
||||
bool Board::is_terminal() const {
|
||||
return n_half_moves == 100 || insufficient_material() || is_checkmate()
|
||||
|| is_stalemate();
|
||||
}
|
||||
|
||||
std::vector<Move> Board::all_legal_moves() const {
|
||||
std::vector<Move> ret;
|
||||
for (int i = 0; i < 64; i++) {
|
||||
@ -335,3 +410,28 @@ std::vector<Move> Board::all_legal_moves() const {
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
std::vector<Move> Board::all_capturing_moves() const {
|
||||
std::vector<Move> moves = all_legal_moves();
|
||||
std::vector<Move> ret;
|
||||
ret.reserve(moves.size());
|
||||
for (const Move& move : moves)
|
||||
if (piece_at(move.target_square) != Piece::None)
|
||||
ret.push_back(move);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
std::vector<int8_t> Board::opponent_pawn_attack_map() const {
|
||||
std::vector<int8_t> ret;
|
||||
for (int i = 0; i < 64; i++) {
|
||||
if (piece_at(i) == Piece::Pawn
|
||||
&& ((colour_at(i) == White && !white_to_play)
|
||||
|| (colour_at(i) == Black && white_to_play))) {
|
||||
std::vector<int8_t> attack_map =
|
||||
pawn_attack_map(*this, Coords::from_index(i));
|
||||
ret.insert(ret.end(), attack_map.begin(), attack_map.end());
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
@ -8,8 +8,9 @@
|
||||
|
||||
struct Board {
|
||||
private:
|
||||
int8_t get_king_of(int8_t) const;
|
||||
bool no_legal_moves_for(int8_t) const;
|
||||
bool _no_legal_moves_for(Colour) const;
|
||||
bool _is_check_for(Colour) const;
|
||||
bool nlm = false, check = false;
|
||||
|
||||
public:
|
||||
int8_t squares[64] = {Piece::None};
|
||||
@ -17,43 +18,48 @@ struct Board {
|
||||
int8_t w_castle_rights = CastleSide::NeitherSide;
|
||||
int8_t b_castle_rights = CastleSide::NeitherSide;
|
||||
int8_t en_passant_target = -1;
|
||||
uint8_t n_half_moves = 0;
|
||||
uint8_t n_full_moves = 0;
|
||||
int n_half_moves = 0;
|
||||
int n_full_moves = 0;
|
||||
|
||||
|
||||
static Board setup_fen_position(std::string fen);
|
||||
|
||||
Board make_move(Move) const;
|
||||
int8_t get_king_of(int8_t) const;
|
||||
Board skip_turn() const;
|
||||
Board make_move(Move, bool = true) const;
|
||||
std::string to_fen() const;
|
||||
bool is_check_for(int8_t) const;
|
||||
bool no_legal_moves() const;
|
||||
bool is_check() const;
|
||||
bool insufficient_material_for(Colour) const;
|
||||
|
||||
bool insufficient_material() const {
|
||||
return insufficient_material_for(White)
|
||||
&& insufficient_material_for(Black);
|
||||
};
|
||||
|
||||
std::vector<Move> all_legal_moves() const;
|
||||
std::vector<Move> all_capturing_moves() const;
|
||||
std::vector<int8_t> opponent_pawn_attack_map() const;
|
||||
|
||||
bool is_checkmate_for(int8_t colour) const {
|
||||
return is_check_for(colour) && no_legal_moves_for(colour);
|
||||
}
|
||||
bool is_checkmate() const;
|
||||
|
||||
bool is_stalemate_for(int8_t colour) const {
|
||||
return !is_check_for(colour) && no_legal_moves_for(colour);
|
||||
}
|
||||
bool is_stalemate() const;
|
||||
|
||||
bool is_terminal() const {
|
||||
return is_checkmate_for(White) || is_checkmate_for(Black)
|
||||
|| is_stalemate_for(White) || is_stalemate_for(Black);
|
||||
}
|
||||
bool is_terminal() const;
|
||||
|
||||
Piece piece_at(int8_t idx) const {
|
||||
inline Piece piece_at(int8_t idx) const {
|
||||
return (Piece) (squares[idx] & 0b00111);
|
||||
}
|
||||
|
||||
Piece piece_at(Coords xy) const {
|
||||
inline Piece piece_at(Coords xy) const {
|
||||
return piece_at(xy.to_index());
|
||||
}
|
||||
|
||||
Colour colour_at(int8_t idx) const {
|
||||
inline Colour colour_at(int8_t idx) const {
|
||||
return (Colour) (squares[idx] & 0b11000);
|
||||
}
|
||||
|
||||
Colour colour_at(Coords xy) const {
|
||||
inline Colour colour_at(Coords xy) const {
|
||||
return colour_at(xy.to_index());
|
||||
}
|
||||
};
|
@ -47,7 +47,7 @@ static std::map<std::string, std::map<int, int>> pos2expected{
|
||||
{3, 2812}, // 11
|
||||
{4, 43238}, // 157
|
||||
{5, 674624}, // 2199
|
||||
// {6, 11030083},
|
||||
{6, 11030083},
|
||||
},
|
||||
},
|
||||
|
||||
@ -59,7 +59,7 @@ static std::map<std::string, std::map<int, int>> pos2expected{
|
||||
{2, 264}, // 1
|
||||
{3, 9467}, // 69
|
||||
{4, 422333}, // 3085
|
||||
// {5, 15833292}, // 124452
|
||||
{5, 15833292}, // 124452
|
||||
},
|
||||
},
|
||||
|
||||
@ -71,7 +71,7 @@ static std::map<std::string, std::map<int, int>> pos2expected{
|
||||
{2, 264}, // 2
|
||||
{3, 9467}, // 104
|
||||
{4, 422333}, // 3742
|
||||
// {5, 15833292}, // 136784
|
||||
{5, 15833292}, // 136784
|
||||
},
|
||||
},
|
||||
|
||||
@ -82,7 +82,7 @@ static std::map<std::string, std::map<int, int>> pos2expected{
|
||||
{1, 44}, // 0
|
||||
{2, 1486}, // 12
|
||||
{3, 62379}, // 357
|
||||
// {4, 2103487}, // 13804
|
||||
{4, 2103487}, // 13804
|
||||
// {5, 89941194}, // 1230428
|
||||
},
|
||||
},
|
||||
@ -95,7 +95,7 @@ static std::map<std::string, std::map<int, int>> pos2expected{
|
||||
{1, 46}, // 0
|
||||
{2, 2079}, // 16
|
||||
{3, 89890}, // 602
|
||||
// {4, 3894594}, // 26612
|
||||
{4, 3894594}, // 26612
|
||||
// {5, 164075551}, // 1230428
|
||||
},
|
||||
},
|
||||
@ -141,6 +141,7 @@ int move_generation_test(
|
||||
} else {
|
||||
// Regular sequential execution
|
||||
for (const Move& move : moves) {
|
||||
// std::cout << "Looking at " << move << std::endl;
|
||||
Board tmp_board = b.make_move(move);
|
||||
int n = move_generation_test(tmp_board, depth - 1, max_depth, pool);
|
||||
if (depth == max_depth)
|
@ -10,8 +10,9 @@ static bool is_clear_king_side(const Board& b, const Coords xy) {
|
||||
return false;
|
||||
|
||||
std::optional<Move> move = move_for_position(b, xy, c);
|
||||
Board board_after_move = b.make_move(move.value());
|
||||
if (board_after_move.is_check_for(b.colour_at(xy)))
|
||||
Board board_after_move = b.make_move(move.value(), false);
|
||||
board_after_move = board_after_move.skip_turn();
|
||||
if (board_after_move.is_check())
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@ -24,8 +25,9 @@ static bool is_clear_queen_side(const Board& b, const Coords xy) {
|
||||
return false;
|
||||
|
||||
std::optional<Move> move = move_for_position(b, xy, c);
|
||||
Board board_after_move = b.make_move(move.value());
|
||||
if (dx < 3 && board_after_move.is_check_for(b.colour_at(xy)))
|
||||
Board board_after_move = b.make_move(move.value(), false);
|
||||
board_after_move = board_after_move.skip_turn();
|
||||
if (dx < 3 && board_after_move.is_check())
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@ -46,7 +48,8 @@ std::vector<Move> king_moves(const Board& b, const Coords xy) {
|
||||
}
|
||||
}
|
||||
|
||||
if (b.is_check_for(b.colour_at(xy)))
|
||||
|
||||
if (b.is_check())
|
||||
return keep_only_blocking(ret, b);
|
||||
|
||||
// -- Castles
|
@ -19,7 +19,7 @@ std::vector<Move> pawn_moves(const Board& b, const Coords xy) {
|
||||
ret.push_back(Move{
|
||||
xy.to_index(),
|
||||
left.to_index(),
|
||||
(int8_t) (my_colour | piece)
|
||||
(Piece) (my_colour | piece)
|
||||
});
|
||||
else
|
||||
ret.push_back(Move{xy.to_index(), left.to_index()});
|
||||
@ -39,7 +39,7 @@ std::vector<Move> pawn_moves(const Board& b, const Coords xy) {
|
||||
ret.push_back(Move{
|
||||
xy.to_index(),
|
||||
right.to_index(),
|
||||
(int8_t) (my_colour | piece)
|
||||
(Piece) (my_colour | piece)
|
||||
});
|
||||
else
|
||||
ret.push_back(Move{xy.to_index(), right.to_index()});
|
||||
@ -68,7 +68,7 @@ std::vector<Move> pawn_moves(const Board& b, const Coords xy) {
|
||||
ret.push_back(Move{
|
||||
xy.to_index(),
|
||||
new_xy.to_index(),
|
||||
.promoting_to = (int8_t) (my_colour | piece)
|
||||
(Piece) (my_colour | piece)
|
||||
});
|
||||
else
|
||||
ret.push_back(Move{
|
||||
@ -79,3 +79,24 @@ std::vector<Move> pawn_moves(const Board& b, const Coords xy) {
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
std::vector<int8_t> pawn_attack_map(const Board& b, Coords xy) {
|
||||
std::vector<int8_t> ret{};
|
||||
Colour my_colour = b.colour_at(xy);
|
||||
|
||||
// -- Capture to the left
|
||||
if (xy.x > 0) {
|
||||
int dy = my_colour == Colour::White ? 1 : -1;
|
||||
Coords left{xy.x - 1, xy.y + dy};
|
||||
ret.push_back(left.to_index());
|
||||
}
|
||||
|
||||
// -- Capture to the right
|
||||
if (xy.x < 7) {
|
||||
int dy = my_colour == Colour::White ? 1 : -1;
|
||||
Coords right{xy.x + 1, xy.y + dy};
|
||||
ret.push_back(right.to_index());
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
@ -9,11 +9,12 @@ keep_only_blocking(const std::vector<Move> candidates, const Board& board) {
|
||||
if (candidates.size() == 0)
|
||||
return {};
|
||||
|
||||
Colour my_colour = board.colour_at(candidates[0].source_square);
|
||||
std::vector<Move> ret;
|
||||
for (Move move : candidates) {
|
||||
Board board_after_move = board.make_move(move);
|
||||
if (!board_after_move.is_check_for(my_colour))
|
||||
Board board_after_move = board.make_move(move, false);
|
||||
board_after_move = board_after_move.skip_turn();
|
||||
|
||||
if (!board_after_move.is_check())
|
||||
ret.push_back(move);
|
||||
}
|
||||
return ret;
|
@ -50,7 +50,12 @@ inline const char* to_string(Piece c) {
|
||||
}
|
||||
}
|
||||
|
||||
inline std::ostream& operator<<(std::ostream& os, const int8_t& i) {
|
||||
inline std::ostream& operator<<(std::ostream& os, const Colour& i) {
|
||||
os << std::to_string(i);
|
||||
return os;
|
||||
}
|
||||
|
||||
inline std::ostream& operator<<(std::ostream& os, const Piece& i) {
|
||||
os << std::to_string(i);
|
||||
return os;
|
||||
}
|
||||
@ -64,6 +69,7 @@ std::vector<Move> keep_only_blocking(const std::vector<Move>, const Board&);
|
||||
std::optional<Move> move_for_position(const Board&, const Coords, const Coords);
|
||||
std::vector<Move> look_direction(const Board&, const Coords, int, int);
|
||||
|
||||
std::vector<int8_t> pawn_attack_map(const Board&, const Coords);
|
||||
std::vector<Move> pawn_moves(const Board&, const Coords);
|
||||
std::vector<Move> rook_moves(const Board&, const Coords);
|
||||
std::vector<Move> knight_moves(const Board&, const Coords);
|
54
src/model/utils/move.cpp
Normal file
@ -0,0 +1,54 @@
|
||||
#include "move.hpp"
|
||||
|
||||
#include "../board/board.hpp"
|
||||
#include "utils.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
int Move::score_guess(const Board& b) const {
|
||||
int ret = 0;
|
||||
|
||||
Piece me_piece = b.piece_at(source_square);
|
||||
Piece captured_piece = b.piece_at(target_square);
|
||||
|
||||
if (captured_piece != Piece::None)
|
||||
ret += 10 * piece_value(captured_piece) - piece_value(me_piece);
|
||||
|
||||
if (promoting_to != Piece::None)
|
||||
ret += piece_value(promoting_to);
|
||||
|
||||
std::vector<int8_t> pawn_attack_map = b.opponent_pawn_attack_map();
|
||||
if (std::find(pawn_attack_map.begin(), pawn_attack_map.end(), target_square)
|
||||
!= pawn_attack_map.end())
|
||||
ret -= me_piece;
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
Move Move::from_string(std::string move) {
|
||||
if (!(4 <= move.size() && move.size() <= 5))
|
||||
throw std::invalid_argument("Move must be 4 or 5 characters long");
|
||||
Move ret;
|
||||
ret.source_square = Coords::from_algebraic(move.substr(0, 2)).to_index();
|
||||
ret.target_square = Coords::from_algebraic(move.substr(2, 2)).to_index();
|
||||
if (move.size() == 5)
|
||||
switch (move[4]) {
|
||||
case 'n':
|
||||
ret.promoting_to = Knigt;
|
||||
break;
|
||||
case 'b':
|
||||
ret.promoting_to = Bishop;
|
||||
break;
|
||||
case 'r':
|
||||
ret.promoting_to = Rook;
|
||||
break;
|
||||
case 'q':
|
||||
ret.promoting_to = Queen;
|
||||
break;
|
||||
default:
|
||||
throw std::invalid_argument("Promotion piece must be one of 'nbrq'"
|
||||
);
|
||||
}
|
||||
ret.target_square = Coords::from_algebraic(move.substr(2, 2)).to_index();
|
||||
return ret;
|
||||
}
|
@ -11,7 +11,11 @@ struct Move {
|
||||
int8_t source_square;
|
||||
int8_t target_square;
|
||||
|
||||
int8_t promoting_to = Piece::None;
|
||||
Piece promoting_to = Piece::None;
|
||||
|
||||
int score_guess(const Board&) const;
|
||||
|
||||
static Move from_string(std::string);
|
||||
|
||||
std::string to_string() const {
|
||||
std::stringstream ss;
|
38
src/model/utils/utils.cpp
Normal file
@ -0,0 +1,38 @@
|
||||
#include "utils.hpp"
|
||||
|
||||
#include "../board/board.hpp"
|
||||
|
||||
std::vector<int8_t> to_target_square(std::vector<Move> moves) {
|
||||
std::vector<int8_t> ret;
|
||||
for (Move move : moves)
|
||||
ret.push_back(move.target_square);
|
||||
return ret;
|
||||
}
|
||||
|
||||
int piece_value(Piece p) {
|
||||
switch (p) {
|
||||
case Piece::Pawn:
|
||||
return PawnValue;
|
||||
case Piece::Knigt:
|
||||
return KnightValue;
|
||||
case Piece::Bishop:
|
||||
return BishopValue;
|
||||
case Piece::Rook:
|
||||
return RookValue;
|
||||
case Piece::Queen:
|
||||
return QueenValue;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int count_material(const Board& b, int8_t colour, bool count_pawns) {
|
||||
int ret = 0;
|
||||
for (int i = 0; i < 64; i++) {
|
||||
if (b.piece_at(i) == Pawn && !count_pawns)
|
||||
continue;
|
||||
if (b.colour_at(i) == colour)
|
||||
ret += piece_value(b.piece_at(i));
|
||||
}
|
||||
return ret;
|
||||
}
|
19
src/model/utils/utils.hpp
Normal file
@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include "move.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
|
||||
std::vector<int8_t> to_target_square(std::vector<Move>);
|
||||
int count_material(const Board&, int8_t, bool = true);
|
||||
int piece_value(Piece);
|
||||
|
||||
const int INFINITY = std::numeric_limits<int>::max();
|
||||
|
||||
const int PawnValue = 100;
|
||||
const int KnightValue = 300;
|
||||
const int BishopValue = 320;
|
||||
const int RookValue = 500;
|
||||
const int QueenValue = 900;
|
@ -134,6 +134,81 @@ void GUI::draw_pieces(const Board& board) {
|
||||
}
|
||||
}
|
||||
|
||||
int GUI::show_popup(
|
||||
const std::string& message, const std::vector<std::string>& options
|
||||
) {
|
||||
sf::RenderWindow popup(sf::VideoMode(300, 200), "Choice");
|
||||
sf::Font font;
|
||||
|
||||
if (!font.loadFromFile("res/arial.ttf")) {
|
||||
std::cerr << "Error: Could not load font!" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
|
||||
sf::Text text(message, font, 20);
|
||||
text.setPosition(20, 20);
|
||||
text.setFillColor(sf::Color::Black);
|
||||
|
||||
std::vector<sf::RectangleShape> buttonShapes;
|
||||
std::vector<sf::Text> buttonTexts;
|
||||
|
||||
for (size_t i = 0; i < options.size(); ++i) {
|
||||
sf::RectangleShape button(sf::Vector2f(200, 30));
|
||||
button.setPosition(50, 70 + i * 40);
|
||||
button.setFillColor(sf::Color(150, 150, 150));
|
||||
buttonShapes.push_back(button);
|
||||
|
||||
sf::Text buttonText(options[i], font, 18);
|
||||
buttonText.setPosition(60, 75 + i * 40);
|
||||
buttonText.setFillColor(sf::Color::Black);
|
||||
buttonTexts.push_back(buttonText);
|
||||
}
|
||||
|
||||
while (popup.isOpen()) {
|
||||
sf::Event event;
|
||||
while (popup.pollEvent(event)) {
|
||||
if (event.type == sf::Event::Closed)
|
||||
popup.close();
|
||||
else if (event.type == sf::Event::MouseButtonPressed) {
|
||||
for (size_t i = 0; i < buttonShapes.size(); ++i) {
|
||||
if (buttonShapes[i].getGlobalBounds().contains(
|
||||
event.mouseButton.x,
|
||||
event.mouseButton.y
|
||||
)) {
|
||||
popup.close();
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
popup.clear(sf::Color::White);
|
||||
popup.draw(text);
|
||||
for (size_t i = 0; i < buttonShapes.size(); ++i) {
|
||||
popup.draw(buttonShapes[i]);
|
||||
popup.draw(buttonTexts[i]);
|
||||
}
|
||||
popup.display();
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
Piece GUI::ask_about_promotion() {
|
||||
std::vector<std::string> options = {"Queen", "Rook", "Bishop", "Knight"};
|
||||
int idx = show_popup("Please choose a promotion for your pawn", options);
|
||||
switch (idx) {
|
||||
case 0:
|
||||
return Queen;
|
||||
case 1:
|
||||
return Rook;
|
||||
case 2:
|
||||
return Bishop;
|
||||
case 3:
|
||||
return Knigt;
|
||||
};
|
||||
return Piece::None;
|
||||
}
|
||||
|
||||
void GUI::show() {
|
||||
while (window.isOpen())
|
||||
handle_events();
|
@ -15,6 +15,7 @@ class GUI : public View {
|
||||
GUI();
|
||||
|
||||
void show() override;
|
||||
Piece ask_about_promotion();
|
||||
void update_board(const Board&, int8_t, std::vector<int8_t>) override;
|
||||
void notify_checkmate(Colour) override;
|
||||
void notify_stalemate(Colour) override;
|
||||
@ -27,6 +28,10 @@ class GUI : public View {
|
||||
sf::Color colours[2] = {sf::Color(0xB88762FF), sf::Color(0xEDD6B0FF)};
|
||||
sf::Color alt_colours[2] = {sf::Color(0xDCC34BFF), sf::Color(0xF6EB72FF)};
|
||||
|
||||
|
||||
int show_popup(
|
||||
const std::string& message, const std::vector<std::string>& options
|
||||
);
|
||||
void load_textures();
|
||||
void handle_events();
|
||||
void handle_click(int, int);
|
@ -9,4 +9,8 @@ class NoOpView : public View {
|
||||
void update_board(const Board&, int8_t, std::vector<int8_t>) override {};
|
||||
void notify_checkmate(Colour) override{};
|
||||
void notify_stalemate(Colour) override{};
|
||||
|
||||
Piece ask_about_promotion() override {
|
||||
return Queen;
|
||||
};
|
||||
};
|
@ -15,6 +15,7 @@ class View {
|
||||
}
|
||||
|
||||
virtual void show() = 0;
|
||||
virtual Piece ask_about_promotion() = 0;
|
||||
virtual void update_board(const Board&, int8_t, std::vector<int8_t>) = 0;
|
||||
virtual void notify_checkmate(Colour) = 0;
|
||||
virtual void notify_stalemate(Colour) = 0;
|
@ -1,4 +1,4 @@
|
||||
#include "../src/board.hpp"
|
||||
#include "../src/model/board/board.hpp"
|
||||
#include "lib.hpp"
|
||||
|
||||
int main() {
|