]> git.sesse.net Git - remoteglot/blob - Position.pm
Merge remote-tracking branch 'magne/master'
[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->{'toplay'};
195         delete $json->{'move_num'};
196         delete $json->{'board'};
197         delete $json->{'prettyprint_cache'};
198         delete $json->{'tbprobe_cache'};
199         delete $json->{'black_castle_k'};
200         delete $json->{'black_castle_q'};
201         delete $json->{'white_castle_k'};
202         delete $json->{'white_castle_q'};
203         delete $json->{'time_since_100move_rule_reset'};
204         delete $json->{'chess960'} if (!$json->{'chess960'});
205         if ($json->{'player_w'} =~ /^base64:(.*)$/) {
206                 $json->{'player_w'} = MIME::Base64::decode_base64($1);
207         }
208         if ($json->{'player_b'} =~ /^base64:(.*)$/) {
209                 $json->{'player_b'} = MIME::Base64::decode_base64($1);
210         }
211         return $json;
212 }
213
214 sub parse_pretty_move {
215         my ($pos, $move) = @_;
216         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'});
217 }
218
219 sub num_pieces {
220         my ($pos) = @_;
221         return $pos->{'board'}->num_pieces();
222 }
223
224 # Returns a new Position object.
225 sub make_move {
226         my ($pos, $from_row, $from_col, $to_row, $to_col, $promo, $pretty_move) = @_;
227
228         my $from_square = _pos_to_square($from_row, $from_col);
229         my $to_square = _pos_to_square($to_row, $to_col);
230
231         my $np = {};
232         $np->{'board'} = $pos->{'board'}->make_move($from_row, $from_col, $to_row, $to_col, $promo);
233         if ($pos->{'toplay'} eq 'W') {
234                 $np->{'toplay'} = 'B';
235                 $np->{'move_num'} = $pos->{'move_num'};
236         } else {
237                 $np->{'toplay'} = 'W';
238                 $np->{'move_num'} = $pos->{'move_num'} + 1;
239         }
240
241         my $piece = $pos->{'board'}[$from_row][$from_col];
242         my $dest_piece = $pos->{'board'}[$to_row][$to_col];
243
244         # Find out if this was a two-step pawn move.
245         if (lc($piece) eq 'p' && abs($from_row - $to_row) == 2) {
246                 $np->{'ep_file_num'} = $from_col;
247         } else {
248                 $np->{'ep_file_num'} = -1;
249         }
250
251         # Castling rights.
252         $np->{'white_castle_k'} = $pos->{'white_castle_k'};
253         $np->{'white_castle_q'} = $pos->{'white_castle_q'};
254         $np->{'black_castle_k'} = $pos->{'black_castle_k'};
255         $np->{'black_castle_q'} = $pos->{'black_castle_q'};
256         if ($piece eq 'K') {
257                 $np->{'white_castle_k'} = undef;
258                 $np->{'white_castle_q'} = undef;
259         } elsif ($piece eq 'k') {
260                 $np->{'black_castle_k'} = undef;
261                 $np->{'black_castle_q'} = undef;
262         } elsif (defined($np->{'white_castle_q'}) &&
263                  ($from_square eq ($np->{'white_castle_q'} . '1') ||
264                   $to_square   eq ($np->{'white_castle_q'} . '1'))) {
265                 $np->{'white_castle_q'} = undef;
266         } elsif (defined($np->{'white_castle_k'}) &&
267                  ($from_square eq ($np->{'white_castle_k'} . '1') ||
268                   $to_square   eq ($np->{'white_castle_k'} . '1'))) {
269                 $np->{'white_castle_k'} = undef;
270         } elsif (defined($np->{'black_castle_q'}) &&
271                  ($from_square eq ($np->{'black_castle_q'} . '8') ||
272                   $to_square   eq ($np->{'black_castle_q'} . '8'))) {
273                 $np->{'black_castle_q'} = undef;
274         } elsif (defined($np->{'black_castle_k'}) &&
275                  ($from_square eq ($np->{'black_castle_k'} . '8') ||
276                   $to_square   eq ($np->{'black_castle_k'} . '8'))) {
277                 $np->{'black_castle_k'} = undef;
278         }
279
280         # 50-move rule. Note that castle does not reset the counter, per FIDE rules.
281         my $castling = (lc($piece) eq 'k' && abs($from_col - $to_col) > 1) ||  # King moves two squares.
282                 ($piece eq 'K' && $dest_piece eq 'R') ||  # Chess960-style king-takes-rook.
283                 ($piece eq 'k' && $dest_piece eq 'r');
284         if (!$castling && (lc($piece) eq 'p' || $dest_piece ne '-')) {
285                 $np->{'time_since_100move_rule_reset'} = 0;
286         } else {
287                 $np->{'time_since_100move_rule_reset'} = $pos->{'time_since_100move_rule_reset'} + 1;
288         }
289         $np->{'player_w'} = $pos->{'player_w'};
290         $np->{'player_b'} = $pos->{'player_b'};
291         $np->{'chess960'} = $pos->{'chess960'};
292         if (exists($pos->{'start_fen'})) {
293                 $np->{'start_fen'} = $pos->{'start_fen'};
294         }
295         if (defined($pretty_move)) {
296                 $np->{'last_move'} = $pretty_move;
297         } else {
298                 my ($move, $nb) = $pos->{'board'}->prettyprint_move($from_row, $from_col, $to_row, $to_col, $promo);
299                 $np->{'last_move'} = $move;
300         }
301         $np->{'last_move_uci'} = Board::move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
302
303         return bless $np;
304 }
305
306 # Returns a new Position object, and the parsed UCI move.
307 sub make_pretty_move {
308         my ($pos, $move) = @_;
309
310         my ($from_row, $from_col, $to_row, $to_col, $promo) = $pos->parse_pretty_move($move);
311         my $uci_move = Board::move_to_uci_notation($from_row, $from_col, $to_row, $to_col, $promo);
312         $pos = $pos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
313         return ($pos, $uci_move);
314 }
315
316 sub _pos_to_square {
317         my ($row, $col) = @_;
318         return sprintf("%c%d", ord('a') + $col, 8 - $row);
319 }
320
321 sub apply_uci_pv {
322         my ($pos, @pv) = @_;
323
324         my $pvpos = $pos;
325         for my $pv_move (@pv) {
326                 my ($from_row, $from_col, $to_row, $to_col, $promo) = _parse_uci_move($pv_move);
327                 $pvpos = $pvpos->make_move($from_row, $from_col, $to_row, $to_col, $promo);
328         }
329
330         return $pvpos;
331 }
332
333 sub _col_num_to_letter {
334         my $col = shift;
335         return sprintf("%c", ord('a') + $col);
336 }
337
338 sub _col_letter_to_num {
339         return ord(shift) - ord('a');
340 }
341
342 sub _row_letter_to_num {
343         return 7 - (ord(shift) - ord('1'));
344 }
345
346 sub _find_piece_col {
347         my ($row, $piece) = @_;
348         for my $col (0..7) {
349                 return $col if ($row->[$col] eq $piece);
350         }
351         die "Could not find piece $piece";
352 }
353
354 sub _find_piece_col_from_right {
355         my ($row, $piece) = @_;
356         for my $col (reverse 0..7) {
357                 return $col if ($row->[$col] eq $piece);
358         }
359         die "Could not find piece $piece";
360 }
361
362 sub _parse_uci_move {
363         my $move = shift;
364         my $from_col = _col_letter_to_num(substr($move, 0, 1));
365         my $from_row = _row_letter_to_num(substr($move, 1, 1));
366         my $to_col   = _col_letter_to_num(substr($move, 2, 1));
367         my $to_row   = _row_letter_to_num(substr($move, 3, 1));
368         my $promo    = substr($move, 4, 1);
369         return ($from_row, $from_col, $to_row, $to_col, $promo);
370 }
371
372 1;