]> git.sesse.net Git - remoteglot/blob - Board.pm
Prioritize the current display line in move selection.
[remoteglot] / Board.pm
1 #! /usr/bin/perl
2 #
3 # There are too many chess modules on CPAN already, so here's another one...
4 #
5 use strict;
6 use warnings;
7
8 package Board;
9
10 sub new {
11         my ($class, @rows) = @_;
12         my $board = [];
13
14         for my $row (0..7) {
15                 for my $col (0..7) {
16                         $board->[$row][$col] = substr($rows[$row], $col, 1);
17                 }
18         }
19
20         return bless $board;
21 }
22
23 sub clone {
24         my ($board) = shift;
25         my $nb = [];
26
27         for my $row (0..7) {
28                 $nb->[$row] = [ @{$board->[$row]} ];
29         }
30
31         return bless $nb;
32 }
33
34 # Returns a new board.
35 sub make_move {
36         my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
37         my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
38         my $piece = $board->[$from_row][$from_col];
39         my $nb = $board->clone();
40
41         if ($piece eq '-') {
42                 die "Invalid move $move";
43         }
44
45         # white short castling
46         if ($move eq 'e1g1' && $piece eq 'K') {
47                 # king
48                 $nb->[7][4] = '-';
49                 $nb->[7][6] = $piece;
50
51                 # rook
52                 $nb->[7][7] = '-';
53                 $nb->[7][5] = 'R';
54
55                 return $nb;
56         }
57
58         # white long castling
59         if ($move eq 'e1c1' && $piece eq 'K') {
60                 # king
61                 $nb->[7][4] = '-';
62                 $nb->[7][2] = $piece;
63
64                 # rook
65                 $nb->[7][0] = '-';
66                 $nb->[7][3] = 'R';
67
68                 return $nb;
69         }
70
71         # black short castling
72         if ($move eq 'e8g8' && $piece eq 'k') {
73                 # king
74                 $nb->[0][4] = '-';
75                 $nb->[0][6] = $piece;
76
77                 # rook
78                 $nb->[0][7] = '-';
79                 $nb->[0][5] = 'r';
80
81                 return $nb;
82         }
83
84         # black long castling
85         if ($move eq 'e8c8' && $piece eq 'k') {
86                 # king
87                 $nb->[0][4] = '-';
88                 $nb->[0][2] = $piece;
89
90                 # rook
91                 $nb->[0][0] = '-';
92                 $nb->[0][3] = 'r';
93
94                 return $nb;
95         }
96
97         # check if the from-piece is a pawn
98         if (lc($piece) eq 'p') {
99                 # attack?
100                 if ($from_col != $to_col) {
101                         # en passant?
102                         if ($board->[$to_row][$to_col] eq '-') {
103                                 if ($piece eq 'p') {
104                                         $nb->[$to_row - 1][$to_col] = '-';
105                                 } else {
106                                         $nb->[$to_row + 1][$to_col] = '-';
107                                 }
108                         }
109                 }
110                 if (defined($promo) && $promo ne '') {
111                         if ($piece eq 'p') {
112                                 $piece = lc($promo);
113                         } else {
114                                 $piece = uc($promo);
115                         }
116                 }
117         }
118
119         # update the board
120         $nb->[$from_row][$from_col] = '-';
121         $nb->[$to_row][$to_col] = $piece;
122
123         return $nb;
124 }
125
126 sub _pos_to_square {
127         my ($row, $col) = @_;
128         return sprintf("%c%d", ord('a') + $col, 8 - $row);
129 }
130
131 sub _col_letter_to_num {
132         return ord(shift) - ord('a');
133 }
134
135 sub _row_letter_to_num {
136         return 7 - (ord(shift) - ord('1'));
137 }
138
139 sub _square_to_pos {
140         my ($square) = @_;
141         $square =~ /^([a-h])([1-8])$/ or die "Invalid square $square";  
142         return (_row_letter_to_num($2), _col_letter_to_num($1));
143 }
144
145 sub move_to_uci_notation {
146         my ($from_row, $from_col, $to_row, $to_col, $promo) = @_;
147         $promo //= "";
148         return _pos_to_square($from_row, $from_col) . _pos_to_square($to_row, $to_col) . $promo;
149 }
150
151 # Note: This is in general not a validation that the move is actually allowed
152 # (e.g. you can castle even though you're in check).
153 sub parse_pretty_move {
154         my ($board, $move, $toplay) = @_;
155
156         # Strip check or mate
157         $move =~ s/[+#]$//;
158
159         if ($move eq '0-0' or $move eq 'O-O') {
160                 if ($toplay eq 'W') {
161                         return (_square_to_pos('e1'), _square_to_pos('g1'));
162                 } else {
163                         return (_square_to_pos('e8'), _square_to_pos('g8'));
164                 }
165         } elsif ($move eq '0-0-0' or $move eq 'O-O-O') {
166                 if ($toplay eq 'W') {
167                         return (_square_to_pos('e1'), _square_to_pos('c1'));
168                 } else {
169                         return (_square_to_pos('e8'), _square_to_pos('c8'));
170                 }
171         }
172
173         # Parse promo
174         my $promo;
175         if ($move =~ s/=?([QRNB])$//) {
176                 $promo = $1;
177         }
178
179         $move =~ /^([KQRBN])?([a-h])?([1-8])?x?([a-h][1-8])$/ or die "Invalid move $move";
180         my $piece = $1;
181         my $from_col = defined($2) ? _col_letter_to_num($2) : undef;
182         my $from_row = defined($3) ? _row_letter_to_num($3) : undef;
183         if (!defined($piece) && (!defined($from_col) || !defined($from_row))) {
184                 $piece = 'P';
185         }
186         my ($to_row, $to_col) = _square_to_pos($4);
187         
188         # Find all possible from-squares that could have been meant.
189         my @squares = ();
190         my $side = 'K';
191         if ($toplay eq 'B') {
192                 $piece = lc($piece) if defined($piece);
193                 $side = 'k';
194         }
195         for my $row (0..7) {
196                 next if (defined($from_row) && $from_row != $row);
197                 for my $col (0..7) {
198                         next if (defined($from_col) && $from_col != $col);
199                         next if (defined($piece) && $board->[$row][$col] ne $piece);
200                         push @squares, [ $row, $col ];
201                 }
202         }
203         if (scalar @squares > 1) {
204                 # Filter out pieces which cannot reach this square.
205                 @squares = grep { $board->can_reach($piece, $_->[0], $_->[1], $to_row, $to_col) } @squares;
206         }
207         if (scalar @squares > 1) {
208                 # See if doing this move would put us in check
209                 # (yes, there are clients that expect us to do this).
210                 @squares = grep { !$board->make_move($_->[0], $_->[1], $to_row, $to_col, $promo)->in_check($side) } @squares;
211         }
212         if (scalar @squares == 0) {
213                 die "Impossible move $move";
214         }
215         if (scalar @squares != 1) {
216                 die "Ambigious move $move";
217         }
218         return (@{$squares[0]}, $to_row, $to_col, $promo);
219 }
220
221 sub fen {
222         my ($board) = @_;
223         my @rows = ();
224         for my $row (0..7) {
225                 my $str = join('', @{$board->[$row]});
226                 $str =~ s/(-+)/length($1)/ge;
227                 push @rows, $str;
228         }
229
230         return join('/', @rows);
231 }
232
233 # Returns a compact bit string describing the same data as fen().
234 # This is encoded using a Huffman-like encoding, and should be
235 # typically about 1/3 the number of bytes.
236 sub bitpacked_fen {
237         my ($board) = @_;
238         my $bits = "";
239
240         for my $row (0..7) {
241                 for my $col (0..7) {
242                         my $piece = $board->[$row][$col];
243                         if ($piece eq '-') {
244                                 $bits .= "0";
245                                 next;
246                         }
247
248                         my $color = (lc($piece) eq $piece) ? 0 : 1;
249                         $bits .= "1" . $color;
250
251                         if (lc($piece) eq 'p') {
252                                 $bits .= "0";
253                         } elsif (lc($piece) eq 'n') {
254                                 $bits .= "100";
255                         } elsif (lc($piece) eq 'b') {
256                                 $bits .= "101";
257                         } elsif (lc($piece) eq 'r') {
258                                 $bits .= "1110";
259                         } elsif (lc($piece) eq 'q') {
260                                 $bits .= "11110";
261                         } elsif (lc($piece) eq 'k') {
262                                 $bits .= "11111";
263                         } else {
264                                 die "Unknown piece $piece";
265                         }
266                 }
267         }
268
269         return pack('b*', $bits);
270 }
271
272 sub can_reach {
273         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
274         
275         # can't eat your own piece
276         my $dest_piece = $board->[$to_row][$to_col];
277         if ($dest_piece ne '-') {
278                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
279         }
280         
281         if ($piece eq 'p') {
282                 # black pawn
283                 if ($to_col == $from_col && $to_row == $from_row + 1) {
284                         return ($dest_piece eq '-');
285                 }
286                 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
287                         my $middle_piece = $board->[2][$to_col];
288                         return ($dest_piece eq '-' && $middle_piece eq '-');
289                 }
290                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
291                         if ($dest_piece eq '-') {
292                                 # En passant. TODO: check that the last move was indeed an EP move
293                                 return ($to_row == 5 && $board->[4][$to_col] eq 'P');
294                         } else {
295                                 return 1;
296                         }
297                 }
298                 return 0;
299         }
300         if ($piece eq 'P') {
301                 # white pawn
302                 if ($to_col == $from_col && $to_row == $from_row - 1) {
303                         return ($dest_piece eq '-');
304                 }
305                 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
306                         my $middle_piece = $board->[5][$to_col];
307                         return ($dest_piece eq '-' && $middle_piece eq '-');
308                 }
309                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
310                         if ($dest_piece eq '-') {
311                                 # En passant. TODO: check that the last move was indeed an EP move
312                                 return ($to_row == 2 && $board->[3][$to_col] eq 'p');
313                         } else {
314                                 return 1;
315                         }
316                 }
317                 return 0;
318         }
319         
320         if (lc($piece) eq 'r') {
321                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
322
323                 # check that there's a clear passage
324                 if ($from_row == $to_row) {
325                         if ($from_col > $to_col) {
326                                 ($to_col, $from_col) = ($from_col, $to_col);
327                         }
328
329                         for my $c (($from_col+1)..($to_col-1)) {
330                                 my $middle_piece = $board->[$to_row][$c];
331                                 return 0 if ($middle_piece ne '-');
332                         }
333
334                         return 1;
335                 } else {
336                         if ($from_row > $to_row) {
337                                 ($to_row, $from_row) = ($from_row, $to_row);
338                         }
339
340                         for my $r (($from_row+1)..($to_row-1)) {
341                                 my $middle_piece = $board->[$r][$to_col];
342                                 return 0 if ($middle_piece ne '-');     
343                         }
344
345                         return 1;
346                 }
347         }
348         if (lc($piece) eq 'b') {
349                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
350
351                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
352                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
353
354                 my $r = $from_row + $dr;
355                 my $c = $from_col + $dc;
356
357                 while ($r != $to_row) {
358                         my $middle_piece = $board->[$r][$c];
359                         return 0 if ($middle_piece ne '-');
360                         
361                         $r += $dr;
362                         $c += $dc;
363                 }
364
365                 return 1;
366         }
367         if (lc($piece) eq 'n') {
368                 my $diff_r = abs($from_row - $to_row);
369                 my $diff_c = abs($from_col - $to_col);
370                 return 1 if ($diff_r == 2 && $diff_c == 1);
371                 return 1 if ($diff_r == 1 && $diff_c == 2);
372                 return 0;
373         }
374         if ($piece eq 'q') {
375                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
376                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
377         }
378         if ($piece eq 'Q') {
379                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
380                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
381         }
382         if (lc($piece) eq 'k') {
383                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
384         }
385
386         # unknown piece
387         return 0;
388 }
389
390 # Like can_reach, but also checks the move doesn't put the side in check.
391 # We use this in prettyprint_move to reduce the disambiguation, because Chess.js
392 # needs moves to be in minimally disambiguated form.
393 sub can_legally_reach {
394         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
395
396         return 0 if (!can_reach($board, $piece, $from_row, $from_col, $to_row, $to_col));
397
398         my $nb = $board->make_move($from_row, $from_col, $to_row, $to_col);
399         my $side = ($piece eq lc($piece)) ? 'k' : 'K';
400
401         return !in_check($nb, $side);
402 }
403
404 my %pieces_against_side = (
405         k => { K => 1, Q => 1, R => 1, N => 1, B => 1, P => 1 },
406         K => { k => 1, q => 1, r => 1, n => 1, b => 1, p => 1 },
407 );
408
409 # Returns whether the given side (given as k or K for black and white) is in check.
410 sub in_check {
411         my ($board, $side) = @_;
412         my ($kr, $kc) = _find_piece($board, $side);
413
414         # check all pieces for the possibility of threatening this king
415         for my $row (0..7) {
416                 next unless grep { exists($pieces_against_side{$side}{$_}) } @{$board->[$row]};
417                 for my $col (0..7) {
418                         my $piece = $board->[$row][$col];
419                         next if ($piece eq '-');
420                         return 1 if ($board->can_reach($piece, $row, $col, $kr, $kc));
421                 }
422         }
423
424         return 0;
425 }
426
427 sub _find_piece {
428         my ($board, $piece) = @_;
429
430         for my $row (0..7) {
431                 next unless grep { $_ eq $piece } @{$board->[$row]};
432                 for my $col (0..7) {
433                         if ($board->[$row][$col] eq $piece) {
434                                 return ($row, $col);
435                         }
436                 }
437         }
438
439         return (undef, undef);
440 }
441
442 # Returns if the given side (given as k or K) is in mate.
443 sub in_mate {
444         my ($board, $side, $in_check) = @_;
445         return 0 if (!$in_check);
446
447         # try all possible moves for the side in check
448         for my $row (0..7) {
449                 for my $col (0..7) {
450                         my $piece = $board->[$row][$col];
451                         next if ($piece eq '-');
452
453                         if ($side eq 'K') {
454                                 next if ($piece eq lc($piece));
455                         } else {
456                                 next if ($piece eq uc($piece));
457                         }
458
459                         for my $dest_row (0..7) {
460                                 for my $dest_col (0..7) {
461                                         next if ($row == $dest_row && $col == $dest_col);
462                                         next unless ($board->can_reach($piece, $row, $col, $dest_row, $dest_col));
463
464                                         my $nb = $board->make_move($row, $col, $dest_row, $dest_col);
465                                         return 0 if (!$nb->in_check($side));
466                                 }
467                         }
468                 }
469         }
470
471         # nothing to do; mate
472         return 1;
473 }
474
475 # Returns the short algebraic form of the move, as well as the new position.
476 sub prettyprint_move {
477         my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
478         my $pretty = $board->_prettyprint_move_no_check_or_mate($from_row, $from_col, $to_row, $to_col, $promo);
479
480         my $nb = $board->make_move($from_row, $from_col, $to_row, $to_col, $promo);
481
482         my $piece = $board->[$from_row][$from_col];
483         my $other_side = (uc($piece) eq $piece) ? 'k' : 'K';
484         my $in_check = $nb->in_check($other_side);
485         if ($nb->in_mate($other_side, $in_check)) {
486                 $pretty .= '#';
487         } elsif ($in_check) {
488                 $pretty .= '+';
489         }
490         return ($pretty, $nb);
491 }
492
493 sub num_pieces {
494         my ($board) = @_;
495
496         my $num = 0;
497         for my $row (0..7) {
498                 for my $col (0..7) {
499                         my $piece = $board->[$row][$col];
500                         ++$num if ($piece ne '-');
501                 }
502         }
503         return $num;    
504 }
505
506 sub _prettyprint_move_no_check_or_mate {
507         my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
508         my $piece = $board->[$from_row][$from_col];
509         my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
510
511         if ($piece eq '-') {
512                 die "Invalid move $move";
513         }
514
515         # white short castling
516         if ($move eq 'e1g1' && $piece eq 'K') {
517                 return 'O-O';
518         }
519
520         # white long castling
521         if ($move eq 'e1c1' && $piece eq 'K') {
522                 return 'O-O-O';
523         }
524
525         # black short castling
526         if ($move eq 'e8g8' && $piece eq 'k') {
527                 return 'O-O';
528         }
529
530         # black long castling
531         if ($move eq 'e8c8' && $piece eq 'k') {
532                 return 'O-O-O';
533         }
534
535         my $pretty;
536
537         # check if the from-piece is a pawn
538         if (lc($piece) eq 'p') {
539                 # attack?
540                 if ($from_col != $to_col) {
541                         $pretty = substr($move, 0, 1) . 'x' . _pos_to_square($to_row, $to_col);
542                 } else {
543                         $pretty = _pos_to_square($to_row, $to_col);
544                 }
545
546                 if (defined($promo) && $promo ne '') {
547                         # promotion
548                         $pretty .= "=";
549                         $pretty .= uc($promo);
550                 }
551                 return $pretty;
552         }
553
554         $pretty = uc($piece);
555
556         # see how many of these pieces could go here, in all
557         my $num_total = 0;
558         for my $col (0..7) {
559                 for my $row (0..7) {
560                         next unless ($board->[$row][$col] eq $piece);
561                         ++$num_total if ($board->can_legally_reach($piece, $row, $col, $to_row, $to_col));
562                 }
563         }
564
565         # see how many of these pieces from the given row could go here
566         my $num_row = 0;
567         for my $col (0..7) {
568                 next unless ($board->[$from_row][$col] eq $piece);
569                 ++$num_row if ($board->can_legally_reach($piece, $from_row, $col, $to_row, $to_col));
570         }
571
572         # and same for columns
573         my $num_col = 0;
574         for my $row (0..7) {
575                 next unless ($board->[$row][$from_col] eq $piece);
576                 ++$num_col if ($board->can_legally_reach($piece, $row, $from_col, $to_row, $to_col));
577         }
578
579         # see if we need to disambiguate
580         if ($num_total > 1) {
581                 if ($num_col == 1) {
582                         $pretty .= substr($move, 0, 1);
583                 } elsif ($num_row == 1) {
584                         $pretty .= substr($move, 1, 1);
585                 } else {
586                         $pretty .= substr($move, 0, 2);
587                 }
588         }
589
590         # attack?
591         if ($board->[$to_row][$to_col] ne '-') {
592                 $pretty .= 'x';
593         }
594
595         $pretty .= _pos_to_square($to_row, $to_col);
596         return $pretty;
597 }
598
599 1;