Compare commits
44 Commits
5c58c86fba
...
zig
| Author | SHA1 | Date | |
|---|---|---|---|
| 47dcfcfeb0 | |||
| 69f11f7220 | |||
| a7c9f4f472 | |||
| 775228d691 | |||
| c1eade9440 | |||
| 94b501fd17 | |||
| ded1566f53 | |||
| 1d41b76fa8 | |||
| 7cded275f2 | |||
| 6af6a16a77 | |||
| 10f81cf7f0 | |||
| 054cd41cf6 | |||
| 008abd6444 | |||
| d6fa809505 | |||
| eccd8efdba | |||
| ca1e62397c | |||
| 059f672c17 | |||
| f9dda928b2 | |||
| bb3bc4442a | |||
| 93e7ff61e0 | |||
| da8eb581e3 | |||
| f9cdd9a259 | |||
| 5a7b5f1642 | |||
| 34601f9c9d | |||
| 3a9b53d384 | |||
| 986e8c8334 | |||
| fc32b56a2f | |||
| 89e00df712 | |||
| 05a0b2b7f1 | |||
| e1fe8ee603 | |||
| eaaa0ca24d | |||
| c25de2cb55 | |||
| 9534803a60 | |||
| 5dd8f04286 | |||
| 9f06b9d86c | |||
| 76c69dbf18 | |||
| 49befc72b6 | |||
| bfe9335515 | |||
| 3aa41364b3 | |||
| 8624840700 | |||
| b2433993a6 | |||
| 33592762a7 | |||
| 1d7d15fb52 | |||
| 64b979b9ab |
13
.gitea/workflows/nix-check.yaml
Normal file
13
.gitea/workflows/nix-check.yaml
Normal file
@@ -0,0 +1,13 @@
|
||||
name: Verify build
|
||||
run-name: ${{ gitea.actor }} is building
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
verify_build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: cachix/install-nix-action@v30
|
||||
with:
|
||||
nix_path: nixpkgs=channel:nixos-25.05
|
||||
- run: nix-build
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1 +1,4 @@
|
||||
/a.out
|
||||
/.zig-cache/
|
||||
/zig-out/
|
||||
/result
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
# RatChess
|
||||
|
||||
A chess engine made for fun
|
||||
|
||||
## Branch
|
||||
Port to zig for fun and to learn zig
|
||||
|
||||
35
TODO.org
Normal file
35
TODO.org
Normal file
@@ -0,0 +1,35 @@
|
||||
* Rewrite[25%]
|
||||
- [ ] UciGo
|
||||
- [ ] move gen
|
||||
- [ ] pawn
|
||||
- [ ] knight
|
||||
- [ ] rook
|
||||
- [ ] bishop
|
||||
- [ ] king
|
||||
- [ ] queen
|
||||
- [ ] move eval
|
||||
- [X] uci interface
|
||||
- [-] uciPos
|
||||
- [ ] fengame
|
||||
- [ ] charToSet
|
||||
- [X] playmoves
|
||||
- [ ] types
|
||||
- [ ] game
|
||||
- [ ] move
|
||||
- [ ] sets
|
||||
* Misc [0%]
|
||||
- [ ] errors
|
||||
- [ ] Proper zig errors
|
||||
- [ ] Proper error handleing
|
||||
- [ ] Speed up
|
||||
- [ ] GPU move gen
|
||||
- [ ] GPU move eval
|
||||
- [ ] clean code
|
||||
- [ ] split code into smaller files
|
||||
- [ ] remove "//this is bad" comments for good code
|
||||
- [ ] more zig stiled controle flow
|
||||
- [ ] uci Config
|
||||
* Bugs
|
||||
** C move gen broken
|
||||
** C findBest slow
|
||||
** FenGame failes to set white to move
|
||||
29
build.zig
Normal file
29
build.zig
Normal file
@@ -0,0 +1,29 @@
|
||||
const std = @import("std");
|
||||
|
||||
pub fn build(b: *std.Build) void {
|
||||
const target = b.standardTargetOptions(.{});
|
||||
const optimize = b.standardOptimizeOption(.{});
|
||||
|
||||
const exe_mod = b.createModule(.{
|
||||
.root_source_file = b.path("src/main.zig"),
|
||||
.target = target,
|
||||
.optimize = optimize,
|
||||
});
|
||||
|
||||
const exe = b.addExecutable(.{ .name = "RatChess", .root_module = exe_mod });
|
||||
b.installArtifact(exe);
|
||||
|
||||
const run_cmd = b.addRunArtifact(exe);
|
||||
run_cmd.step.dependOn(b.getInstallStep());
|
||||
|
||||
if (b.args) |args| run_cmd.addArgs(args);
|
||||
|
||||
const run_step = b.step("run", "Run the app");
|
||||
run_step.dependOn(&run_cmd.step);
|
||||
|
||||
const exe_unit_tests = b.addTest(.{ .root_module = exe_mod });
|
||||
const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);
|
||||
|
||||
const test_step = b.step("test", "Run unit tests");
|
||||
test_step.dependOn(&run_exe_unit_tests.step);
|
||||
}
|
||||
86
build.zig.zon
Normal file
86
build.zig.zon
Normal file
@@ -0,0 +1,86 @@
|
||||
.{
|
||||
// This is the default name used by packages depending on this one. For
|
||||
// example, when a user runs `zig fetch --save <url>`, this field is used
|
||||
// as the key in the `dependencies` table. Although the user can choose a
|
||||
// different name, most users will stick with this provided value.
|
||||
//
|
||||
// It is redundant to include "zig" in this name because it is already
|
||||
// within the Zig package namespace.
|
||||
.name = .RatChess,
|
||||
|
||||
// This is a [Semantic Version](https://semver.org/).
|
||||
// In a future version of Zig it will be used for package deduplication.
|
||||
.version = "0.0.0",
|
||||
|
||||
// Together with name, this represents a globally unique package
|
||||
// identifier. This field is generated by the Zig toolchain when the
|
||||
// package is first created, and then *never changes*. This allows
|
||||
// unambiguous detection of one package being an updated version of
|
||||
// another.
|
||||
//
|
||||
// When forking a Zig project, this id should be regenerated (delete the
|
||||
// field and run `zig build`) if the upstream project is still maintained.
|
||||
// Otherwise, the fork is *hostile*, attempting to take control over the
|
||||
// original project's identity. Thus it is recommended to leave the comment
|
||||
// on the following line intact, so that it shows up in code reviews that
|
||||
// modify the field.
|
||||
.fingerprint = 0xad90dd593d9885b0, // Changing this has security and trust implications.
|
||||
|
||||
// Tracks the earliest Zig version that the package considers to be a
|
||||
// supported use case.
|
||||
.minimum_zig_version = "0.14.1",
|
||||
|
||||
// This field is optional.
|
||||
// Each dependency must either provide a `url` and `hash`, or a `path`.
|
||||
// `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
|
||||
// Once all dependencies are fetched, `zig build` no longer requires
|
||||
// internet connectivity.
|
||||
.dependencies = .{
|
||||
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
|
||||
//.example = .{
|
||||
// // When updating this field to a new URL, be sure to delete the corresponding
|
||||
// // `hash`, otherwise you are communicating that you expect to find the old hash at
|
||||
// // the new URL. If the contents of a URL change this will result in a hash mismatch
|
||||
// // which will prevent zig from using it.
|
||||
// .url = "https://example.com/foo.tar.gz",
|
||||
//
|
||||
// // This is computed from the file contents of the directory of files that is
|
||||
// // obtained after fetching `url` and applying the inclusion rules given by
|
||||
// // `paths`.
|
||||
// //
|
||||
// // This field is the source of truth; packages do not come from a `url`; they
|
||||
// // come from a `hash`. `url` is just one of many possible mirrors for how to
|
||||
// // obtain a package matching this `hash`.
|
||||
// //
|
||||
// // Uses the [multihash](https://multiformats.io/multihash/) format.
|
||||
// .hash = "...",
|
||||
//
|
||||
// // When this is provided, the package is found in a directory relative to the
|
||||
// // build root. In this case the package's hash is irrelevant and therefore not
|
||||
// // computed. This field and `url` are mutually exclusive.
|
||||
// .path = "foo",
|
||||
//
|
||||
// // When this is set to `true`, a package is declared to be lazily
|
||||
// // fetched. This makes the dependency only get fetched if it is
|
||||
// // actually used.
|
||||
// .lazy = false,
|
||||
//},
|
||||
},
|
||||
|
||||
// Specifies the set of files and directories that are included in this package.
|
||||
// Only files and directories listed here are included in the `hash` that
|
||||
// is computed for this package. Only files listed here will remain on disk
|
||||
// when using the zig package manager. As a rule of thumb, one should list
|
||||
// files required for compilation plus any license(s).
|
||||
// Paths are relative to the build root. Use the empty string (`""`) to refer to
|
||||
// the build root itself.
|
||||
// A directory listed here means that all files within, recursively, are included.
|
||||
.paths = .{
|
||||
"build.zig",
|
||||
"build.zig.zon",
|
||||
"src",
|
||||
// For example...
|
||||
//"LICENSE",
|
||||
//"README.md",
|
||||
},
|
||||
}
|
||||
33
default.nix
Normal file
33
default.nix
Normal file
@@ -0,0 +1,33 @@
|
||||
# default.nix
|
||||
{ pkgs ? import <nixpkgs> {} }:
|
||||
|
||||
pkgs.stdenv.mkDerivation {
|
||||
pname = "RatChess";
|
||||
version = "0.0.1";
|
||||
|
||||
src = ./.;
|
||||
|
||||
nativeBuildInputs = with pkgs; [
|
||||
zig
|
||||
zls
|
||||
];
|
||||
|
||||
buildInputs = with pkgs; [
|
||||
];
|
||||
|
||||
buildPhase = ''
|
||||
echo "Building project..."
|
||||
${pkgs.zig}/bin/zig build --global-cache-dir ./cache --release=fast
|
||||
'';
|
||||
|
||||
installPhase = ''
|
||||
mkdir $out
|
||||
cp -r zig-out/* $out/
|
||||
'';
|
||||
|
||||
checkPhase = ''
|
||||
echo "Testing project..."
|
||||
${pkgs.zig}/bin/zig build test --global-cache-dir ./cache
|
||||
'';
|
||||
doCheck = true;
|
||||
}
|
||||
168
main.c
168
main.c
@@ -1,168 +0,0 @@
|
||||
#include <assert.h>
|
||||
#include <ctype.h>
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define BUFF_SIZE 4096
|
||||
|
||||
typedef struct {
|
||||
long long pawns;
|
||||
long long knights;
|
||||
long long bishops;
|
||||
long long rooks;
|
||||
long long queen;
|
||||
long long king;
|
||||
} sets;
|
||||
|
||||
typedef struct {
|
||||
sets white;
|
||||
sets black;
|
||||
bool whiteToMove;
|
||||
} game;
|
||||
|
||||
game *fenGame(char *str);
|
||||
|
||||
void print_bitboard(long long bitboard) {
|
||||
for (int i = 63; i >= 0; i--) {
|
||||
// Check if the i-th bit is set
|
||||
if ((bitboard >> i) & 1) {
|
||||
printf("1 ");
|
||||
} else {
|
||||
printf("0 ");
|
||||
}
|
||||
// Print a newline every 8 bits (for rows)
|
||||
if (i % 8 == 0) {
|
||||
printf("\n");
|
||||
}
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
int main() {
|
||||
setbuf(stdin, NULL);
|
||||
setbuf(stdout, NULL);
|
||||
game *g = NULL;
|
||||
|
||||
char line[BUFF_SIZE];
|
||||
char *lineRest, *token;
|
||||
char ltz[] = "abcdefgh";
|
||||
int cnt = 0;
|
||||
while (1) {
|
||||
(void)fgets(line, sizeof(line), stdin);
|
||||
size_t len = strlen(line);
|
||||
if (len - 1)
|
||||
line[len - 1] = '\0';
|
||||
token = strtok_r(line, " ", &lineRest);
|
||||
if (!strcmp("uci", token)) {
|
||||
printf("id name RatChess 0.0\n");
|
||||
printf("id author rat<3\n");
|
||||
printf("uciok\n");
|
||||
} else if (!strcmp("quit", token)) {
|
||||
return 0;
|
||||
} else if (!strcmp("setoption", token)) {
|
||||
} else if (!strcmp("position", token)) {
|
||||
game *g;
|
||||
token = strtok_r(lineRest, " ", &lineRest);
|
||||
if (!strcmp("fen", token)) {
|
||||
g = fenGame(lineRest + 1);
|
||||
for (int i = 0; i < 6; i++)
|
||||
token = strtok_r(lineRest, " ", &lineRest);
|
||||
} else {
|
||||
g = fenGame("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
|
||||
}
|
||||
token = strtok_r(lineRest, " ", &lineRest);
|
||||
if (!strcmp("moves", token)) {
|
||||
// TODO
|
||||
}
|
||||
print_bitboard(g->white.pawns);
|
||||
print_bitboard(g->black.pawns);
|
||||
|
||||
} else if (!strcmp("ucinewgame", token)) {
|
||||
} else if (!strcmp("isready", token)) {
|
||||
printf("readyok\n");
|
||||
} else if (!strcmp("go", token)) {
|
||||
printf("bestmove %c2%c4\n", ltz[cnt], ltz[cnt]);
|
||||
cnt++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
game *fenGame(char *str) {
|
||||
int rank = 7;
|
||||
int file = 0;
|
||||
size_t pos = 0;
|
||||
game *g;
|
||||
g = malloc(sizeof(game));
|
||||
memset(g, 0, sizeof(game));
|
||||
|
||||
while (str[pos] != '\0' && str[pos] != ' ') {
|
||||
char current_char = *str;
|
||||
|
||||
if (isdigit(*str)) {
|
||||
int empty_squares = *str - '0';
|
||||
file += empty_squares;
|
||||
str++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (current_char == '/') {
|
||||
rank--;
|
||||
file = 0;
|
||||
str++;
|
||||
continue;
|
||||
}
|
||||
|
||||
long long bit = 1LL << (rank * 8 + file);
|
||||
switch (*str) {
|
||||
case 'P':
|
||||
g->white.pawns |= bit;
|
||||
break;
|
||||
case 'N':
|
||||
g->white.knights |= bit;
|
||||
break;
|
||||
case 'B':
|
||||
g->white.bishops |= bit;
|
||||
break;
|
||||
case 'R':
|
||||
g->white.rooks |= bit;
|
||||
break;
|
||||
case 'Q':
|
||||
g->white.queen |= bit;
|
||||
break;
|
||||
case 'K':
|
||||
g->white.king |= bit;
|
||||
break;
|
||||
case 'p':
|
||||
g->black.pawns |= bit;
|
||||
break;
|
||||
case 'n':
|
||||
g->black.knights |= bit;
|
||||
break;
|
||||
case 'b':
|
||||
g->black.bishops |= bit;
|
||||
break;
|
||||
case 'r':
|
||||
g->black.rooks |= bit;
|
||||
break;
|
||||
case 'q':
|
||||
g->black.queen |= bit;
|
||||
break;
|
||||
case 'k':
|
||||
g->black.king |= bit;
|
||||
break;
|
||||
default:
|
||||
fprintf(stderr,
|
||||
"Error: Unknown piece character in FEN: %c at position %zu\n",
|
||||
*str, pos);
|
||||
break;
|
||||
}
|
||||
file++;
|
||||
str++;
|
||||
}
|
||||
str++;
|
||||
g->whiteToMove = (*str == 'w') ? true : false;
|
||||
return g;
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
{pkgs ? import <nixpkgs> {}}:
|
||||
with pkgs;
|
||||
mkShell rec {
|
||||
packages = [gdb clang-tools];
|
||||
packages = [gdb zls uchess cutechess stockfish];
|
||||
nativeBuildInputs = [
|
||||
pkg-config
|
||||
gcc
|
||||
gnumake
|
||||
zig
|
||||
];
|
||||
buildInputs = [
|
||||
];
|
||||
|
||||
161
src/main.zig
Normal file
161
src/main.zig
Normal file
@@ -0,0 +1,161 @@
|
||||
const std = @import("std");
|
||||
const mov = @import("move.zig");
|
||||
const types = @import("types.zig");
|
||||
|
||||
pub fn main() !void {
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
defer _ = gpa.deinit();
|
||||
const alloc = gpa.allocator();
|
||||
const stdin = std.io.getStdIn();
|
||||
var reader = stdin.reader();
|
||||
|
||||
var game: *types.game = uciPos("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", alloc);
|
||||
defer alloc.destroy(game);
|
||||
while (true) {
|
||||
const line = try reader.readUntilDelimiterAlloc(alloc, '\n', std.math.maxInt(usize));
|
||||
defer alloc.free(line);
|
||||
switch (uci(line, game, alloc)) {
|
||||
.text => |value| {
|
||||
try std.io.getStdOut().writer().print("{s}", .{value});
|
||||
},
|
||||
.move => |value| {
|
||||
try std.io.getStdOut().writer().print("bestmove {s}\n", .{value});
|
||||
alloc.free(value);
|
||||
},
|
||||
.game => |value| {
|
||||
alloc.destroy(game);
|
||||
game = value;
|
||||
},
|
||||
.exit => {
|
||||
break;
|
||||
},
|
||||
.pass => {
|
||||
try std.io.getStdOut().writer().print("info bad input\n", .{});
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn uci(str: []const u8, game: *types.game, alloc: std.mem.Allocator) types.uciRet {
|
||||
const pos = std.mem.indexOfAny(u8, str, " \t\n\r") orelse str.len;
|
||||
const tok = str[0..pos];
|
||||
if (std.mem.eql(u8, tok, "uci")) return .{ .text = "id name RatChess 0.1\nid author rat<3\nuciok\n" };
|
||||
if (std.mem.eql(u8, tok, "isready")) return .{ .text = "readyok\n" };
|
||||
if (std.mem.eql(u8, tok, "go")) return .{ .move = uciGo(game, alloc) };
|
||||
if (std.mem.eql(u8, tok, "position")) return .{ .game = uciPos(str[(pos + 1)..], alloc) };
|
||||
if (std.mem.eql(u8, tok, "quit")) return .{ .exit = {} };
|
||||
return .{ .pass = {} };
|
||||
}
|
||||
|
||||
fn uciPos(str: []const u8, alloc: std.mem.Allocator) *types.game {
|
||||
const pos = std.mem.indexOfAny(u8, str, " \t\n\r") orelse str.len;
|
||||
const tok = str[0..pos];
|
||||
if (std.mem.eql(u8, tok, "fen")) return fenGame(str[pos..], alloc);
|
||||
if (std.mem.eql(u8, tok, "startpos")) {
|
||||
var game = fenGame("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", alloc);
|
||||
game = mov.playMoves(game, str[(pos)..]);
|
||||
return game;
|
||||
}
|
||||
return fenGame("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", alloc); //this should be an error
|
||||
}
|
||||
|
||||
fn fenGame(str: []const u8, alloc: std.mem.Allocator) *types.game {
|
||||
var pos: u8 = 63;
|
||||
var space: u8 = 0;
|
||||
var g = alloc.create(types.game) catch unreachable;
|
||||
g.* = std.mem.zeroes(types.game);
|
||||
for (str) |chr| {
|
||||
if (chr == ' ') {
|
||||
space += 1;
|
||||
continue;
|
||||
}
|
||||
if (space == 1) {
|
||||
if (chr == 'b') g.whiteToMove = false;
|
||||
if (chr == 'w') g.whiteToMove = true;
|
||||
//continue;
|
||||
break;
|
||||
}
|
||||
|
||||
if (std.ascii.isDigit(chr)) {
|
||||
pos += @truncate(chr - '0');
|
||||
continue;
|
||||
}
|
||||
if (chr == '/') continue;
|
||||
const set: *u64 = mov.charToSet(g, chr);
|
||||
const bit: u64 = @as(u64, 1) << @truncate(pos);
|
||||
set.* |= bit;
|
||||
pos -= 1;
|
||||
}
|
||||
return g;
|
||||
}
|
||||
|
||||
fn uciGo(game: *types.game, alloc: std.mem.Allocator) []u8 {
|
||||
var moves = std.ArrayList(types.move).init(alloc);
|
||||
defer moves.deinit();
|
||||
const str = alloc.alloc(u8, 5) catch unreachable;
|
||||
mov.pawnMove(game, &moves);
|
||||
mov.rookMove(game, &moves);
|
||||
mov.knightMove(game, &moves);
|
||||
mov.bishipMove(game, &moves);
|
||||
mov.kingMove(game, &moves);
|
||||
mov.quenMove(game, &moves);
|
||||
if (moves.capacity == 0) {
|
||||
@memcpy(str.ptr, "0000");
|
||||
return str;
|
||||
}
|
||||
|
||||
mov.moveTypeToStr(moves.items[0], str);
|
||||
return str;
|
||||
}
|
||||
|
||||
test "uci uci" {
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
defer _ = gpa.deinit();
|
||||
const alloc = gpa.allocator();
|
||||
const game = uciPos("fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", alloc);
|
||||
defer alloc.destroy(game);
|
||||
|
||||
const out = uci("uci", game, alloc);
|
||||
try std.testing.expect(out == .text);
|
||||
}
|
||||
|
||||
test "uci ready" {
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
defer _ = gpa.deinit();
|
||||
const alloc = gpa.allocator();
|
||||
const game = uciPos("fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", alloc);
|
||||
defer alloc.destroy(game);
|
||||
|
||||
const out = uci("isready", game, alloc);
|
||||
try std.testing.expect(out == .text);
|
||||
}
|
||||
|
||||
test "uci go" {
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
defer _ = gpa.deinit();
|
||||
const alloc = gpa.allocator();
|
||||
const game = uciPos("fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", alloc);
|
||||
defer alloc.destroy(game);
|
||||
|
||||
const out = uci("go", game, alloc);
|
||||
try std.testing.expect(out == .move);
|
||||
alloc.free(out.move);
|
||||
}
|
||||
|
||||
test "uci position" {
|
||||
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
defer _ = gpa.deinit();
|
||||
const alloc = gpa.allocator();
|
||||
const game = uciPos("fen rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", alloc);
|
||||
const gameb = uciPos("startpos", alloc);
|
||||
defer alloc.destroy(game);
|
||||
defer alloc.destroy(gameb);
|
||||
|
||||
const out = uci("position startpos", game, alloc);
|
||||
defer alloc.destroy(out.game);
|
||||
try std.testing.expect(out == .game);
|
||||
try std.testing.expect(out.game.whiteToMove == true);
|
||||
try std.testing.expect(out.game.white.king != 0);
|
||||
try std.testing.expect(out.game.black.king != 0);
|
||||
try std.testing.expectEqualDeep(game, gameb);
|
||||
}
|
||||
261
src/move.zig
Normal file
261
src/move.zig
Normal file
@@ -0,0 +1,261 @@
|
||||
const std = @import("std");
|
||||
const types = @import("types.zig");
|
||||
|
||||
pub fn moveTypeToStr(move: types.move, buf: []u8) void {
|
||||
const xTo = @mod(move.To, 8);
|
||||
const yTo = @divTrunc(move.To, 8);
|
||||
const xFrom = @mod(move.From, 8);
|
||||
const yFrom = @divTrunc(move.From, 8);
|
||||
|
||||
buf[0] = @intCast(xFrom + 'a');
|
||||
buf[1] = @intCast(yFrom + '0' + 1);
|
||||
buf[2] = @intCast(xTo + 'a');
|
||||
buf[3] = @intCast(yTo + '0' + 1);
|
||||
buf[4] = move.Promo;
|
||||
}
|
||||
|
||||
pub fn playMoves(game: *types.game, str: []const u8) *types.game {
|
||||
if (str.len < 4) return game;
|
||||
var splitItr = std.mem.splitSequence(u8, str, " ");
|
||||
while (splitItr.next()) |moveString| {
|
||||
if (moveString.len < 4 or moveString[0] > 'h')
|
||||
continue;
|
||||
var move: types.move = .{ .To = 0, .From = 0, .Promo = 0 };
|
||||
if (moveString.len < 4) continue;
|
||||
move.From = (moveString[0] - 'a') + (moveString[1] - '1') * 8;
|
||||
move.To = (moveString[2] - 'a') + (moveString[3] - '1') * 8;
|
||||
move.Promo = if (moveString.len == 5) moveString[4] else 0;
|
||||
makeMove(@ptrCast(game), @ptrCast(&move));
|
||||
}
|
||||
return game;
|
||||
}
|
||||
|
||||
fn fullSet(set: *types.set) u64 {
|
||||
return set.bishops | set.king | set.knights | set.pawns | set.queen | set.rooks;
|
||||
}
|
||||
|
||||
fn findSet(game: *types.game, bit: u64) ?*u64 {
|
||||
if (game.white.pawns & bit != 0) {
|
||||
return &game.white.pawns;
|
||||
} else if (game.white.knights & bit != 0) {
|
||||
return &game.white.knights;
|
||||
} else if (game.white.bishops & bit != 0) {
|
||||
return &game.white.bishops;
|
||||
} else if (game.white.rooks & bit != 0) {
|
||||
return &game.white.rooks;
|
||||
} else if (game.white.queen & bit != 0) {
|
||||
return &game.white.queen;
|
||||
} else if (game.white.king & bit != 0) {
|
||||
return &game.white.king;
|
||||
} else if (game.black.pawns & bit != 0) {
|
||||
return &game.black.pawns;
|
||||
} else if (game.black.knights & bit != 0) {
|
||||
return &game.black.knights;
|
||||
} else if (game.black.bishops & bit != 0) {
|
||||
return &game.black.bishops;
|
||||
} else if (game.black.rooks & bit != 0) {
|
||||
return &game.black.rooks;
|
||||
} else if (game.black.queen & bit != 0) {
|
||||
return &game.black.queen;
|
||||
} else if (game.black.king & bit != 0) {
|
||||
return &game.black.king;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
fn makeMove(game: *types.game, move: *types.move) void {
|
||||
const from = @as(u64, 1) << @truncate(move.From);
|
||||
const to = @as(u64, 1) << @truncate(move.To);
|
||||
const set = findSet(game, from);
|
||||
if (set == null)
|
||||
return;
|
||||
set.?.* &= ~from;
|
||||
|
||||
const cap = findSet(game, to);
|
||||
if (cap != null)
|
||||
cap.?.* &= ~to;
|
||||
|
||||
if (move.Promo != 0) {
|
||||
charToSet(game, move.Promo).* |= to;
|
||||
} else {
|
||||
set.?.* |= to;
|
||||
}
|
||||
|
||||
game.whiteToMove = !game.whiteToMove;
|
||||
}
|
||||
|
||||
pub fn charToSet(g: *types.game, chr: u8) *u64 {
|
||||
return switch (chr) {
|
||||
'P' => &g.white.pawns,
|
||||
'N' => &g.white.knights,
|
||||
'B' => &g.white.bishops,
|
||||
'R' => &g.white.rooks,
|
||||
'Q' => &g.white.queen,
|
||||
'K' => &g.white.king,
|
||||
'p' => &g.black.pawns,
|
||||
'n' => &g.black.knights,
|
||||
'b' => &g.black.bishops,
|
||||
'r' => &g.black.rooks,
|
||||
'q' => &g.black.queen,
|
||||
'k' => &g.black.king,
|
||||
else => {
|
||||
std.log.err("you should not be here ${c}$", .{chr});
|
||||
unreachable;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
pub fn pawnMove(game: *types.game, arr: *std.ArrayList(types.move)) void {
|
||||
_ = game;
|
||||
_ = arr;
|
||||
}
|
||||
|
||||
pub fn bishipMove(game: *types.game, arr: *std.ArrayList(types.move)) void {
|
||||
_ = game;
|
||||
_ = arr;
|
||||
}
|
||||
|
||||
pub fn kingMove(game: *types.game, arr: *std.ArrayList(types.move)) void {
|
||||
_ = game;
|
||||
_ = arr;
|
||||
}
|
||||
|
||||
pub fn quenMove(game: *types.game, arr: *std.ArrayList(types.move)) void {
|
||||
const set = if (game.whiteToMove) &game.white.queen else &game.black.queen;
|
||||
const full = fullSet(&game.white) | fullSet(&game.black);
|
||||
var val = set.*;
|
||||
const n = @popCount(val);
|
||||
for (0..n) |_| {
|
||||
const pos = @ctz(val);
|
||||
const bit = @as(u64, 1) << @truncate(pos);
|
||||
var moves = sqrScan(bit, full, false);
|
||||
moves |= @bitReverse(sqrScan(bit, full, true));
|
||||
val = val ^ (@as(u64, 1) << @truncate(pos));
|
||||
|
||||
bitboardToMoves(pos, moves, arr);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rookMove(game: *types.game, arr: *std.ArrayList(types.move)) void {
|
||||
const set = if (game.whiteToMove) &game.white.rooks else &game.black.rooks;
|
||||
const full = fullSet(&game.white) | fullSet(&game.black);
|
||||
var val = set.*;
|
||||
const n = @popCount(val);
|
||||
for (0..n) |_| {
|
||||
const pos = @ctz(val);
|
||||
const bit = @as(u64, 1) << @truncate(pos);
|
||||
var moves = sqrScan(bit, full, false);
|
||||
moves |= @bitReverse(sqrScan(bit, full, true));
|
||||
val = val ^ (@as(u64, 1) << @truncate(pos));
|
||||
|
||||
bitboardToMoves(pos, moves, arr);
|
||||
}
|
||||
}
|
||||
|
||||
fn sqrScan(rook: u64, hit: u64, flip: bool) u64 {
|
||||
const vecLut: [64]u64 = comptime blk: {
|
||||
var value: [64]u64 = undefined;
|
||||
for (0..64) |i| {
|
||||
value[i] = vecCalc(@truncate(i));
|
||||
}
|
||||
break :blk value;
|
||||
};
|
||||
var center = rook;
|
||||
var hits = hit;
|
||||
if (flip) {
|
||||
center = @bitReverse(rook);
|
||||
hits = @bitReverse(hit);
|
||||
}
|
||||
|
||||
const vec = vecLut[@ctz(center)];
|
||||
|
||||
var attackedBits = hits & vec;
|
||||
const n = @popCount(attackedBits);
|
||||
var min: u64 = vec;
|
||||
for (0..n) |_| {
|
||||
const pos = @ctz(attackedBits);
|
||||
const bit = @as(u64, 1) << @truncate(pos);
|
||||
attackedBits = attackedBits & ~bit;
|
||||
if (bit - 1 < min) min = bit - 1;
|
||||
}
|
||||
min = min & (~center);
|
||||
return min;
|
||||
}
|
||||
|
||||
fn vecCalc(i: u8) u64 {
|
||||
var ret: u64 = 0;
|
||||
const col = i % 8;
|
||||
|
||||
// "West" ray
|
||||
for (1..8) |n| {
|
||||
if (i < n or (i - n) % 8 != col)
|
||||
break;
|
||||
ret = ret | @as(u64, 1) << (i - n);
|
||||
}
|
||||
|
||||
// "North" ray
|
||||
for (1..8) |n| {
|
||||
const new_pos = i + (n * 8);
|
||||
if (new_pos > 63)
|
||||
break;
|
||||
ret = ret | @as(u64, 1) << new_pos;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
pub fn knightMove(g: *types.game, arr: *std.ArrayList(types.move)) void {
|
||||
const moveLut: [64]u64 = comptime blk: {
|
||||
var value: [64]u64 = undefined;
|
||||
for (0..64) |i| {
|
||||
value[i] = knightCalc(@truncate(i));
|
||||
}
|
||||
break :blk value;
|
||||
};
|
||||
const set = if (g.whiteToMove) &g.white.knights else &g.black.knights;
|
||||
const fset: u64 = if (g.whiteToMove) @as(u64, fullSet(@ptrCast(&g.white))) else @as(u64, fullSet(@ptrCast(&g.black)));
|
||||
var val = set.*; //local copy
|
||||
const n = @popCount(val);
|
||||
for (0..n) |_| {
|
||||
const pos = @ctz(val);
|
||||
const moves = moveLut[pos] & ~fset;
|
||||
val = val ^ (@as(u64, 1) << @truncate(pos));
|
||||
bitboardToMoves(pos, moves, arr);
|
||||
}
|
||||
}
|
||||
|
||||
fn knightCalc(index: u8) u64 {
|
||||
var moves: u64 = 0;
|
||||
const offsets = [_]i8{ 17, -17, 15, -15, 10, -10, 6, -6 };
|
||||
var cnt: u8 = undefined;
|
||||
for (offsets) |off| {
|
||||
if (off > 0) {
|
||||
cnt = index + @abs(off);
|
||||
} else if (index > @abs(off)) { //Icky bad that zig makes me do
|
||||
cnt = index - @abs(off);
|
||||
}
|
||||
const fromFile: i32 = index % 8;
|
||||
const toFile: i32 = cnt % 8;
|
||||
const fromRank: i32 = index / 8;
|
||||
const toRank: i32 = cnt / 8;
|
||||
|
||||
const fileDiff = @abs(fromFile - toFile);
|
||||
const rankDiff = @abs(fromRank - toRank);
|
||||
if (!((fileDiff == 1 and rankDiff == 2) or
|
||||
(fileDiff == 2 and rankDiff == 1)) or cnt > 63)
|
||||
continue;
|
||||
moves = moves | @as(u64, 1) << @truncate(cnt);
|
||||
}
|
||||
return moves;
|
||||
}
|
||||
|
||||
fn bitboardToMoves(start: u8, moves: u64, arr: *std.ArrayList(types.move)) void {
|
||||
var lmoves = moves;
|
||||
while (lmoves != 0) {
|
||||
const pos = @ctz(lmoves);
|
||||
const m: types.move = .{ .From = start, .Promo = 0, .To = pos };
|
||||
lmoves = lmoves & ~@as(u64, 1) << @truncate(pos);
|
||||
arr.append(m) catch unreachable;
|
||||
}
|
||||
}
|
||||
47
src/types.zig
Normal file
47
src/types.zig
Normal file
@@ -0,0 +1,47 @@
|
||||
const c = @cImport({
|
||||
@cInclude("main.h");
|
||||
@cInclude("types.h");
|
||||
@cInclude("help.h");
|
||||
@cInclude("eval.h");
|
||||
@cInclude("moves.h");
|
||||
});
|
||||
|
||||
const uciTag = enum {
|
||||
text,
|
||||
move,
|
||||
game,
|
||||
exit,
|
||||
pass,
|
||||
};
|
||||
|
||||
pub const uciRet = union(uciTag) {
|
||||
text: []const u8,
|
||||
move: []u8,
|
||||
game: *game,
|
||||
exit: void,
|
||||
pass: void,
|
||||
};
|
||||
|
||||
pub const set = struct {
|
||||
pawns: u64,
|
||||
knights: u64,
|
||||
bishops: u64,
|
||||
rooks: u64,
|
||||
queen: u64,
|
||||
king: u64,
|
||||
};
|
||||
pub const game = struct {
|
||||
black: set,
|
||||
white: set,
|
||||
whiteToMove: bool,
|
||||
};
|
||||
pub const move = struct {
|
||||
From: u32,
|
||||
To: u32,
|
||||
Promo: u8,
|
||||
};
|
||||
// struct {
|
||||
// To: u8,
|
||||
// From: u8,
|
||||
// Promo: u8,
|
||||
// };
|
||||
64
uchess.json
Normal file
64
uchess.json
Normal file
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"uciWhite": "rat",
|
||||
"uciBlack": "rat",
|
||||
"uciHint": "stockfish",
|
||||
"uciEngines": [
|
||||
{
|
||||
"name":"rat",
|
||||
"engine":"./zig-out/bin/RatChess",
|
||||
"ponder":false
|
||||
},
|
||||
{
|
||||
"name": "stockfish",
|
||||
"engine": "/nix/store/xrzjqi5m9yphj4p5wgpvnamxs38ap0wv-stockfish-17/bin/stockfish",
|
||||
"hash": 128,
|
||||
"ponder": false,
|
||||
"ownBook": false,
|
||||
"multiPV": 1,
|
||||
"depth": 1,
|
||||
"searchMoves": "",
|
||||
"moveTime": 100,
|
||||
"options": [
|
||||
{
|
||||
"name": "skill level",
|
||||
"value": "3"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
|
||||
"activeTheme": "basic",
|
||||
"theme": [
|
||||
{
|
||||
"name": "basic",
|
||||
"moveLabelBg": "#d0d0d0",
|
||||
"moveLabelFg": "#000000",
|
||||
"squareDark": "#d7d7d7",
|
||||
"squareLight": "#ffffd7",
|
||||
"squareHigh": "#ffff00",
|
||||
"squareHint": "#ffd7af",
|
||||
"squareCheck": "#ffafd7",
|
||||
"white": "#080808",
|
||||
"black": "#080808",
|
||||
"msg": "#d70000",
|
||||
"rank": "#9e9e9e",
|
||||
"file": "#9e9e9e",
|
||||
"prompt": "#d70000",
|
||||
"meterBase": "#585858",
|
||||
"meterMid": "#0",
|
||||
"meterNeutral": "#00d7ff",
|
||||
"meterWin": "#87ffd7",
|
||||
"meterLose": "#d75f5f",
|
||||
"playerNames": "#0",
|
||||
"score": "#9e9e9e",
|
||||
"moveBox": "#0",
|
||||
"emoji": "#0",
|
||||
"input": "#0",
|
||||
"advantage": "#9e9e9e"
|
||||
}
|
||||
],
|
||||
"whitePiece": "cpu",
|
||||
"blackPiece": "cpu",
|
||||
"whiteName": "",
|
||||
"blackName": ""
|
||||
}
|
||||
Reference in New Issue
Block a user