]> git.sesse.net Git - remoteglot/blob - Board.pm
A little serve-analysis bugfix I forgot to commit.
[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 sub parse_pretty_move {
152         my ($board, $move, $toplay) = @_;
153
154         # Strip check or mate
155         $move =~ s/[+#]$//;
156
157         if ($move eq '0-0' or $move eq 'O-O') {
158                 if ($toplay eq 'W') {
159                         return (_square_to_pos('e1'), _square_to_pos('g1'));
160                 } else {
161                         return (_square_to_pos('e8'), _square_to_pos('g8'));
162                 }
163         } elsif ($move eq '0-0-0' or $move eq 'O-O-O') {
164                 if ($toplay eq 'W') {
165                         return (_square_to_pos('e1'), _square_to_pos('c1'));
166                 } else {
167                         return (_square_to_pos('e8'), _square_to_pos('c8'));
168                 }
169         }
170
171         # Parse promo
172         my $promo;
173         if ($move =~ s/=?([QRNB])$//) {
174                 $promo = $1;
175         }
176
177         $move =~ /^([KQRBN])?([a-h])?([1-8])?x?([a-h][1-8])$/ or die "Invalid move $move";
178         my $piece = $1 // 'P';
179         my $from_col = defined($2) ? _col_letter_to_num($2) : undef;
180         my $from_row = defined($3) ? _row_letter_to_num($3) : undef;
181         my ($to_row, $to_col) = _square_to_pos($4);
182         
183         # Find all possible from-squares that could have been meant.
184         my @squares = ();
185         my $side = 'K';
186         if ($toplay eq 'B') {
187                 $piece = lc($piece);
188                 $side = 'k';
189         }
190         for my $row (0..7) {
191                 next if (defined($from_row) && $from_row != $row);
192                 for my $col (0..7) {
193                         next if (defined($from_col) && $from_col != $col);
194                         next if ($board->[$row][$col] ne $piece);
195                         next if (!$board->can_reach($piece, $row, $col, $to_row, $to_col));
196
197                         # See if doing this move would put us in check
198                         # (yes, there are clients that expect us to do this).
199                         next if ($board->make_move($row, $col, $to_row, $to_col, $promo)->in_check($side));
200                         push @squares, [ $row, $col ];
201                 }
202         }
203         if (scalar @squares == 0) {
204                 die "Impossible move $move";
205         }
206         if (scalar @squares != 1) {
207                 die "Ambigious move $move";
208         }
209         return (@{$squares[0]}, $to_row, $to_col, $promo);
210 }
211
212 sub fen {
213         my ($board) = @_;
214         my @rows = ();
215         for my $row (0..7) {
216                 my $str = join('', @{$board->[$row]});
217                 $str =~ s/(-+)/length($1)/ge;
218                 push @rows, $str;
219         }
220
221         return join('/', @rows);
222 }
223
224 # Returns a compact bit string describing the same data as fen().
225 # This is encoded using a Huffman-like encoding, and should be
226 # typically about 1/3 the number of bytes.
227 sub bitpacked_fen {
228         my ($board) = @_;
229         my $bits = "";
230
231         for my $row (0..7) {
232                 for my $col (0..7) {
233                         my $piece = $board->[$row][$col];
234                         if ($piece eq '-') {
235                                 $bits .= "0";
236                                 next;
237                         }
238
239                         my $color = (lc($piece) eq $piece) ? 0 : 1;
240                         $bits .= "1" . $color;
241
242                         if (lc($piece) eq 'p') {
243                                 $bits .= "0";
244                         } elsif (lc($piece) eq 'n') {
245                                 $bits .= "100";
246                         } elsif (lc($piece) eq 'b') {
247                                 $bits .= "101";
248                         } elsif (lc($piece) eq 'r') {
249                                 $bits .= "1110";
250                         } elsif (lc($piece) eq 'q') {
251                                 $bits .= "11110";
252                         } elsif (lc($piece) eq 'k') {
253                                 $bits .= "11111";
254                         } else {
255                                 die "Unknown piece $piece";
256                         }
257                 }
258         }
259
260         return pack('b*', $bits);
261 }
262
263 sub can_reach {
264         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
265         
266         # can't eat your own piece
267         my $dest_piece = $board->[$to_row][$to_col];
268         if ($dest_piece ne '-') {
269                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
270         }
271         
272         if ($piece eq 'p') {
273                 # black pawn
274                 if ($to_col == $from_col && $to_row == $from_row + 1) {
275                         return ($dest_piece eq '-');
276                 }
277                 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
278                         my $middle_piece = $board->[2][$to_col];
279                         return ($dest_piece eq '-' && $middle_piece eq '-');
280                 }
281                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
282                         if ($dest_piece eq '-') {
283                                 # En passant. TODO: check that the last move was indeed an EP move
284                                 return ($to_row == 5 && $board->[4][$to_col] eq 'P');
285                         } else {
286                                 return 1;
287                         }
288                 }
289                 return 0;
290         }
291         if ($piece eq 'P') {
292                 # white pawn
293                 if ($to_col == $from_col && $to_row == $from_row - 1) {
294                         return ($dest_piece eq '-');
295                 }
296                 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
297                         my $middle_piece = $board->[5][$to_col];
298                         return ($dest_piece eq '-' && $middle_piece eq '-');
299                 }
300                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
301                         if ($dest_piece eq '-') {
302                                 # En passant. TODO: check that the last move was indeed an EP move
303                                 return ($to_row == 2 && $board->[3][$to_col] eq 'p');
304                         } else {
305                                 return 1;
306                         }
307                 }
308                 return 0;
309         }
310         
311         if (lc($piece) eq 'r') {
312                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
313
314                 # check that there's a clear passage
315                 if ($from_row == $to_row) {
316                         if ($from_col > $to_col) {
317                                 ($to_col, $from_col) = ($from_col, $to_col);
318                         }
319
320                         for my $c (($from_col+1)..($to_col-1)) {
321                                 my $middle_piece = $board->[$to_row][$c];
322                                 return 0 if ($middle_piece ne '-');
323                         }
324
325                         return 1;
326                 } else {
327                         if ($from_row > $to_row) {
328                                 ($to_row, $from_row) = ($from_row, $to_row);
329                         }
330
331                         for my $r (($from_row+1)..($to_row-1)) {
332                                 my $middle_piece = $board->[$r][$to_col];
333                                 return 0 if ($middle_piece ne '-');     
334                         }
335
336                         return 1;
337                 }
338         }
339         if (lc($piece) eq 'b') {
340                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
341
342                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
343                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
344
345                 my $r = $from_row + $dr;
346                 my $c = $from_col + $dc;
347
348                 while ($r != $to_row) {
349                         my $middle_piece = $board->[$r][$c];
350                         return 0 if ($middle_piece ne '-');
351                         
352                         $r += $dr;
353                         $c += $dc;
354                 }
355
356                 return 1;
357         }
358         if (lc($piece) eq 'n') {
359                 my $diff_r = abs($from_row - $to_row);
360                 my $diff_c = abs($from_col - $to_col);
361                 return 1 if ($diff_r == 2 && $diff_c == 1);
362                 return 1 if ($diff_r == 1 && $diff_c == 2);
363                 return 0;
364         }
365         if ($piece eq 'q') {
366                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
367                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
368         }
369         if ($piece eq 'Q') {
370                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
371                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
372         }
373         if (lc($piece) eq 'k') {
374                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
375         }
376
377         # unknown piece
378         return 0;
379 }
380
381 my %pieces_against_side = (
382         k => { K => 1, Q => 1, R => 1, N => 1, B => 1, P => 1 },
383         K => { k => 1, q => 1, r => 1, n => 1, b => 1, p => 1 },
384 );
385
386 # Returns whether the given side (given as k or K for black and white) is in check.
387 sub in_check {
388         my ($board, $side) = @_;
389         my ($kr, $kc) = _find_piece($board, $side);
390
391         # check all pieces for the possibility of threatening this king
392         for my $row (0..7) {
393                 next unless grep { exists($pieces_against_side{$side}{$_}) } @{$board->[$row]};
394                 for my $col (0..7) {
395                         my $piece = $board->[$row][$col];
396                         next if ($piece eq '-');
397                         return 1 if ($board->can_reach($piece, $row, $col, $kr, $kc));
398                 }
399         }
400
401         return 0;
402 }
403
404 sub _find_piece {
405         my ($board, $piece) = @_;
406
407         for my $row (0..7) {
408                 next unless grep { $_ eq $piece } @{$board->[$row]};
409                 for my $col (0..7) {
410                         if ($board->[$row][$col] eq $piece) {
411                                 return ($row, $col);
412                         }
413                 }
414         }
415
416         return (undef, undef);
417 }
418
419 # Returns if the given side (given as k or K) is in mate.
420 sub in_mate {
421         my ($board, $side, $in_check) = @_;
422         return 0 if (!$in_check);
423
424         # try all possible moves for the side in check
425         for my $row (0..7) {
426                 for my $col (0..7) {
427                         my $piece = $board->[$row][$col];
428                         next if ($piece eq '-');
429
430                         if ($side eq 'K') {
431                                 next if ($piece eq lc($piece));
432                         } else {
433                                 next if ($piece eq uc($piece));
434                         }
435
436                         for my $dest_row (0..7) {
437                                 for my $dest_col (0..7) {
438                                         next if ($row == $dest_row && $col == $dest_col);
439                                         next unless ($board->can_reach($piece, $row, $col, $dest_row, $dest_col));
440
441                                         my $nb = $board->make_move($row, $col, $dest_row, $dest_col);
442                                         return 0 if (!$nb->in_check($side));
443                                 }
444                         }
445                 }
446         }
447
448         # nothing to do; mate
449         return 1;
450 }
451
452 # Returns the short algebraic form of the move, as well as the new position.
453 sub prettyprint_move {
454         my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
455         my $pretty = $board->_prettyprint_move_no_check_or_mate($from_row, $from_col, $to_row, $to_col, $promo);
456
457         my $nb = $board->make_move($from_row, $from_col, $to_row, $to_col, $promo);
458
459         my $piece = $board->[$from_row][$from_col];
460         my $other_side = (uc($piece) eq $piece) ? 'k' : 'K';
461         my $in_check = $nb->in_check($other_side);
462         if ($nb->in_mate($other_side, $in_check)) {
463                 $pretty .= '#';
464         } elsif ($in_check) {
465                 $pretty .= '+';
466         }
467         return ($pretty, $nb);
468 }
469
470 sub num_pieces {
471         my ($board) = @_;
472
473         my $num = 0;
474         for my $row (0..7) {
475                 for my $col (0..7) {
476                         my $piece = $board->[$row][$col];
477                         ++$num if ($piece ne '-');
478                 }
479         }
480         return $num;    
481 }
482
483 sub _prettyprint_move_no_check_or_mate {
484         my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
485         my $piece = $board->[$from_row][$from_col];
486         my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
487
488         if ($piece eq '-') {
489                 die "Invalid move $move";
490         }
491
492         # white short castling
493         if ($move eq 'e1g1' && $piece eq 'K') {
494                 return '0-0';
495         }
496
497         # white long castling
498         if ($move eq 'e1c1' && $piece eq 'K') {
499                 return '0-0-0';
500         }
501
502         # black short castling
503         if ($move eq 'e8g8' && $piece eq 'k') {
504                 return '0-0';
505         }
506
507         # black long castling
508         if ($move eq 'e8c8' && $piece eq 'k') {
509                 return '0-0-0';
510         }
511
512         my $pretty;
513
514         # check if the from-piece is a pawn
515         if (lc($piece) eq 'p') {
516                 # attack?
517                 if ($from_col != $to_col) {
518                         $pretty = substr($move, 0, 1) . 'x' . _pos_to_square($to_row, $to_col);
519                 } else {
520                         $pretty = _pos_to_square($to_row, $to_col);
521
522                         if (defined($promo) && $promo ne '') {
523                                 # promotion
524                                 $pretty .= "=";
525                                 $pretty .= uc($promo);
526                         }
527                 }
528                 return $pretty;
529         }
530
531         $pretty = uc($piece);
532
533         # see how many of these pieces could go here, in all
534         my $num_total = 0;
535         for my $col (0..7) {
536                 for my $row (0..7) {
537                         next unless ($board->[$row][$col] eq $piece);
538                         ++$num_total if ($board->can_reach($piece, $row, $col, $to_row, $to_col));
539                 }
540         }
541
542         # see how many of these pieces from the given row could go here
543         my $num_row = 0;
544         for my $col (0..7) {
545                 next unless ($board->[$from_row][$col] eq $piece);
546                 ++$num_row if ($board->can_reach($piece, $from_row, $col, $to_row, $to_col));
547         }
548
549         # and same for columns
550         my $num_col = 0;
551         for my $row (0..7) {
552                 next unless ($board->[$row][$from_col] eq $piece);
553                 ++$num_col if ($board->can_reach($piece, $row, $from_col, $to_row, $to_col));
554         }
555
556         # see if we need to disambiguate
557         if ($num_total > 1) {
558                 if ($num_col == 1) {
559                         $pretty .= substr($move, 0, 1);
560                 } elsif ($num_row == 1) {
561                         $pretty .= substr($move, 1, 1);
562                 } else {
563                         $pretty .= substr($move, 0, 2);
564                 }
565         }
566
567         # attack?
568         if ($board->[$to_row][$to_col] ne '-') {
569                 $pretty .= 'x';
570         }
571
572         $pretty .= _pos_to_square($to_row, $to_col);
573         return $pretty;
574 }
575
576 1;