BlueGit

projects-timfalken-com microchess

Files

microchess / web / lib / MoveFeedback.php

MoveFeedback.php

effects
timfa Tim Falken · pushed by timfa · 2 months ago
d82deb2f History
MoveFeedback.php 4.6 KiB Download Raw
1<?php
2declare(strict_types=1);
3require_once __DIR__.'/Chess.php';
4
5/** Small tactical estimate for the submitted move, never a claim of perfect play. */
6final class MoveFeedback
7{
8 private const VALUES=['p'=>100,'n'=>300,'b'=>300,'r'=>500,'q'=>900,'k'=>0];
9 private const MATE=100000;
10 private const THRESHOLD=100;
11 private int $nodes=0;
12 private int $deadline;
13
14 public function __construct(private int $milliseconds=200,private int $maxNodes=8000) {}
15
16 public function rate(array $before,array $after): array
17 {
18 $started=hrtime(true);$this->deadline=$started+max(0,$this->milliseconds)*1000000;$this->nodes=0;
19 $out=['quality'=>null,'reason'=>'quiet','model'=>'tactical-estimate','ply'=>$after['ply']];
20 try {
21 $this->budget();
22 $result=Chess::result($after);
23 if ($result) {
24 if ($result['winner']===$before['turn']) $out['quality']='good';
25 $out['reason']=$result['winner']===null?'draw':'checkmate';
26 } elseif (Chess::claimable($before)||Chess::claimable($after)) {
27 // A move-only grade would omit the player's draw-claim option.
28 $out['reason']='draw-claim';
29 } else {
30 // Opponent's best reply, our answer, then up to two tactical continuation plies.
31 $score=-$this->search($after,2,2,-self::MATE,self::MATE,0);
32 $gain=$score-$this->material($before);
33 if ($score<=-self::MATE+100) {$out['quality']='poor';$out['reason']='mate-threat';}
34 elseif ($score>=self::MATE-100) {$out['quality']='good';$out['reason']='mate-threat';}
35 elseif ($gain>=self::THRESHOLD) {$out['quality']='good';$out['reason']='material-gain';}
36 elseif ($gain<=-self::THRESHOLD) {$out['quality']='poor';$out['reason']='material-loss';}
37 $out['gain']=$gain;
38 }
39 } catch (FeedbackLimit $e) {
40 $out['quality']=null;$out['reason']='inconclusive';
41 }
42 $out['nodes']=$this->nodes;$out['elapsed_ms']=round((hrtime(true)-$started)/1000000,2);
43 return $out;
44 }
45
46 private function budget(): void
47 {
48 if (++$this->nodes>$this->maxNodes || hrtime(true)>=$this->deadline) throw new FeedbackLimit();
49 }
50
51 /** Material from the side-to-move perspective; one pawn is 100. */
52 private function material(array $s): int
53 {
54 $value=0;
55 foreach ($s['board'] as $p) if ($p!=='.') $value+=(Chess::color($p)===$s['turn']?1:-1)*self::VALUES[strtolower($p)];
56 return $value;
57 }
58
59 private function search(array $s,int $depth,int $tactical,int $alpha,int $beta,int $ply,int $evasions=2): int
60 {
61 $this->budget();
62 $legal=Chess::legal($s);$check=Chess::check($s);
63 if (!$legal) return $check?-self::MATE+$ply:0;
64 if (Chess::dead($s)||$s['halfmove']>=150||Chess::repetitions($s)>=5) return 0;
65 $claim=Chess::claimable($s);
66 if ($depth===0 && $tactical===0) {
67 if (!$check) return $claim?max(0,$this->material($s)):$this->material($s);
68 // Give checks a little extra room; never pretend that staying in check is a legal option.
69 if ($evasions===0) throw new FeedbackLimit();
70 $tactical=1;$evasions--;
71 }
72 $best=$claim?0:-self::MATE;
73 if ($depth===0 && !$check) {
74 // Quiet material baseline; follow captures/promotions to avoid praising an exchange halfway through.
75 $best=max($best,$this->material($s));
76 if ($best>=$beta) return $best;
77 $alpha=max($alpha,$best);
78 $legal=array_values(array_filter($legal,fn($m)=>$s['board'][$m['to']]!=='.'||$m['promotion']!==null));
79 }
80 usort($legal,fn($a,$b)=>$this->priority($s,$b)<=>$this->priority($s,$a));
81 foreach ($legal as $m) {
82 $next=Chess::afterLegal($s,$m);
83 $score=-$this->search($next,max(0,$depth-1),$depth>0?$tactical:$tactical-1,-$beta,-$alpha,$ply+1,$evasions);
84 // The mover may also claim a draw using this intended move.
85 if (Chess::claimable($next)) $score=max(0,$score);
86 $best=max($best,$score);$alpha=max($alpha,$score);
87 if ($alpha>=$beta) break;
88 }
89 return $best;
90 }
91
92 private function priority(array $s,array $m): int
93 {
94 $victim=$s['board'][$m['to']];
95 return ($m['promotion']?self::VALUES[$m['promotion']]:0)+($victim==='.'?0:10*self::VALUES[strtolower($victim)]-self::VALUES[strtolower($s['board'][$m['from']])]);
96 }
97}
98final class FeedbackLimit extends RuntimeException {}