Fix a castling edge case in Chess960 positions where the kings start on the e-file...
[remoteglot] / Position.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 use MIME::Base64;
8
9 require 'Board.pm';
10
11 package Position;
12
13 # Takes in a FICS style 12-type position.
14 sub new {
15         my ($class, $str) = @_;
16         my $pos = {};
17         my (@x) = split / /, $str;
18
19         $pos->{'board'} = Board->new(@x[1..8]);
20         $pos->{'toplay'} = $x[9];
21         $pos->{'ep_file_num'} = $x[10];
22         $pos->{'white_castle_k'} = $x[11] ? 'h' : undef;
23         $pos->{'white_castle_q'} = $x[12] ? 'a' : undef;
24         $pos->{'black_castle_k'} = $x[13] ? 'h' : undef;
25         $pos->{'black_castle_q'} = $x[14] ? 'a' : undef;
26         $pos->{'time_since_100move_rule_reset'} = $x[15];
27         $pos->{'player_w'} = $x[17];
28         $pos->{'player_b'} = $x[18];
29         $pos->{'player_w'} =~ s/^W?[FCIG]M//;
30         $pos->{'player_b'} =~ s/^W?[FCIG]M//;
31         $pos->{'white_clock'} = $x[24];
32         $pos->{'black_clock'} = $x[25];
33         $pos->{'move_num'} = $x[26];
34         if ($x[27] =~ /([a-h][1-8])-([a-h][1-8])/) {
35                 $pos->{'last_move_uci'} = $1 . $2;
36         } else {
37                 $pos->{'last_move_uci'} = undef;
38         }
39         $pos->{'last_move'} = $x[29];
40         $pos->{'prettyprint_cache'} = {};
41         $pos->{'tbprobe_cache'} = {};
42
43         bless $pos, $class;
44         return $pos;
45 }
46
47 sub start_pos {
48         my ($class, $white, $black) = @_;
49         $white = "base64:" . MIME::Base64::encode_base64($white);
50         $black = "base64:" . MIME::Base64::encode_base64($black);
51         return $class->new("<12> rnbqkbnr pppppppp -------- -------- -------- -------- PPPPPPPP RNBQKBNR W -1 1 1 1 1 0 dummygamenum $white $black -2 dummytime dummyincrement 39 39 dummytime dummytime 1 none (0:00) none 0 0 0");
52 }
53
54 sub from_fen {
55         my ($class, $fen) = @_;
56         my ($board, $toplay, $castling, $ep_square, $halfmove_clock, $fullmove_clock) = split / /, $fen;
57
58         my $pos = {};
59         $board =~ s/(\d)/"-"x$1/ge;
60         $pos->{'board'} = Board->new(split /\//, $board);
61         $board = $pos->{'board'};
62         $pos->{'toplay'} = uc($toplay);
63
64         if ($ep_square =~ /^([a-h])/) {
65                 $pos->{'ep_file_num'} = ord($1) - ord('a');
66         } else {
67                 $pos->{'ep_file_num'} = -1;
68         }
69
70         # X-FEN castling rights parsing.
71         if ($castling =~ /K/) {
72                 $pos->{'white_castle_k'} = _col_num_to_letter(_find_piece_col_from_right($board->[7], 'R'));
73         }
74         if ($castling =~ /Q/) {
75                 $pos->{'white_castle_q'} = _col_num_to_letter(_find_piece_col($board->[7], 'R'));
76         }
77         while ($castling =~ s/([A-H])//) {
78                 my $rook_col = lc($1);
79                 my $king_col = _col_num_to_letter(_find_piece_col($board->[7], 'K'));
80                 if ($rook_col lt $king_col) {
81                         $pos->{'white_castle_q'} = $rook_col;
82                 } else {
83                         $pos->{'white_castle_k'} = $rook_col;
84                 }
85         }
86         if ($castling =~ /k/) {
87                 $pos->{'black_castle_k'} = _col_num_to_letter(_find_piece_col_from_right($board->[0], 'r'));
88         }
89         if ($castling =~ /q/) {
90                 $pos->{'black_castle_q'} = _col_num_to_letter(_find_piece_col($board->[0], 'r'));
91         }
92         while ($castling =~ s/([a-h])//) {
93                 my $rook_col = $1;
94                 my $king_col = _col_num_to_letter(_find_piece_col($board->[0], 'k'));
95                 if ($rook_col lt $king_col) {
96                         $pos->{'black_castle_q'} = $rook_col;
97                 } else {
98                         $pos->{'black_castle_k'} = $rook_col;
99                 }
100         }
101         $pos->{'time_since_100move_rule_reset'} = $halfmove_clock // 0;
102         $pos->{'player_w'} = 'white';
103         $pos->{'player_b'} = 'black';
104         $pos->{'white_clock'} = 0;
105         $pos->{'black_clock'} = 0;
106         $pos->{'move_num'} = $fullmove_clock // 0;
107         $pos->{'last_move_uci'} = undef;
108         $pos->{'last_move'} = undef;
109         $pos->{'prettyprint_cache'} = {};
110         $pos->{'tbprobe_cache'} = {};
111         
112         bless $pos, $class;
113         return $pos;
114 }
115
116 sub fen {
117         my $pos = shift;
118
119         # the board itself
120         my $fen = $pos->{'board'}->fen();
121
122         # white/black to move
123         $fen .= " ";
124         $fen .= lc($pos->{'toplay'});
125
126         # Castling (X-FEN compatible).
127         my $castling = "";
128         if (defined($pos->{'white_castle_k'})) {
129                 my $outer_rook_col = _col_num_to_letter(_find_piece_col_from_right($pos->{'board'}[7], 'R'));
130                 if ($outer_rook_col eq $pos->{'white_castle_k'}) {
131                         $castling .= "K";
132                 } else {
133                         $castling .= uc($pos->{'white_castle_k'});
134                 }
135         }
136         if (defined($pos->{'white_castle_q'})) {
137                 my $outer_rook_col = _col_num_to_letter(_find_piece_col($pos->{'board'}[7], 'R'));
138                 if ($outer_rook_col eq $pos->{'white_castle_q'}) {
139                         $castling .= "Q";
140                 } else {
141                         $castling .= uc($pos->{'white_castle_q'});
142                 }
143         }
144         if (defined($pos->{'black_castle_k'})) {
145                 my $outer_rook_col = _col_num_to_letter(_find_piece_col_from_right($pos->{'board'}[0], 'r'));
146                 if ($outer_rook_col eq $pos->{'black_castle_k'}) {
147                         $castling .= "k";
148                 } else {
149                         $castling .= $pos->{'black_castle_k'};
150                 }
151         }
152         if (defined($pos->{'black_castle_q'})) {
153                 my $outer_rook_col = _col_num_to_letter(_find_piece_col($pos->{'board'}[0], 'r'));
154                 if ($outer_rook_col eq $pos->{'black_castle_q'}) {
155                         $castling .= "q";
156                 } else {
157                         $castling .= $pos->{'black_castle_q'};
158                 }
159         }
160         $castling = "-" if ($castling eq "");
161         # $castling = "-"; # chess960
162         $fen .= " ";
163         $fen .= $castling;
164
165         # en passant
166         my $ep = "-";
167         if ($pos->{'ep_file_num'} != -1) {
168                 my $col = $pos->{'ep_file_num'};
169                 $ep = (qw(a b c d e f g h))[$col];
170
171                 if ($pos->{'toplay'} eq 'B') {
172                         $ep .= "3";
173                 } else {
174                         $ep .= "6";
175                 }
176         }
177         $fen .= " ";
178         $fen .= $ep;
179
180         # half-move clock
181         $fen .= " ";
182         $fen .= $pos->{'time_since_100move_rule_reset'};
183
184         # full-move clock
185         $fen .= " ";
186         $fen .= $pos->{'move_num'};
187
188         return $fen;
189 }
190
191 sub to_json_hash {
192         my $pos = shift;
193         my $json = { %$pos, fen => $pos->fen() };
194         delete $json->{'board'};
195         delete $json->{'prettyprint_cache'};
196         delete $json->{'tbprobe_cache'};
197         delete $json->{'black_castle_k'};
198         delete $json->{'black_castle_q'};
199         delete $json->{'white_castle_k'};
200         delete $json->{'white_castle_q'};
201         delete $json->{'time_since_100move_rule_reset'};
202         delete $json->{'chess960'} if (!$json->{'chess960'});
203         if ($json->{'player_w'} =~ /^base64:(.*)$/) {
204                 $json->{'player_w'} = MIME::Base64::decode_base64($1);
205         }
206         if ($json->{'player_b'} =~ /^base64:(.*)$/) {
207                 $json->{'player_b'} = MIME::Base64::decode_base64($1);
208         }
209         return $json;
210 }
211
212 sub parse_pretty_move {
213         my ($pos, $move) = @_;
214         return $pos->{'board'}->parse_pretty_move($move, $pos->{'toplay'}, $pos->{'chess960'}, $pos->{'white_castle_k'}, $pos->{'white_castle_q'}, $pos->{'black_castle_k'}, $pos->{'black_castle_q'});
215 }
216
217 sub num_pieces {
218         my ($pos) = @_;
219         return $pos->{'board'}->num_pieces();
220 }
221
222 # Returns a new Position object.
223 sub make_move {
224         my ($pos, $from_row, $from_col, $to_row, $to_col, $promo, $pretty_move) = @_;
225
226         my $from_square = _pos_to_square($from_row, $from_col);
227         my $to_square = _pos_to_square($to_row, $to_col);
228
229         my $np = {};
230         $np->{'board'} = $pos->{'board'}->make_move($from_row, $from_col, $to_row, $to_col, $promo);
231         if ($pos->{'toplay'} eq 'W') {
232                 $np->{'toplay'} = 'B';
233                 $np->{'move_num'} = $pos->{'move_num'};
234         } else {
235                 $np->{'toplay'} = 'W';
236                 $np->{'move_num'} = $pos->{'move_num'} + 1;
237         }
238
239         my $piece = $pos->{'board'}[$from_row][$from_col];
240         my $dest_piece = $pos->{'board'}[$to_row][$to_col];
241
242         # Find out if this was a two-step pawn move.
243         if (lc($piece) eq 'p' && abs($from_row - $to_row) == 2) {
244                 $np->{'ep_file_num'} = $from_col;
245         } else {
246                 $np->{'ep_file_num'} = -1;
247         }
248
249         # Castling rights.
250         $np->{'white_castle_k'} = $pos->{'white_castle_k'};
251         $np->{'white_castle_q'} = $pos->{'white_castle_q'};
252         $np->{'black_castle_k'} = $pos->{'black_castle_k'};
253         $np->{'black_castle_q'} = $pos->{'black_castle_q'};
254         if ($piece eq 'K') {
255                 $np->{'white_castle_k'} = undef;
256                 $np->{'white_castle_q'} = undef;
257         } elsif ($piece eq 'k') {
258                 $np->{'black_castle_k'} = undef;
259                 $np->{'black_castle_q'} = undef;
260         } elsif (defined($np->{'white_castle_q'}) &&
261                  ($from_square eq ($np->{'white_castle_q'} . '1') ||
262                   $to_square   eq ($np->{'white_castle_q'} . '1'))) {
263                 $np->{'white_castle_q'} = undef;
264         } elsif (defined($np->{'white_castle_k'}) &&
265                  ($from_square eq ($np->{'white_castle_k'} . '1') ||
266                   $to_square   eq ($np->{'white_castle_k'} . '1'))) {
267                 $np->{'white_castle_k'} = undef;
268         } elsif (defined($np->{'black_castle_q'}) &&
269                  ($from_square eq ($np->{'black_castle_q'} . '8') ||
270                   $to_square   eq ($np->{'black_castle_q'} . '8'))) {
271                 $np->{'black_castle_q'} = undef;
272         } elsif (defined($np->{'black_castle_k'}) &&
273                  ($from_square eq ($np->{'black_castle_k'} . '8') ||
274                   $to_square   eq ($np->{'black_castle_k'} . '8'))) {
275                 $np->{'black_castle_k'} = undef;
276         }
277
278         # 50-move rule. Note that castle does not reset the counter, per FIDE rules.
279         my $castling = (lc($piece) eq 'k' && abs($from_col - $to_col) > 1) ||  # King moves two squares.
280                 ($piece eq 'K' && $dest_piece eq 'R') ||  # Chess960-style king-takes-rook.
281                 ($piece eq 'k' && $dest_piece eq 'r');
282         if (!$castling && (lc($piece) eq 'p' || $dest_piece ne '-')) {
283                 $np->{'time_since_100move_rule_reset'} = 0;
284         } else {
285                 $np->{'time_since_100move_rule_reset'} = $pos->{'time_since_100move_rule_reset'} + 1;
286         }
287         $np->{'player_w'} = $pos->{'player_w'};
288         $np->{'player_b'} = $pos->{'player_b'};
289         $np->{'chess960'} = $pos->{'chess960'};
290         if (exists($pos->{'start_fen'})) {
291                 $np->{'start_fen'} = $pos->{'start_fen'};
292         }
293         if (defined($pretty_move)) {
294                 $np->{'last_move'} = $pretty_move;
295         } else {
296                 my ($move, $nb) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
297                 $np->{'last_move'} = $move;
298         }
299         $np->{'last_move_uci'} = Board::move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
300
301         return bless $np;
302 }
303
304 # Returns a new Position object, and the parsed UCI move.
305 sub make_pretty_move {
306         my ($pos, $move) = @_;
307
308         my ($from_row, $from_col, $to_row, $to_col, $promo) = $pos->parse_pretty_move($move);
309         my $uci_move = Board::move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
310         $pos = $pos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
311         return ($pos, $uci_move);
312 }
313
314 sub _pos_to_square {
315         my ($row, $col) = @_;
316         return sprintf("%c%d", ord('a') + $col, 8 - $row);
317 }
318
319 sub apply_uci_pv {
320         my ($pos, @pv) = @_;
321
322         my $pvpos = $pos;
323         for my $pv_move (@pv) {
324                 my ($from_row, $from_col, $to_row, $to_col, $promo) = _parse_uci_move($pv_move);
325                 $pvpos = $pvpos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
326         }
327
328         return $pvpos;
329 }
330
331 sub _col_num_to_letter {
332         my $col = shift;
333         return sprintf("%c", ord('a') + $col);
334 }
335
336 sub _col_letter_to_num {
337         return ord(shift) - ord('a');
338 }
339
340 sub _row_letter_to_num {
341         return 7 - (ord(shift) - ord('1'));
342 }
343
344 sub _find_piece_col {
345         my ($row, $piece) = @_;
346         for my $col (0..7) {
347                 return $col if ($row->[$col] eq $piece);
348         }
349         die "Could not find piece $piece";
350 }
351
352 sub _find_piece_col_from_right {
353         my ($row, $piece) = @_;
354         for my $col (reverse 0..7) {
355                 return $col if ($row->[$col] eq $piece);
356         }
357         die "Could not find piece $piece";
358 }
359
360 sub _parse_uci_move {
361         my $move = shift;
362         my $from_col = _col_letter_to_num(substr($move, 0, 1));
363         my $from_row = _row_letter_to_num(substr($move, 1, 1));
364         my $to_col   = _col_letter_to_num(substr($move, 2, 1));
365         my $to_row   = _row_letter_to_num(substr($move, 3, 1));
366         my $promo    = substr($move, 4, 1);
367         return ($from_row, $from_col, $to_row, $to_col, $promo);
368 }
369
370 1;