]> git.sesse.net Git - remoteglot/blob - Board.pm
f20cecfea2faf2cdf2ad357c16959bcb420bfd1c
[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 != 1) {
204                 die "Ambigious or impossible move $move";
205         }
206         return (@{$squares[0]}, $to_row, $to_col, $promo);
207 }
208
209 sub fen {
210         my ($board) = @_;
211         my @rows = ();
212         for my $row (0..7) {
213                 my $str = join('', @{$board->[$row]});
214                 $str =~ s/(-+)/length($1)/ge;
215                 push @rows, $str;
216         }
217
218         return join('/', @rows);
219 }
220
221 sub can_reach {
222         my ($board, $piece, $from_row, $from_col, $to_row, $to_col) = @_;
223         
224         # can't eat your own piece
225         my $dest_piece = $board->[$to_row][$to_col];
226         if ($dest_piece ne '-') {
227                 return 0 if (($piece eq lc($piece)) == ($dest_piece eq lc($dest_piece)));
228         }
229         
230         if ($piece eq 'p') {
231                 # black pawn
232                 if ($to_col == $from_col && $to_row == $from_row + 1) {
233                         return ($dest_piece eq '-');
234                 }
235                 if ($to_col == $from_col && $from_row == 1 && $to_row == 3) {
236                         my $middle_piece = $board->[2][$to_col];
237                         return ($dest_piece eq '-' && $middle_piece eq '-');
238                 }
239                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row + 1) {
240                         if ($dest_piece eq '-') {
241                                 # En passant. TODO: check that the last move was indeed an EP move
242                                 return ($to_row == 5 && $board->[4][$to_col] eq 'P');
243                         } else {
244                                 return 1;
245                         }
246                 }
247                 return 0;
248         }
249         if ($piece eq 'P') {
250                 # white pawn
251                 if ($to_col == $from_col && $to_row == $from_row - 1) {
252                         return ($dest_piece eq '-');
253                 }
254                 if ($to_col == $from_col && $from_row == 6 && $to_row == 4) {
255                         my $middle_piece = $board->[5][$to_col];
256                         return ($dest_piece eq '-' && $middle_piece eq '-');
257                 }
258                 if (abs($to_col - $from_col) == 1 && $to_row == $from_row - 1) {
259                         if ($dest_piece eq '-') {
260                                 # En passant. TODO: check that the last move was indeed an EP move
261                                 return ($to_row == 2 && $board->[3][$to_col] eq 'p');
262                         } else {
263                                 return 1;
264                         }
265                 }
266                 return 0;
267         }
268         
269         if (lc($piece) eq 'r') {
270                 return 0 unless ($from_row == $to_row || $from_col == $to_col);
271
272                 # check that there's a clear passage
273                 if ($from_row == $to_row) {
274                         if ($from_col > $to_col) {
275                                 ($to_col, $from_col) = ($from_col, $to_col);
276                         }
277
278                         for my $c (($from_col+1)..($to_col-1)) {
279                                 my $middle_piece = $board->[$to_row][$c];
280                                 return 0 if ($middle_piece ne '-');
281                         }
282
283                         return 1;
284                 } else {
285                         if ($from_row > $to_row) {
286                                 ($to_row, $from_row) = ($from_row, $to_row);
287                         }
288
289                         for my $r (($from_row+1)..($to_row-1)) {
290                                 my $middle_piece = $board->[$r][$to_col];
291                                 return 0 if ($middle_piece ne '-');     
292                         }
293
294                         return 1;
295                 }
296         }
297         if (lc($piece) eq 'b') {
298                 return 0 unless (abs($from_row - $to_row) == abs($from_col - $to_col));
299
300                 my $dr = ($to_row - $from_row) / abs($to_row - $from_row);
301                 my $dc = ($to_col - $from_col) / abs($to_col - $from_col);
302
303                 my $r = $from_row + $dr;
304                 my $c = $from_col + $dc;
305
306                 while ($r != $to_row) {
307                         my $middle_piece = $board->[$r][$c];
308                         return 0 if ($middle_piece ne '-');
309                         
310                         $r += $dr;
311                         $c += $dc;
312                 }
313
314                 return 1;
315         }
316         if (lc($piece) eq 'n') {
317                 my $diff_r = abs($from_row - $to_row);
318                 my $diff_c = abs($from_col - $to_col);
319                 return 1 if ($diff_r == 2 && $diff_c == 1);
320                 return 1 if ($diff_r == 1 && $diff_c == 2);
321                 return 0;
322         }
323         if ($piece eq 'q') {
324                 return (can_reach($board, 'r', $from_row, $from_col, $to_row, $to_col) ||
325                         can_reach($board, 'b', $from_row, $from_col, $to_row, $to_col));
326         }
327         if ($piece eq 'Q') {
328                 return (can_reach($board, 'R', $from_row, $from_col, $to_row, $to_col) ||
329                         can_reach($board, 'B', $from_row, $from_col, $to_row, $to_col));
330         }
331         if (lc($piece) eq 'k') {
332                 return (abs($from_row - $to_row) <= 1 && abs($from_col - $to_col) <= 1);
333         }
334
335         # unknown piece
336         return 0;
337 }
338
339 my %pieces_against_side = (
340         k => { K => 1, Q => 1, R => 1, N => 1, B => 1, P => 1 },
341         K => { k => 1, q => 1, r => 1, n => 1, b => 1, p => 1 },
342 );
343
344 # Returns whether the given side (given as k or K for black and white) is in check.
345 sub in_check {
346         my ($board, $side) = @_;
347         my ($kr, $kc) = _find_piece($board, $side);
348
349         # check all pieces for the possibility of threatening this king
350         for my $row (0..7) {
351                 next unless grep { exists($pieces_against_side{$side}{$_}) } @{$board->[$row]};
352                 for my $col (0..7) {
353                         my $piece = $board->[$row][$col];
354                         next if ($piece eq '-');
355                         return 1 if ($board->can_reach($piece, $row, $col, $kr, $kc));
356                 }
357         }
358
359         return 0;
360 }
361
362 sub _find_piece {
363         my ($board, $piece) = @_;
364
365         for my $row (0..7) {
366                 next unless grep { $_ eq $piece } @{$board->[$row]};
367                 for my $col (0..7) {
368                         if ($board->[$row][$col] eq $piece) {
369                                 return ($row, $col);
370                         }
371                 }
372         }
373
374         return (undef, undef);
375 }
376
377 # Returns if the given side (given as k or K) is in mate.
378 sub in_mate {
379         my ($board, $side, $in_check) = @_;
380         return 0 if (!$in_check);
381
382         # try all possible moves for the side in check
383         for my $row (0..7) {
384                 for my $col (0..7) {
385                         my $piece = $board->[$row][$col];
386                         next if ($piece eq '-');
387
388                         if ($side eq 'K') {
389                                 next if ($piece eq lc($piece));
390                         } else {
391                                 next if ($piece eq uc($piece));
392                         }
393
394                         for my $dest_row (0..7) {
395                                 for my $dest_col (0..7) {
396                                         next if ($row == $dest_row && $col == $dest_col);
397                                         next unless ($board->can_reach($piece, $row, $col, $dest_row, $dest_col));
398
399                                         my $nb = $board->make_move($row, $col, $dest_row, $dest_col);
400                                         return 0 if (!$nb->in_check($side));
401                                 }
402                         }
403                 }
404         }
405
406         # nothing to do; mate
407         return 1;
408 }
409
410 # Returns the short algebraic form of the move, as well as the new position.
411 sub prettyprint_move {
412         my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
413         my $pretty = $board->_prettyprint_move_no_check_or_mate($from_row, $from_col, $to_row, $to_col, $promo);
414
415         my $nb = $board->make_move($from_row, $from_col, $to_row, $to_col, $promo);
416
417         my $piece = $board->[$from_row][$from_col];
418         my $other_side = (uc($piece) eq $piece) ? 'k' : 'K';
419         my $in_check = $nb->in_check($other_side);
420         if ($nb->in_mate($other_side, $in_check)) {
421                 $pretty .= '#';
422         } elsif ($in_check) {
423                 $pretty .= '+';
424         }
425         return ($pretty, $nb);
426 }
427
428 sub _prettyprint_move_no_check_or_mate {
429         my ($board, $from_row, $from_col, $to_row, $to_col, $promo) = @_;
430         my $piece = $board->[$from_row][$from_col];
431         my $move = move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
432
433         if ($piece eq '-') {
434                 die "Invalid move $move";
435         }
436
437         # white short castling
438         if ($move eq 'e1g1' && $piece eq 'K') {
439                 return '0-0';
440         }
441
442         # white long castling
443         if ($move eq 'e1c1' && $piece eq 'K') {
444                 return '0-0-0';
445         }
446
447         # black short castling
448         if ($move eq 'e8g8' && $piece eq 'k') {
449                 return '0-0';
450         }
451
452         # black long castling
453         if ($move eq 'e8c8' && $piece eq 'k') {
454                 return '0-0-0';
455         }
456
457         my $pretty;
458
459         # check if the from-piece is a pawn
460         if (lc($piece) eq 'p') {
461                 # attack?
462                 if ($from_col != $to_col) {
463                         $pretty = substr($move, 0, 1) . 'x' . _pos_to_square($to_row, $to_col);
464                 } else {
465                         $pretty = _pos_to_square($to_row, $to_col);
466
467                         if (defined($promo) && $promo ne '') {
468                                 # promotion
469                                 $pretty .= "=";
470                                 $pretty .= $promo;
471                         }
472                 }
473                 return $pretty;
474         }
475
476         $pretty = uc($piece);
477
478         # see how many of these pieces could go here, in all
479         my $num_total = 0;
480         for my $col (0..7) {
481                 for my $row (0..7) {
482                         next unless ($board->[$row][$col] eq $piece);
483                         ++$num_total if ($board->can_reach($piece, $row, $col, $to_row, $to_col));
484                 }
485         }
486
487         # see how many of these pieces from the given row could go here
488         my $num_row = 0;
489         for my $col (0..7) {
490                 next unless ($board->[$from_row][$col] eq $piece);
491                 ++$num_row if ($board->can_reach($piece, $from_row, $col, $to_row, $to_col));
492         }
493
494         # and same for columns
495         my $num_col = 0;
496         for my $row (0..7) {
497                 next unless ($board->[$row][$from_col] eq $piece);
498                 ++$num_col if ($board->can_reach($piece, $row, $from_col, $to_row, $to_col));
499         }
500
501         # see if we need to disambiguate
502         if ($num_total > 1) {
503                 if ($num_col == 1) {
504                         $pretty .= substr($move, 0, 1);
505                 } elsif ($num_row == 1) {
506                         $pretty .= substr($move, 1, 1);
507                 } else {
508                         $pretty .= substr($move, 0, 2);
509                 }
510         }
511
512         # attack?
513         if ($board->[$to_row][$to_col] ne '-') {
514                 $pretty .= 'x';
515         }
516
517         $pretty .= _pos_to_square($to_row, $to_col);
518         return $pretty;
519 }
520
521 1;