]> git.cworth.org Git - loudgame/blob - loa-board.c
Export and document loa_board_move_is_legal
[loudgame] / loa-board.c
1 /*
2  * Copyright (C) 2008 Carl Worth
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see http://www.gnu.org/licenses/ .
16  *
17  * Author: Carl Worth <cworth@cworth.org>
18  */
19
20 #include <stdio.h>
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <assert.h>
24 #include <string.h>
25 #include <ctype.h>
26
27 #include <glib.h>
28
29 #include "loa-board.h"
30
31 static loa_bool_t
32 loa_move_is_valid (const loa_move_t *move)
33 {
34     return (move->x1 >= 0 && move->x1 < LOA_BOARD_SIZE &&
35             move->y1 >= 0 && move->y1 < LOA_BOARD_SIZE &&
36             move->x2 >= 0 && move->x2 < LOA_BOARD_SIZE &&
37             move->y2 >= 0 && move->y2 < LOA_BOARD_SIZE);
38 }
39
40 const char *
41 loa_move_to_string (const loa_move_t *move)
42 {
43 #define LOA_MOVE_STRING_SIZE 6
44     static char move_string[LOA_MOVE_STRING_SIZE];
45
46     if (! loa_move_is_valid (move)) {
47         strcpy (move_string, "***");
48         return move_string;
49     }
50
51     snprintf (move_string, LOA_MOVE_STRING_SIZE,
52               "%c%d%c%c%d",
53               'a' + move->x1, LOA_BOARD_SIZE - move->y1,
54               move->is_capture ? 'x' : '-',
55               'a' + move->x2, LOA_BOARD_SIZE - move->y2);
56
57     return move_string;
58 }
59
60 loa_bool_t
61 loa_move_init_from_string (loa_move_t *move, const char *string)
62 {
63     char xc1, xc2, sep;
64     int x1, y1, x2, y2;
65     int matched;
66
67     /* Avoid returning uninitialized data on error. */
68     move->x1 = 0;
69     move->y1 = 0;
70     move->x2 = 0;
71     move->y2 = 0;
72     move->is_capture = 0;
73
74     matched = sscanf (string, "%c%d%c%c%d", &xc1, &y1, &sep, &xc2, &y2);
75     if (matched != 5)
76         return FALSE;
77
78     x1 = tolower (xc1) - 'a';
79     x2 = tolower (xc2) - 'a';
80     y1 = LOA_BOARD_SIZE - y1;
81     y2 = LOA_BOARD_SIZE - y2;
82
83     if (x1 < 0 || x1 >= LOA_BOARD_SIZE ||
84         y1 < 0 || y1 >= LOA_BOARD_SIZE ||
85         x2 < 0 || x2 >= LOA_BOARD_SIZE ||
86         y2 < 0 || y2 >= LOA_BOARD_SIZE)
87     {
88         return FALSE;
89     }
90
91     if (sep != '-' && sep != 'x' && sep != 'X')
92         return FALSE;
93
94     move->x1 = x1;
95     move->y1 = y1;
96     move->x2 = x2;
97     move->y2 = y2;
98
99     if (sep == 'x' || sep == 'X')
100         move->is_capture = TRUE;
101     else
102         move->is_capture = FALSE;
103
104     return TRUE;
105 }
106
107 /* Given an (x,y) position on the board, return the index of the array
108  * used to count pieces in diagonal rows running from upper-left to
109  * lower-right, (like a grave accent: à or like a backslash: \).
110  *
111  * This is the array to look into when a move occurs with dx and dy of
112  * the same sign. */
113 static int
114 _grave_index (int x, int y)
115 {
116     return x - y + LOA_BOARD_SIZE - 1;
117 }
118
119 /* Given an (x,y) position on the board, return the index of the array
120  * used to count pieces in diagonal rows running from lower-left to
121  * upper-right, (like an acute accent: á or like a forward slash: /).
122  *
123  * This is the array to look into when a move occurs with dx and dy of
124  * opposite sign, (one positive, one negative). */
125 static int
126 _acute_index (int x, int y)
127 {
128     return x + y;
129 }
130
131 static void
132 loa_board_add_piece (loa_board_t *board, int x, int y, loa_cell_t cell)
133 {
134     assert (cell == LOA_CELL_BLACK || cell == LOA_CELL_WHITE);
135     assert (board->cells[x][y] == LOA_CELL_EMPTY);
136
137     board->col_pieces[x]++;
138     board->row_pieces[y]++;
139     board->diag_grave_pieces[_grave_index (x, y)]++;
140     board->diag_acute_pieces[_acute_index (x, y)]++;
141
142     board->num_pieces[cell]++;
143
144     board->cells[x][y] = cell;
145 }
146
147 static loa_cell_t
148 loa_board_remove_piece (loa_board_t *board, int x, int y)
149 {
150     loa_cell_t cell;
151
152     cell = board->cells[x][y];
153
154     if (cell == LOA_CELL_EMPTY)
155         return LOA_CELL_EMPTY;
156
157     board->col_pieces[x]--;
158     board->row_pieces[y]--;
159     board->diag_grave_pieces[_grave_index (x, y)]--;
160     board->diag_acute_pieces[_acute_index (x, y)]--;
161
162     board->num_pieces[cell]--;
163
164     board->cells[x][y] = LOA_CELL_EMPTY;
165
166     return cell;
167 }
168
169 void
170 loa_board_init (loa_board_t *board)
171 {
172     board->moves = NULL;
173     board->moves_size = 0;
174
175     loa_board_reset (board);
176 }
177
178 void
179 loa_board_fini (loa_board_t *board)
180 {
181     if (board->moves)
182         free (board->moves);
183 }
184
185 void
186 loa_board_reset (loa_board_t *board)
187 {
188     int i, x, y;
189
190     for (x = 0; x < LOA_BOARD_SIZE; x++)
191         for (y = 0; y < LOA_BOARD_SIZE; y++)
192             board->cells[x][y] = LOA_CELL_EMPTY;
193
194     board->num_pieces[LOA_CELL_BLACK] = 0;
195     board->num_pieces[LOA_CELL_WHITE] = 0;
196
197     for (i = 0; i < LOA_BOARD_SIZE; i++) {
198         board->row_pieces[i] = 0;
199         board->col_pieces[i] = 0;
200     }
201
202     for (i = 0; i < LOA_DIAG_ARRAY_SIZE; i++) {
203         board->diag_grave_pieces[i] = 0;
204         board->diag_acute_pieces[i] = 0;
205     }
206
207     for (i = 1; i < LOA_BOARD_SIZE - 1; i++) {
208         loa_board_add_piece (board, i, 0, LOA_CELL_BLACK);
209         loa_board_add_piece (board, i, LOA_BOARD_SIZE - 1, LOA_CELL_BLACK);
210         loa_board_add_piece (board, 0, i, LOA_CELL_WHITE);
211         loa_board_add_piece (board, LOA_BOARD_SIZE - 1, i, LOA_CELL_WHITE);
212     }
213
214     /* Leave board->moves and board->moves_size as allocated */
215     board->num_moves = 0;
216
217     board->player = LOA_PLAYER_BLACK;
218 }
219
220 static int
221 loa_board_group_size_recursive (loa_board_t *board, int x, int y,
222                                 loa_cell_t cell,
223                                 uint64_t *visited)
224 {
225     uint64_t bit;
226
227     if (x < 0 || y < 0)
228         return 0;
229
230     if (x >= LOA_BOARD_SIZE || y >= LOA_BOARD_SIZE)
231         return 0;
232
233     bit = 1ll << (x * LOA_BOARD_SIZE + y);
234     if (*visited & bit)
235         return 0;
236
237     *visited |= bit;
238
239     if (board->cells[x][y] != cell)
240         return 0;
241
242     return 1 +
243         loa_board_group_size_recursive (board, x-1, y-1, cell, visited) +
244         loa_board_group_size_recursive (board, x-1, y  , cell, visited) +
245         loa_board_group_size_recursive (board, x-1, y+1, cell, visited) +
246         loa_board_group_size_recursive (board, x  , y-1, cell, visited) +
247         loa_board_group_size_recursive (board, x  , y  , cell, visited) +
248         loa_board_group_size_recursive (board, x  , y+1, cell, visited) +
249         loa_board_group_size_recursive (board, x+1, y-1, cell, visited) +
250         loa_board_group_size_recursive (board, x+1, y  , cell, visited) +
251         loa_board_group_size_recursive (board, x+1, y+1, cell, visited);
252 }
253
254 static int
255 loa_board_group_size (loa_board_t *board, int x, int y)
256 {
257     uint64_t visited = 0ll;
258     loa_cell_t cell = board->cells[x][y];
259
260     return loa_board_group_size_recursive (board, x, y, cell, &visited);
261 }
262
263 int
264 loa_board_is_won (loa_board_t *board, int x, int y)
265 {
266     loa_cell_t cell = board->cells[x][y];
267
268     if (cell == LOA_CELL_EMPTY)
269         return 0;
270
271     if (loa_board_group_size (board, x, y) == board->num_pieces[cell])
272         return 1;
273
274     return 0;
275 }
276
277 loa_bool_t
278 loa_board_move_is_legal (loa_board_t     *board,
279                          loa_move_t      *move,
280                          char           **error)
281 {
282     int x, y;
283     int x1, y1, x2, y2;
284     int dx, dy;
285     int step_x, step_y;
286
287     if (! loa_move_is_valid (move))
288     {
289         *error = "Invalid coordinates (not on board)";
290         return FALSE;
291     }
292
293     x1 = move->x1;
294     y1 = move->y1;
295     x2 = move->x2;
296     y2 = move->y2;
297
298     if (board->cells[x1][y1] == LOA_CELL_EMPTY) {
299         *error = "There is no piece there to move";
300         return FALSE;
301     }
302
303     if (board->cells[x1][y1] != board->player) {
304         *error = "You cannot move your opponent's piece";
305         return FALSE;
306     }
307
308     if (board->cells[x2][y2] == board->cells[x1][y1]) {
309         *error = "You cannot capture your own piece";
310         return FALSE;
311     }
312
313     if (board->cells[x2][y2] == LOA_CELL_EMPTY)
314         move->is_capture = FALSE;
315     else
316         move->is_capture = TRUE;
317
318     dx = x2 - x1;
319     dy = y2 - y1;
320
321     /* Here's the meat of Lines of Action legaility: Does the distance
322      * moved exactly match the number of pieces (of either color) in
323      * the row, column, or diagonal of the movement. */
324     if (dx == 0) { 
325         /* Column */
326         if (abs (dy) != board->col_pieces[x1]) {
327             *error = "The move distance does not match the number of pieces in that column";
328             return FALSE;
329         }
330     } else if (dy == 0) {
331         /* Row */
332         if (abs (dx) != board->row_pieces[y1]) {
333             *error = "The move distance does not match the number of pieces in that row";
334             return FALSE;
335         }
336     } else {
337         if (abs (dx) != abs (dy)) {
338             *error = "That move is not in a row, column, or diagonal";
339             return FALSE;
340         }
341         /* Diagonal */
342         if ((dx > 0) == (dy > 0)) {
343             if (abs (dx) != board->diag_grave_pieces[_grave_index (x1, y1)]) {
344                 *error = "The move distance does not match the number of pieces in that diagonal";
345                 return FALSE;
346             }
347         } else {
348             if (abs (dx) != board->diag_acute_pieces[_acute_index (x1, y1)]) {
349                 *error = "The move distance does not match the number of pieces in that diagonal";
350                 return FALSE;
351             }
352         }
353     }
354
355     /* Finally, we have to ensure that no opponent pieces are being
356      * jumped. */
357     step_x = dx ? ((dx < 0) ? -1 : +1) : 0;
358     step_y = dy ? ((dy < 0) ? -1 : +1) : 0;
359     for (x = x1 + step_x, y = y1 + step_y;
360          x != x2 || y != y2;
361          x += step_x, y += step_y)
362     {
363         if (board->cells[x][y] != LOA_CELL_EMPTY &&
364             board->cells[x][y] != board->cells[x1][y1])
365         {
366             *error = "You cannot jump an opponent's piece";
367             return FALSE;
368         }
369     }
370
371     return TRUE;
372 }
373
374 static void
375 loa_board_next_player (loa_board_t *board)
376 {
377     if (board->player == LOA_PLAYER_BLACK)
378         board->player = LOA_PLAYER_WHITE;
379     else
380         board->player = LOA_PLAYER_BLACK;
381 }
382
383 /* XXX: Should check for a legal move for the current player and
384  * return FALSE in that case, (that is, it should be illegal to pass
385  * if there's a legal move available). */
386 int
387 loa_board_pass (loa_board_t *board)
388 {
389     loa_board_next_player (board);
390
391     return TRUE;
392 }
393
394 /* Once the move is validated and executed, append it to the moves
395  * array that stores the move history. */
396 static void
397 loa_board_add_move_to_history (loa_board_t      *board,
398                                const loa_move_t *move)
399 {
400     board->num_moves++;
401
402     if (board->num_moves > board->moves_size) {
403         if (board->moves_size)
404             board->moves_size *= 2;
405         else
406             board->moves_size = 20;
407
408         board->moves = realloc (board->moves,
409                                 board->moves_size * sizeof (loa_move_t));
410         if (board->moves == NULL) {
411             fprintf (stderr, "Out of memory.\n");
412             exit (1);
413         }
414     }
415
416     board->moves[board->num_moves - 1] = *move;
417 }
418
419 int
420 loa_board_move (loa_board_t *board,
421                 loa_move_t *move,
422                 char **error)
423 {
424     loa_cell_t cell;
425
426     if (! loa_board_move_is_legal (board, move, error))
427         return FALSE;
428
429     cell = loa_board_remove_piece (board, move->x1, move->y1);
430     assert (cell == board->player);
431
432     cell = loa_board_remove_piece (board, move->x2, move->y2);
433     assert (cell == LOA_CELL_EMPTY ||
434             (move->is_capture && cell != board->player));
435
436     loa_board_add_piece (board,
437                          move->x2, move->y2,
438                          board->player);
439
440     loa_board_add_move_to_history (board, move);
441
442     loa_board_next_player (board);
443
444     return TRUE;
445 }
446
447 /* A few different ideas for displaying boards:
448  *
449  * 8│ │●│●│●│●│●│●│ |       8| |*|*|*|*|*|*| |
450  * 7│○│ │ │ │ │ │ │○|       7|o| | | | | | |o|
451  * 6│○│ │ │ │ │ │ │○|       6|o| | | | | | |o|
452  * 5│○│ │ │ │ │ │ │○|       5|o| | | | | | |o|
453  * 4│○│ │ │ │ │ │ │○|       4|o| | | | | | |o|
454  * 3│○│ │ │ │ │ │ │○|       3|o| | | | | | |o|
455  * 2│○│ │ │ │ │ │ │○|       2|o| | | | | | |o|
456  * 1│ │●│●│●│●│●│●│ |       1| |*|*|*|*|*|*| |
457  *   A B C D E F G H      A B C D E F G H
458  *
459  *  ┌───┬───┬───┬───┬───┬───┬───┬───┐   ------------------------------- 
460  * 8│   │ ● │ ● │ ● │ ● │ ● │ ● │   │     8|   | * | * | * | * | * | * |   |
461  *  ├───┼───┼───┼───┼───┼───┼───┼───┤  |---+---+---+---+---+---+---+---|
462  * 7│ ○ │   │   │   │   │   │   │ ○ │     7| o |   |   |   |   |   |   | o |
463  *  ├───┼───┼───┼───┼───┼───┼───┼───┤  |---+---+---+---+---+---+---+---|
464  * 6│ ○ │   │   │   │   │   │   │ ○ │     6| o |   |   |   |   |   |   | o |
465  *  ├───┼───┼───┼───┼───┼───┼───┼───┤  |---+---+---+---+---+---+---+---|
466  * 5│ ○ │   │   │   │   │   │   │ ○ │     5| o |   |   |   |   |   |   | o |
467  *  ├───┼───┼───┼───┼───┼───┼───┼───┤  |---+---+---+---+---+---+---+---|
468  * 4│ ○ │   │   │   │   │   │   │ ○ │     4| o |   |   |   |   |   |   | o |
469  *  ├───┼───┼───┼───┼───┼───┼───┼───┤  |---+---+---+---+---+---+---+---|
470  * 3│ ○ │   │   │   │   │   │   │ ○ │     3| o |   |   |   |   |   |   | o |
471  *  ├───┼───┼───┼───┼───┼───┼───┼───┤  |---+---+---+---+---+---+---+---|
472  * 2│ ○ │   │   │   │   │   │   │ ○ │     2| o |   |   |   |   |   |   | o |
473  *  ├───┼───┼───┼───┼───┼───┼───┼───┤  |---+---+---+---+---+---+---+---|
474  * 1│   │ ● │ ● │ ● │ ● │ ● │ ● │   │     1|   | * | * | * | * | * | * |   |
475  *  └───┴───┴───┴───┴───┴───┴───┴───┘   ------------------------------- 
476  *    A   B   C   D   E   F   G   H        A   B   C   D   E   F   G   H
477  */
478 char *
479 loa_board_to_string (loa_board_t *board)
480 {
481     int x, y;
482     /* In order of BLACK, WHITE, EMPTY */
483     const char* cell_strings[] = {"●","○"," "};
484     const char   board_header[] = "┌───┬───┬───┬───┬───┬───┬───┬───┐";
485     const char     row_header[] = "│ ";
486     const char cell_separator[] =    " │ ";
487     const char     row_footer[] =                                " │";
488     const char  row_separator[] = "├───┼───┼───┼───┼───┼───┼───┼───┤";
489     const char   board_footer[] = "└───┴───┴───┴───┴───┴───┴───┴───┘";
490     char *board_string = g_strdup ("");
491
492 #define APPEND(str) do {                                        \
493     char *_new = g_strconcat (board_string, (str), NULL);       \
494     free (board_string);                                        \
495     board_string = _new;                                        \
496 } while (0)
497
498 #define APPENDF(format, ...) do {                               \
499     char *str = g_strdup_printf (format, ## __VA_ARGS__);       \
500     APPEND (str);                                               \
501     free (str);                                                 \
502 } while (0)
503
504     APPENDF (" %s\n", board_header);
505     for (y = 0; y < LOA_BOARD_SIZE; y++) {
506         APPENDF ("%d%s", LOA_BOARD_SIZE - y, row_header);
507         for (x = 0; x < LOA_BOARD_SIZE; x++) {
508             APPENDF ("%s", cell_strings[board->cells[x][y]]);
509             if (x != LOA_BOARD_SIZE - 1)
510                 APPENDF ("%s", cell_separator);
511         }
512         APPENDF ("%s\n", row_footer);
513         if (y != LOA_BOARD_SIZE -1)
514             APPENDF (" %s\n", row_separator);
515     }
516     APPENDF (" %s\n", board_footer);
517
518     APPENDF ("   ");
519     for (x = 0; x < LOA_BOARD_SIZE; x++) {
520         APPENDF ("%c", 'A' + x);
521         if (x != LOA_BOARD_SIZE - 1)
522             APPENDF ("   ");
523     }
524     APPENDF ("\n");
525
526     return board_string;
527 }