src/chess/king.c

changeset 169
9962f5d98764
parent 163
2a6d83f4677e
child 170
bde99d803caf
--- a/src/chess/king.c	Sun Aug 02 15:19:47 2026 +0200
+++ b/src/chess/king.c	Thu Aug 06 14:45:55 2026 +0200
@@ -30,8 +30,6 @@
 #include "rules.h"
 #include "king.h"
 
-#include <string.h>
-
 static bool king_castling_chkmoved(
         const GameState *gamestate, Row row, File file) {
 
@@ -89,3 +87,54 @@
     
     return blocked;
 }
+
+size_t king_moves(GameState *gamestate, Color c, Row r, File f, Move *moves) {
+
+    size_t count = 0;
+    Piece king = mkpiece(KING, c);
+
+    for (int dr = -1 ; dr <= 1 ; dr++) {
+        for (int df = -1 ; df <= 1 ; df++) {
+            if (dr == 0 && df == 0) {
+                continue;
+            }
+
+            Row torow = r + dr;
+            File tofile = f + df;
+
+            if (!isidx(torow) || !isidx(tofile)) {
+                continue;
+            }
+
+            moves[count] = (Move){0};
+            moves[count].piece = king;
+            moves[count].fromrow = r;
+            moves[count].fromfile = f;
+            moves[count].torow = torow;
+            moves[count].tofile = tofile;
+            moves[count].capture = piece_at(gamestate, torow, tofile) != 0;
+            count++;
+        }
+    }
+
+    Row homerow = c == WHITE ? 0 : 7;
+    if (r == homerow && f == fileidx('e')) {
+        moves[count] = (Move){0};
+        moves[count].piece = king;
+        moves[count].fromrow = r;
+        moves[count].fromfile = f;
+        moves[count].torow = r;
+        moves[count].tofile = fileidx('c');
+        count++;
+
+        moves[count] = (Move){0};
+        moves[count].piece = king;
+        moves[count].fromrow = r;
+        moves[count].fromfile = f;
+        moves[count].torow = r;
+        moves[count].tofile = fileidx('g');
+        count++;
+    }
+
+    return count;
+}

mercurial