Compare commits

..

7 Commits

Author SHA1 Message Date
k
da8eb581e3 C go added and uci ret type
All checks were successful
Verify build / verify_build (push) Successful in 1m3s
2025-07-12 15:08:12 -04:00
k
f9cdd9a259 Merge branch 'zig' of git.dhilton.xyz:k/RatChess into zig
All checks were successful
Verify build / verify_build (push) Successful in 1m16s
2025-07-01 16:04:10 -04:00
k
5a7b5f1642 fenGame fn connected to zig 2025-07-01 15:59:39 -04:00
k
34601f9c9d update nix version
All checks were successful
Verify build / verify_build (push) Successful in 2m0s
2025-07-01 16:01:05 +00:00
k
3a9b53d384 fix yaml
Some checks failed
Verify build / verify_build (push) Failing after 1m11s
2025-07-01 15:57:58 +00:00
k
986e8c8334 add nixbased build ci 2025-07-01 02:56:48 -04:00
k
fc32b56a2f working in zig build 2025-07-01 02:16:44 -04:00
13 changed files with 369 additions and 74 deletions

View 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
View File

@@ -1 +1,4 @@
/a.out
/.zig-cache/
/zig-out/
/result

View File

@@ -1,3 +1,6 @@
# RatChess
A chess engine made for fun
A chess engine made for fun
## Branch
Port to zig for fun and to learn zig

36
build.zig Normal file
View File

@@ -0,0 +1,36 @@
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 });
exe.linkLibC();
exe.addIncludePath(b.path("headers/"));
exe.addCSourceFile(.{ .file = b.path("src/eval.c") });
exe.addCSourceFile(.{ .file = b.path("src/help.c") });
exe.addCSourceFile(.{ .file = b.path("src/main.c") });
exe.addCSourceFile(.{ .file = b.path("src/moves.c") });
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
View 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
View 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;
}

10
headers/main.h Normal file
View File

@@ -0,0 +1,10 @@
#ifndef MAIN_H
#define MAIN_H
#include "types.h"
int cmain();
game *fenGame(char *str);
void playMoves(game *g, char *moves);
char* uciGo(game *g);
#endif

View File

@@ -3,12 +3,12 @@
#include <stdbool.h>
typedef struct {
long long pawns;
long long knights;
long long bishops;
long long rooks;
long long queen;
long long king;
unsigned long long pawns;
unsigned long long knights;
unsigned long long bishops;
unsigned long long rooks;
unsigned long long queen;
unsigned long long king;
} sets;
typedef struct {

View File

@@ -1,11 +1,9 @@
{pkgs ? import <nixpkgs> {}}:
with pkgs;
mkShell rec {
packages = [gdb clang-tools uchess cutechess];
packages = [gdb zls uchess cutechess];
nativeBuildInputs = [
pkg-config
gcc
gnumake
zig
];
buildInputs = [
];

View File

@@ -56,20 +56,20 @@ int evaluateBoard(game *game) {
}
void makeMove(game *g, move* m) {
long long from_bit = 1LL << m->From;
long long to_bit = 1LL << m->To;
unsigned long long from_bit = 1ULL << m->From;
unsigned long long to_bit = 1ULL << m->To;
long long *set = findSet(g, from_bit);
unsigned long long *set = findSet(g, from_bit);
if (!set)
return;
*set &= ~from_bit;
long long *captured = findSet(g, to_bit);
unsigned long long *captured = findSet(g, to_bit);
if (captured) *captured &= ~to_bit;
if (m->Promo) {
char promoChar = g->whiteToMove ? toupper(m->Promo) : m->Promo;
long long *newSet = charToSet(g, promoChar);
unsigned long long *newSet = charToSet(g, promoChar);
if (newSet)
*newSet |= to_bit;
} else {

View File

@@ -10,6 +10,7 @@
#include "types.h"
#include "help.h"
#include "eval.h"
#include "main.h"
#define BUFF_SIZE 4096
@@ -18,7 +19,7 @@ void playMoves(game *g, char *moves);
long long *findSet(game *g, long long bit);
long long *charToSet(game *g, char c);
int main() {
int cmain() {
setbuf(stdin, NULL);
setbuf(stdout, NULL);
game *g = NULL;
@@ -55,38 +56,47 @@ int main() {
} else if (!strcmp("isready", token)) {
printf("readyok\n");
} else if (!strcmp("go", token)) {
static move mov[1500];//big dumb buffer
size_t cnt = 0;
cnt += pawnMove(g,mov);
cnt += knightMove(g,(mov+cnt));
cnt += rookMove(g,(mov+cnt));
cnt += bishopMove(g,(mov+cnt));
cnt += kingMove(g,(mov+cnt));
cnt += queenMove(g,(mov+cnt));
move *m = findBest(mov,cnt,g);
if(m == NULL){
printf("bestmove 0000\n");
continue;
}
char *end = "";
int yTo, xTo, yFrom, xFrom;
xTo = m->To % 8;
yTo = m->To / 8 + 1;
xFrom = m->From % 8;
yFrom = m->From / 8 + 1;
long long bit = 1LL << m->From;
if (m->Promo) {
end = "q\n";
} else {
end = "\n";
}
printf("bestmove %c%d%c%d%s", ltz[xFrom], yFrom, ltz[xTo], yTo, end);
uciGo(g);
}
}
}
char* uciGo(game *g){
char ltz[] = "abcdefgh";
static move mov[1500];//big dumb buffer
size_t cnt = 0;
cnt += pawnMove(g,mov);
cnt += knightMove(g,(mov+cnt));
cnt += rookMove(g,(mov+cnt));
cnt += bishopMove(g,(mov+cnt));
cnt += kingMove(g,(mov+cnt));
cnt += queenMove(g,(mov+cnt));
move *m = findBest(mov,cnt,g);
if(m == NULL){
printf("bestmove 0000\n");
return "";
}
char *end = "";
int yTo, xTo, yFrom, xFrom;
xTo = m->To % 8;
yTo = m->To / 8 + 1;
xFrom = m->From % 8;
yFrom = m->From / 8 + 1;
long long bit = 1LL << m->From;
if (m->Promo) {
end = "q\n";
} else {
end = "\n";
}
char* resultString = (char*)malloc(10 * sizeof(char));
sprintf(resultString, "%c%d%c%d%s", ltz[xFrom], yFrom, ltz[xTo], yTo, end);
return resultString;
}
game *fenGame(char *str) {
int rank = 7;
int file = 0;
@@ -112,7 +122,7 @@ game *fenGame(char *str) {
continue;
}
long long bit = 1LL << (rank * 8 + file);
long long bit = 1ULL << (rank * 8 + file);
long long *set = charToSet(g, *str);
if (set)
*set |= bit;

101
src/main.zig Normal file
View File

@@ -0,0 +1,101 @@
const std = @import("std");
const c = @cImport({
@cInclude("main.h");
@cInclude("types.h");
});
const uciTag = enum {
text,
move,
game,
exit,
pass,
};
const uciRet = union(uciTag) {
text: []const u8,
move: []const u8,
game: *c.game,
exit: void,
pass: void,
};
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: *c.game = uciPos("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
while (true) {
const line = try reader.readUntilDelimiterAlloc(alloc, '\n', std.math.maxInt(usize));
defer alloc.free(line);
switch (uci(line, game)) {
.text => |value| {
try std.io.getStdOut().writer().print("{s}", .{value});
},
.move => |value| {
try std.io.getStdOut().writer().print("bestmove {s}\n", .{value});
},
.game => |value| {
game = value;
},
.exit => {
break;
},
.pass => {
try std.io.getStdOut().writer().print("info bad input\n", .{});
},
}
}
}
fn uci(str: []const u8, game: *c.game) 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) };
if (std.mem.eql(u8, tok, "position")) return .{ .game = uciPos("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1") };
if (std.mem.eql(u8, tok, "exit")) return .{ .exit = {} };
return .{ .pass = {} };
}
fn uciPos(str: []const u8) [*c]c.game {
var buffer: [256]u8 = undefined;
const len = @min(str.len, buffer.len - 1);
@memcpy(buffer[0..len], str[0..len]);
buffer[len] = 0;
const game = c.fenGame(&buffer);
return game;
}
fn uciGo(game: *c.game) []const u8 {
return std.mem.span(c.uciGo(game));
}
test "uci uci" {
const game = uciPos("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
const out = uci("uci", game);
try std.testing.expect(out == .text);
}
test "uci ready" {
const game = uciPos("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
const out = uci("isready", game);
try std.testing.expect(out == .text);
}
test "uci go" {
const game = uciPos("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
const out = uci("go", game);
try std.testing.expect(out == .move);
}
test "uci position" {
const game = uciPos("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
const out = uci("position startpos", game);
try std.testing.expect(out == .game);
}

View File

@@ -12,7 +12,7 @@ int pawnMove(game *g, move *moves) {
long long pawns = g->whiteToMove ? g->white.pawns : g->black.pawns;
long long enemy = g->whiteToMove ? fullSet(&g->black) : fullSet(&g->white);
long long occupied = fullSetBoth(g);
long long promo = (0xFFLL) << (g->whiteToMove ? 56 : 0);
long long promo = (0xFFULL) << (g->whiteToMove ? 56 : 0);
int movdir = g->whiteToMove ? 8 : -8;
int capLeft = g->whiteToMove ? 7 : -9;
@@ -21,29 +21,29 @@ int pawnMove(game *g, move *moves) {
size_t index = 0;
for (int i = 0; i < 64; ++i) {
long long bit = 1LL << i;
long long bit = 1ULL << i;
char p = 0;
if (!(pawns & bit))
continue;
// forword
int to = i + movdir;
p = (promo & (1LL << to)) ? 'q' : 0;
if (to >= 0 && to < 64 && !(occupied & (1LL << to))) {
p = (promo & (1ULL << to)) ? 'q' : 0;
if (to >= 0 && to < 64 && !(occupied & (1ULL << to))) {
moves[index++] = (move){.From = i, .To = to, .Promo = p};
}
// left
to = i + capLeft;
p = (promo & (1LL << to)) ? 'q' : 0;
if (i % 8 > 0 && (to >= 0 && to < 64) && (enemy & (1LL << to))) {
p = (promo & (1ULL << to)) ? 'q' : 0;
if (i % 8 > 0 && (to >= 0 && to < 64) && (enemy & (1ULL << to))) {
moves[index++] = (move){.From = i, .To = to, .Promo = p};
}
// right
to = i + capRight;
p = (promo & (1LL << to)) ? 'q' : 0;
if (i % 8 < 7 && (to >= 0 && to < 64) && (enemy & (1LL << to))) {
p = (promo & (1ULL << to)) ? 'q' : 0;
if (i % 8 < 7 && (to >= 0 && to < 64) && (enemy & (1ULL << to))) {
moves[index++] = (move){.From = i, .To = to, .Promo = p};
}
}
@@ -58,7 +58,7 @@ int knightMove(game *g, move *moves) {
int index = 0;
for (int i = 0; i < 64; i++) {
long long bit = 1LL << i;
long long bit = 1ULL << i;
if (!(knights & bit))
continue;
@@ -78,7 +78,7 @@ int knightMove(game *g, move *moves) {
(fileDiff == 2 && rankDiff == 1)))
continue;
long long destBit = 1LL << to;
long long destBit = 1ULL << to;
if (occupied & destBit)
continue;
@@ -100,7 +100,7 @@ int rookScan(game *g, move *moves, long long w, long long b) {
int index = 0;
for (int i = 0; i < 64; i++) {
long long bit = 1LL << i;
long long bit = 1ULL << i;
int x = i % 8;
int y = i / 8;
if (!(rooks & bit))
@@ -109,7 +109,7 @@ int rookScan(game *g, move *moves, long long w, long long b) {
// fwd
for (int j = y + 1; j < 8; j++) {
int to = (j * 8) + x;
long long lbit = 1LL << to;
long long lbit = 1ULL << to;
if (occupied & lbit)
break;
moves[index++] = (move){.From = i, .To = to, .Promo=0};
@@ -120,7 +120,7 @@ int rookScan(game *g, move *moves, long long w, long long b) {
// bck
for (int j = y - 1; j >= 0; j--) {
int to = (j * 8) + x;
long long lbit = 1LL << to;
long long lbit = 1ULL << to;
if (occupied & lbit)
break;
moves[index++] = (move){.From = i, .To = to, .Promo=0};
@@ -131,7 +131,7 @@ int rookScan(game *g, move *moves, long long w, long long b) {
// rht
for (int j = x + 1; j < 8; j++) {
int to = (y * 8) + j;
long long lbit = 1LL << to;
long long lbit = 1ULL << to;
if (occupied & lbit)
break;
moves[index++] = (move){.From = i, .To = to, .Promo=0};
@@ -142,7 +142,7 @@ int rookScan(game *g, move *moves, long long w, long long b) {
// lft
for (int j = x - 1; j >= 0; j--) {
int to = (y * 8) + j;
long long lbit = 1LL << to;
long long lbit = 1ULL << to;
if (occupied & lbit)
break;
moves[index++] = (move){.From = i, .To = to, .Promo=0};
@@ -158,14 +158,14 @@ int bishopMove(game *g, move *moves) {
}
int bishopScan(game *g, move *moves, long long w, long long b) {
long long bishops = g->whiteToMove ? w : b;
long long occupied = g->whiteToMove ? fullSet(&g->white) : fullSet(&g->black);
long long occupiedE =
unsigned long long bishops = g->whiteToMove ? w : b;
unsigned long long occupied = g->whiteToMove ? fullSet(&g->white) : fullSet(&g->black);
unsigned long long occupiedE =
!g->whiteToMove ? fullSet(&g->white) : fullSet(&g->black);
int index = 0;
for (int i = 0; i < 64; i++) {
long long bit = 1LL << i;
unsigned long long bit = 1ULL << i;
int x = i % 8;
int y = i / 8;
@@ -180,7 +180,7 @@ int bishopScan(game *g, move *moves, long long w, long long b) {
break;
int to = (yTo * 8) + xTo;
long long lbit = 1LL << to;
unsigned long long lbit = 1ULL << to;
if (occupied & lbit)
break;
@@ -197,7 +197,7 @@ int bishopScan(game *g, move *moves, long long w, long long b) {
break;
int to = (yTo * 8) + xTo;
long long lbit = 1LL << to;
unsigned long long lbit = 1ULL << to;
if (occupied & lbit)
break;
@@ -214,7 +214,7 @@ int bishopScan(game *g, move *moves, long long w, long long b) {
break;
int to = (yTo * 8) + xTo;
long long lbit = 1LL << to;
unsigned long long lbit = 1ULL << to;
if (occupied & lbit)
break;
@@ -231,7 +231,7 @@ int bishopScan(game *g, move *moves, long long w, long long b) {
break;
int to = (yTo * 8) + xTo;
long long lbit = 1LL << to;
unsigned long long lbit = 1ULL << to;
if (occupied & lbit)
break;
@@ -245,7 +245,7 @@ int bishopScan(game *g, move *moves, long long w, long long b) {
int queenMove(game *g, move *moves){
int size = 0;
long long w,b;
unsigned long long w,b;
w = g->white.queen;
b = g->black.queen;
size += rookScan(g,moves,w,b);
@@ -255,12 +255,12 @@ int queenMove(game *g, move *moves){
int kingMove(game *g, move *moves){
long long king = g->whiteToMove ? g->white.king : g->black.king;
long long occupied = g->whiteToMove ? fullSet(&g->white) : fullSet(&g->black);
unsigned long long king = g->whiteToMove ? g->white.king : g->black.king;
unsigned long long occupied = g->whiteToMove ? fullSet(&g->white) : fullSet(&g->black);
int index = 0;
for (int i = 0; i < 64; i++){
long long bit = 1LL << i;
unsigned long long bit = 1ULL << i;
int x = i % 8;
int y = i / 8;
int movesX[] = {-1, 0, 1, -1, 1, -1, 0, 1};
@@ -273,7 +273,9 @@ int kingMove(game *g, move *moves){
int toX = x + movesX[j];
int toY = y + movesY[j];
int to = (toY * 8) + toX;
long long destBit = 1LL << to;
if(to > 63 || to < 1)
continue;
unsigned long long destBit = 1ULL << to;
if (toX >= 0 && toX < 8 && toY >= 0 && toY < 8) {
if (!(occupied & destBit)) {