BlueGit

projects-timfalken-com microchess

Files

microchess / web / lib / Chess.php

Chess.php

effects
timfa Tim Falken · pushed by timfa · 2 months ago
d82deb2f History
Chess.php 5.8 KiB Download Raw
1<?php
2declare(strict_types=1);
3
4/** Board indices: a5=0, d5=3, a1=16, d1=19. Uppercase is white. */
5final class Chess
6{
7 public static function initial(): array
8 {
9 $s = ['board'=>[], 'turn'=>'w', 'halfmove'=>0, 'ply'=>0, 'history'=>[], 'last'=>null];
10 // Keep empty squares explicit; the position contains exactly twenty squares.
11 $s['board'] = ['k','n','b','r','p','.','.','.','.','.','.','.','.','.','.','P','R','B','N','K'];
12 $s['history'][] = self::key($s);
13 return $s;
14 }
15 public static function color(string $p): ?string { return $p==='.' ? null : (ctype_upper($p)?'w':'b'); }
16 public static function opposite(string $c): string { return $c==='w'?'b':'w'; }
17 public static function key(array $s): string { return implode('', $s['board']).$s['turn']; }
18 public static function attacked(array $b, int $target, string $by): bool
19 {
20 foreach ($b as $i=>$p) {
21 if (self::color($p)!==$by) continue;
22 $dx=$target%4-$i%4; $dy=intdiv($target,4)-intdiv($i,4); $t=strtolower($p);
23 if ($t==='p' && abs($dx)===1 && $dy===($by==='w'?-1:1)) return true;
24 if ($t==='n' && abs($dx)*abs($dy)===2) return true;
25 if ($t==='k' && max(abs($dx),abs($dy))===1) return true;
26 $diagonal=abs($dx)===abs($dy) && $dx!==0;
27 $straight=($dx===0 xor $dy===0);
28 if (!(($t==='b' && $diagonal)||($t==='r' && $straight)||($t==='q' && ($diagonal||$straight)))) continue;
29 $sx=$dx<=>0; $sy=$dy<=>0; $x=$i%4+$sx; $y=intdiv($i,4)+$sy;
30 while ($y*4+$x!==$target) { if ($b[$y*4+$x]!=='.') continue 2; $x+=$sx; $y+=$sy; }
31 return true;
32 }
33 return false;
34 }
35 public static function check(array $s, ?string $color=null): bool
36 {
37 $color ??= $s['turn'];
38 $king=array_search($color==='w'?'K':'k',$s['board'],true);
39 return $king===false || self::attacked($s['board'],$king,self::opposite($color));
40 }
41 public static function legal(array $s): array
42 {
43 $out=[]; $b=$s['board']; $c=$s['turn'];
44 foreach ($b as $from=>$p) {
45 if (self::color($p)!==$c) continue;
46 for ($to=0;$to<20;$to++) {
47 if ($to===$from || self::color($b[$to])===$c || strtolower($b[$to])==='k') continue;
48 $dx=$to%4-$from%4; $dy=intdiv($to,4)-intdiv($from,4);
49 if (strtolower($p)==='p') {
50 $ok=$dy===($c==='w'?-1:1) && (($dx===0 && $b[$to]==='.')||(abs($dx)===1 && $b[$to]!=='.'));
51 } else {
52 $ok=self::pieceReaches($b,$from,$to);
53 }
54 if (!$ok) continue;
55 $next=$s; $next['board'][$to]=$p; $next['board'][$from]='.';
56 if (self::check($next,$c)) continue;
57 if (strtolower($p)==='p' && (intdiv($to,4)===0||intdiv($to,4)===4)) {
58 foreach (['q','r','b','n'] as $promotion) $out[]=['from'=>$from,'to'=>$to,'promotion'=>$promotion];
59 } else $out[]=['from'=>$from,'to'=>$to,'promotion'=>null];
60 }
61 }
62 return $out;
63 }
64 private static function pieceReaches(array $b,int $from,int $to): bool
65 {
66 $dx=$to%4-$from%4; $dy=intdiv($to,4)-intdiv($from,4); $t=strtolower($b[$from]);
67 if ($t==='n') return abs($dx)*abs($dy)===2;
68 if ($t==='k') return max(abs($dx),abs($dy))===1;
69 $d=abs($dx)===abs($dy) && $dx!==0; $r=($dx===0 xor $dy===0);
70 if (!(($t==='b'&&$d)||($t==='r'&&$r)||($t==='q'&&($d||$r)))) return false;
71 $sx=$dx<=>0; $sy=$dy<=>0; $x=$from%4+$sx; $y=intdiv($from,4)+$sy;
72 while ($y*4+$x!==$to) { if ($b[$y*4+$x]!=='.') return false; $x+=$sx; $y+=$sy; }
73 return true;
74 }
75 public static function move(array $s,int $from,int $to,?string $promotion=null): array
76 {
77 $move=['from'=>$from,'to'=>$to,'promotion'=>$promotion];
78 if (!in_array($move,self::legal($s),true)) throw new DomainException('That move is not legal.');
79 return self::afterLegal($s,$move);
80 }
81 /** Apply a move already generated by legal(); external input must go through move(). */
82 public static function afterLegal(array $s,array $move): array
83 {
84 ['from'=>$from,'to'=>$to,'promotion'=>$promotion]=$move;
85 $p=$s['board'][$from];
86 $s['halfmove']=strtolower($p)==='p'||$s['board'][$to]!=='.'?0:$s['halfmove']+1;
87 $s['board'][$to]=$promotion ? ($s['turn']==='w'?strtoupper($promotion):$promotion):$p;
88 $s['board'][$from]='.'; $s['turn']=self::opposite($s['turn']); $s['ply']++; $s['last']=$move;
89 $s['history'][]=self::key($s); return $s;
90 }
91 public static function dead(array $s): bool
92 {
93 $minors=[];
94 foreach ($s['board'] as $i=>$p) {
95 if (in_array(strtolower($p),['.','k'],true)) continue;
96 if (!in_array(strtolower($p),['b','n'],true)) return false;
97 $minors[$i]=$p;
98 }
99 if (count($minors)<=1) return true;
100 $squares=[];
101 foreach ($minors as $i=>$p) { if (strtolower($p)!=='b') return false; $squares[]=($i%4+intdiv($i,4))%2; }
102 return count(array_unique($squares))===1;
103 }
104 public static function repetitions(array $s): int { return count(array_filter($s['history'],fn($k)=>$k===self::key($s))); }
105 public static function claimable(array $s): bool { return $s['halfmove']>=100 || self::repetitions($s)>=3; }
106 public static function result(array $s): ?array
107 {
108 if (!self::legal($s)) return self::check($s)?['winner'=>self::opposite($s['turn']),'reason'=>'Checkmate']:['winner'=>null,'reason'=>'Stalemate'];
109 if (self::dead($s)) return ['winner'=>null,'reason'=>'Dead position'];
110 if ($s['halfmove']>=150) return ['winner'=>null,'reason'=>'75-move rule'];
111 if (self::repetitions($s)>=5) return ['winner'=>null,'reason'=>'Fivefold repetition'];
112 return null;
113 }
114}