File: board.c

package info (click to toggle)
dreamchess 0.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 8,844 kB
  • ctags: 2,708
  • sloc: ansic: 17,566; sh: 3,785; objc: 297; yacc: 225; makefile: 219; lex: 97; xml: 38
file content (747 lines) | stat: -rw-r--r-- 20,014 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
/*  DreamChess
**
**  DreamChess is the legal property of its developers, whose names are too
**  numerous to list here. Please refer to the COPYRIGHT file distributed
**  with this source distribution.
**
**  This program is free software: you can redistribute it and/or modify
**  it under the terms of the GNU General Public License as published by
**  the Free Software Foundation, either version 3 of the License, or
**  (at your option) any later version.
**
**  This program is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**  GNU General Public License for more details.
**
**  You should have received a copy of the GNU General Public License
**  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "board.h"
#include "san.h"
#include "debug.h"

static int move_is_semi_valid(board_t *board, move_t *move);
static int in_check(board_t *board, int turn);

void board_setup(board_t *board)
{
    int i;

    for (i = 16; i < 48; i++)
        board->square[i] = NONE;

    board->square[0] = WHITE_ROOK;
    board->square[1] = WHITE_KNIGHT;
    board->square[2] = WHITE_BISHOP;
    board->square[3] = WHITE_QUEEN;
    board->square[4] = WHITE_KING;
    board->square[5] = WHITE_BISHOP;
    board->square[6] = WHITE_KNIGHT;
    board->square[7] = WHITE_ROOK;
    board->square[56] = BLACK_ROOK;
    board->square[57] = BLACK_KNIGHT;
    board->square[58] = BLACK_BISHOP;
    board->square[59] = BLACK_QUEEN;
    board->square[60] = BLACK_KING;
    board->square[61] = BLACK_BISHOP;
    board->square[62] = BLACK_KNIGHT;
    board->square[63] = BLACK_ROOK;

    for (i = 8; i < 16; i++)
        board->square[i] = WHITE_PAWN;

    for (i = 48; i < 56; i++)
        board->square[i] = BLACK_PAWN;

    for (i = 0; i < 10; i++)
        board->captured[i] = 0;

    board->turn = WHITE;
    board->state = BOARD_NORMAL;
}

static int move_is_capture(board_t *board, move_t *move)
{
    if (board->square[move->destination] != NONE)
        return 1;

    if ((PIECE(board->square[move->source]) == PAWN) &&
            ((move->destination - move->source) % 8 != 0))
        return 1;

    return 0;
}

static void square_to_str(char *buf, int square)
{
    buf[0] = (square % 8) + 'a';
    buf[1] = (square / 8) + '1';
}

char *move_to_fullalg(board_t *board, move_t *move)
{
    char *s = (char *) malloc(6);
    char prom[4] = "nbrq";

    square_to_str(s, move->source);
    square_to_str(s + 2, move->destination);
    s[4] = '\0';
    s[5] = '\0';

    if ((PIECE(board->square[move->source]) == PAWN) && ((move->destination < 8) || (move->destination >= 56)))
        s[4] = prom[(move->promotion_piece - 2) / 2];
    return s;
}

static int san_piece(int piece)
{
    switch (PIECE(piece))
    {
    case KING:
        return SAN_KING;
    case QUEEN:
        return SAN_QUEEN;
    case ROOK:
        return SAN_ROOK;
    case BISHOP:
        return SAN_BISHOP;
    case KNIGHT:
        return SAN_KNIGHT;
    case PAWN:
        return SAN_PAWN;
    }

    DBG_ERROR("failed to convert user interface piece to SAN piece");
    exit(1);
}

int make_move(board_t *board, move_t *move)
{
    /* Assume that move is valid. */

    if ((PIECE(board->square[move->source]) == PAWN) && ((PIECE(board->square[move->destination]) == NONE)) && ((move->source % 8) != (move->destination % 8)))
    {
        /* En-passant move. */
        int ep = move->destination - 8 * (move->destination > move->source ? 1 : -1);
        board->captured[board->square[ep]]++;
        board->square[ep] = NONE;
    }

    /* Update captured pieces. */
    if (board->square[move->destination] != NONE)
        board->captured[board->square[move->destination]]++;

    if ((PIECE(board->square[move->source]) == KING) && (move->destination - move->source == 2))
    {
        /* Kingside castle. */
        board->square[move->destination - 1] = board->square[move->destination + 1];
        board->square[move->destination + 1] = NONE;
    }

    if ((PIECE(board->square[move->source]) == KING) && (move->source - move->destination == 2))
    {
        /* Queenside castle. */
        board->square[move->destination + 1] = board->square[move->destination - 2];
        board->square[move->destination - 2] = NONE;
    }

    if ((PIECE(board->square[move->source]) == PAWN) && (move->destination < 8 || move->destination >= 56))
        /* Promotion. */
        board->square[move->destination] = move->promotion_piece;
    else
        board->square[move->destination] = board->square[move->source];

    board->square[move->source] = NONE;
    board->turn = OPPONENT(board->turn);

    return 0;
}

#define HOR abs(move->source % 8 - move->destination % 8)
#define VERT abs(move->source / 8 - move->destination / 8)

static int ray_ok(board_t *board, move_t *move)
{
    int step, i;
    if (VERT != 0)
        step = (move->destination - move->source) / VERT;
    else
        step = (move->destination > move->source ? 1 : -1);

    i = move->source + step;

    while (i != move->destination)
    {
        if (board->square[i] != NONE)
            return 0;
        i += step;
    }

    if (board->square[i] == NONE)
        return 1;

    if (COLOUR(board->square[i]) != COLOUR(board->square[move->source]))
        return 1;

    return 0;
}

static int square_attacked(board_t *b, int square, int side)
{
    board_t board = *b;
    move_t move;
    int i;

    board.turn = side;

    /* We add a piece because we only want to take capture moves into consideration. */
    board.square[square] = KING + OPPONENT(side);

    move.destination = square;

    for (i = 0; i < 64; i++)
    {
        if (COLOUR(board.square[i]) == side)
        {
            move.source = i;
            if ((PIECE(board.square[i]) == PAWN) && ((square < 8) || (square >= 56)))
                move.promotion_piece = QUEEN + side;
            else
                move.promotion_piece = NONE;
            if (move_is_semi_valid(&board, &move))
                return 1;
        }
    }
    return 0;
}

/* Checks whether a move is valid, except for whether this puts own king in check. */
static int move_is_semi_valid(board_t *board, move_t *move)
{
    /* Bounds check. */
    if ((move->source > 63) || (move->source < 0))
        return 0;

    if ((move->destination > 63) || (move->destination < 0))
        return 0;

    /* Test for moving to same square. */
    if (move->source == move->destination)
        return 0;

    /* Test for empty source square. */
    if (board->square[move->source] == NONE)
        return 0;

    /* Test for moving opponent's piece. */
    if (COLOUR(board->square[move->source]) != board->turn)
        return 0;

    /* Check that a promotion piece is specified for promotion moves. */
    if ((PIECE(board->square[move->source]) == PAWN) && ((move->destination < 8) || (move->destination >= 56)))
    {
        switch (PIECE(move->promotion_piece))
        {
        case KNIGHT:
        case ROOK:
        case BISHOP:
        case QUEEN:
            break;
        default:
            return 0;
        }

        if (COLOUR(move->promotion_piece) != board->turn)
            return 0;
    }
    else if (move->promotion_piece != NONE)
        /* Promotion piece specified for non-promotion move. */
        return 0;

    switch (PIECE(board->square[move->source]))
    {
    case KNIGHT:
        if ((HOR != 1) && (HOR != 2))
            return 0;
        if ((HOR == 1) && (VERT != 2))
            return 0;
        if ((HOR == 2) && (VERT != 1))
            return 0;
        if (board->square[move->destination] == NONE)
            break;
        if (COLOUR(board->square[move->destination]) == COLOUR(board->square[move->source]))
            return 0;
        break;
    case BISHOP:
        if (HOR != VERT)
            return 0;
        if (!ray_ok(board, move))
            return 0;
        break;
    case ROOK:
        if ((HOR != 0) && (VERT != 0))
            return 0;
        if (!ray_ok(board, move))
            return 0;
        break;
    case QUEEN:
        if ((HOR != 0) && (VERT != 0) && (HOR != VERT))
            return 0;
        if (!ray_ok(board, move))
            return 0;
        break;
    case PAWN:
        /* Catch moves in wrong direction. */
        if ((move->destination > move->source) && (COLOUR(board->square[move->source]) == BLACK))
            return 0;
        if ((move->destination < move->source) && (COLOUR(board->square[move->source]) == WHITE))
            return 0;

        if (HOR > 1)
            return 0;

        if (HOR == 0)
        {
            /* Regular or double push. */

            if (VERT > 2)
                return 0;
            if (VERT == 2)
                if (!(((move->source >= 8) && (move->source <= 15)) || ((move->source >= 48) && (move->source <= 55))))
                    return 0;
            /* Use ray checking code with added requirement that destination square is empty. */
            if (!ray_ok(board, move) || (board->square[move->destination] != NONE))
                return 0;
        }
        else
        {
            if (VERT != 1)
                return 0;
            if (!ray_ok(board, move))
                return 0;
            /* En-passant move. */
            if (board->square[move->destination] == NONE)
            {
                if ((COLOUR(board->square[move->source]) == WHITE) && !((move->source >= 32) && (move->source < 40)))
                    return 0;
                if ((COLOUR(board->square[move->source]) == BLACK) && !((move->source >= 24) && (move->source < 32)))
                    return 0;

                if (board->square[move->destination + (COLOUR(board->square[move->source]) == WHITE ? -8 : 8)] !=
                        PAWN + OPPONENT(COLOUR(board->square[move->source])))
                    return 0;
            }

        }
        break;
    case KING:
        if (HOR > 2)
            return 0;
        else if (HOR == 2)
        {
            int white = COLOUR(board->square[move->source]) == WHITE;

            int i, step = (move->destination > move->source ? 1 : -1);
            int rook = (step == 1 ? (white ? 7 : 63) : (white ? 0 : 56));

            /* Castling. */
            if (VERT != 0)
                return 0;

            if (move->source != (white ? 4 : 60))
                return 0;

            if (board->square[rook] != ROOK + COLOUR(board->square[move->source]))
                return 0;

            i = move->source + step;

            while (i != rook)
            {
                if (board->square[i] != NONE)
                    return 0;
                i += step;
            }

            /* Check whether any of the squares the king moves over is under
            ** attack. Note that destination square is checked later.
            */
            if (square_attacked(board, move->source, (white ? BLACK : WHITE)))
                return 0;
            if (square_attacked(board, move->source + step, (white ? BLACK : WHITE)))
                return 0;
        }
        else
        {
            if (VERT > 1)
                return 0;
            if (!ray_ok(board, move))
                return 0;
        }
    }
    return 1;
}

static int in_check(board_t *board, int turn)
{
    int i;
    for (i = 0; i < 64; i++)
        if (board->square[i] ==  KING + turn)
            break;

    if (i == 64)
    {
        DBG_ERROR("board is missing a king");
        exit(1);
    }

    return square_attacked(board, i, OPPONENT(turn));
}

int move_is_valid(board_t *b, move_t *move)
{
    board_t board = *b;

    if (!move_is_semi_valid(&board, move))
        return 0;

    make_move(&board, move);

    return !in_check(&board, b->turn);
}

static int is_mated(board_t *board, int side)
{
    int src, dest;
    move_t move;

    for (src = 0; src < 64; src++)
        if (COLOUR(board->square[src]) == side)
            for (dest = 0; dest < 64; dest++)
            {
                move.source = src;
                move.destination = dest;
                if ((PIECE(board->square[src]) == PAWN) && ((dest < 8) || (dest >= 56)))
                    move.promotion_piece = QUEEN + side;
                else
                    move.promotion_piece = NONE;
                if (move_is_valid(board, &move))
                    return 0;
            }
    return 1;
}

void move_set_attr(board_t *b, move_t *move)
{
    int check, mated;
    board_t board = *b;

    if (move_is_capture(b, move))
        move->type = CAPTURE;
    else
        move->type = NORMAL;

    if (PIECE(b->square[move->source]) == KING)
    {
        int hor = move->destination % 8 - move->source % 8;

        if (hor > 1)
            move->type = KINGSIDE_CASTLE;
        else if (hor < -1)
            move->type = QUEENSIDE_CASTLE;
    }

    make_move(&board, move);

    check = in_check(&board, board.turn);
    mated = is_mated(&board, board.turn);

    if (check && mated)
        move->state = MOVE_CHECKMATE;
    else if (check)
        move->state = MOVE_CHECK;
    else if (mated)
        move->state = MOVE_STALEMATE;
    else
        move->state = MOVE_NORMAL;

}

move_t *fullalg_to_move(board_t *board, char *move_s)
{
    move_t *move;

    if ((strlen(move_s) < 4) || (strlen(move_s) > 5))
        return NULL;
    if ((move_s[0] < 'a') || (move_s[0] > 'h'))
        return NULL;
    if ((move_s[1] < '1') || (move_s[1] > '8'))
        return NULL;
    if ((move_s[2] < 'a') || (move_s[2] > 'h'))
        return NULL;
    if ((move_s[3] < '1') || (move_s[3] > '8'))
        return NULL;
    if ((strlen(move_s) == 5) && (move_s[4] != 'n')
            && (move_s[4] != 'b') && (move_s[4] != 'r')
            && (move_s[4] != 'q'))
        return NULL;

    move = (move_t *) malloc(sizeof(move_t));
    move->source = move_s[0] - 'a' + (move_s[1] - '1') * 8;
    move->destination = move_s[2] - 'a' + (move_s[3] - '1') * 8;

    if (strlen(move_s) == 5)
    {
        switch (move_s[4])
        {
        case 'n':
            move->promotion_piece = KNIGHT;
            break;
        case 'b':
            move->promotion_piece = BISHOP;
            break;
        case 'r':
            move->promotion_piece = ROOK;
            break;
        case 'q':
            move->promotion_piece = QUEEN;
        }
        move->promotion_piece += board->turn;
    }
    else
        move->promotion_piece = NONE;

    if (!move_is_valid(board, move))
    {
        free(move);
        return NULL;
    }

    move_set_attr(board, move);

    return move;
}

static int ui_piece(int san_piece)
{
    switch (san_piece)
    {
    case SAN_PAWN:
        return PAWN;
    case SAN_KNIGHT:
        return KNIGHT;
    case SAN_BISHOP:
        return BISHOP;
    case SAN_ROOK:
        return ROOK;
    case SAN_QUEEN:
        return QUEEN;
    case SAN_KING:
        return KING;
    case SAN_NOT_SPECIFIED:
        return NONE;
    }

    DBG_ERROR("failed to convert SAN piece to user interface piece");
    exit(1);
}

static move_t *find_unique_move(board_t *board, san_move_t *san_move)
{
    int square;
    int piece;
    int found = 0;
    move_t move, *retval;

    if (san_move->type == SAN_QUEENSIDE_CASTLE)
    {
        san_move->source_file = 4;
        san_move->source_rank = (board->turn == WHITE ? 0 : 7);
        san_move->destination = (board->turn == WHITE ? 2 : 58);
        piece = KING;
    }
    else if (san_move->type == SAN_KINGSIDE_CASTLE)
    {
        san_move->source_file = 4;
        san_move->source_rank = (board->turn == WHITE ? 0 : 7);
        san_move->destination = (board->turn == WHITE ? 6 : 62);
        piece = KING;
    }
    else
        piece = ui_piece(san_move->piece);

    piece += board->turn;

    for (square = 0; square < 64; square++)
    {
        move_t m;

        if (board->square[square] != piece)
            continue;

        /* We found a piece. */

        if (san_move->source_file != SAN_NOT_SPECIFIED)
            if (san_move->source_file != square % 8)
                continue;

        if (san_move->source_rank != SAN_NOT_SPECIFIED)
            if (san_move->source_rank != square / 8)
                continue;

        m.source = square;
        m.destination = san_move->destination;
        m.promotion_piece = ui_piece(san_move->promotion_piece);

        if (m.promotion_piece != NONE)
            m.promotion_piece += board->turn;

        if (move_is_valid(board, &m))
        {
            move = m;
            found++;
            if (found > 1)
                return NULL;
        }
    }

    if (!found)
    {
        DBG_ERROR("failed to find a legal move corresponding to SAN move");
        return NULL;
    }

    retval = (move_t *) malloc(sizeof(move_t));
    *retval = move;
    return retval;
}

char *move_to_san(board_t *board, move_t *move)
{
    san_move_t san_move;

    switch (move->state)
    {
    case MOVE_CHECK:
        san_move.state = SAN_STATE_CHECK;
        break;
    case MOVE_CHECKMATE:
        san_move.state = SAN_STATE_CHECKMATE;
        break;
    default:
        san_move.state = SAN_STATE_NORMAL;
    }

    switch (move->type)
    {
    case QUEENSIDE_CASTLE:
        san_move.type = SAN_QUEENSIDE_CASTLE;
        return san_string(&san_move);
    case KINGSIDE_CASTLE:
        san_move.type = SAN_KINGSIDE_CASTLE;
        return san_string(&san_move);
    case CAPTURE:
        san_move.type = SAN_CAPTURE;
        break;
    default:
        san_move.type = SAN_NORMAL;
    }

    san_move.piece = san_piece(board->square[move->source]);
    san_move.source_file = SAN_NOT_SPECIFIED;
    san_move.source_rank = SAN_NOT_SPECIFIED;
    san_move.destination = move->destination;
    if (move->promotion_piece != NONE)
        san_move.promotion_piece = san_piece(move->promotion_piece);
    else
        san_move.promotion_piece = SAN_NOT_SPECIFIED;

    if (san_move.piece == SAN_PAWN)
    {
        if (move->source % 8 != move->destination % 8)
            san_move.source_file = move->source % 8;
    }
    else
    {
        move_t *u_move;
        u_move = find_unique_move(board, &san_move);

        if (!u_move)
        {
            san_move.source_file = move->source % 8;
            u_move = find_unique_move(board, &san_move);
            if (!u_move)
            {
                san_move.source_file = SAN_NOT_SPECIFIED;
                san_move.source_rank = move->source / 8;
                u_move = find_unique_move(board, &san_move);
                if (!u_move)
                {
                    san_move.source_file = move->source % 8;
                    u_move = find_unique_move(board, &san_move);
                    if (!u_move)
                    {
                        char *move_s = move_to_fullalg(board, move);

                        DBG_ERROR("failed to convert move %s to SAN notation", move_s);

                        free(move_s);
                        return NULL;
                    }
                }
                else
                    free(u_move);
            }
            else
                free(u_move);
        }
        else
            free(u_move);
    }

    return san_string(&san_move);
}

move_t* san_to_move(board_t *board, char *move_s)
{
    san_move_t *san_move = san_parse(move_s);

    if (!san_move)
    {
        DBG_LOG("failed to parse SAN move string '%s'", move_s);
        return NULL;
    }

    return find_unique_move(board, san_move);
}

char* san_to_fan(board_t *board, char *move_s)
{
    char *move = strdup(move_s);

    switch (move[0])
    {
    case 'K':
        move[0] = CHAR_KING;
        break;
    case 'Q':
        move[0] = CHAR_QUEEN;
        break;
    case 'R':
        move[0] = CHAR_ROOK;
        break;
    case 'N':
        move[0] = CHAR_KNIGHT;
        break;
    case 'B':
        move[0] = CHAR_BISHOP;
    }

    return move;
}