src/chess/rules.c

Wed, 29 Aug 2018 17:31:36 +0200

author
Mike Becker <universe@uap-core.de>
date
Wed, 29 Aug 2018 17:31:36 +0200
changeset 68
b34de5ce7d0e
parent 67
c76e46970a59
child 69
c8f2c280cff7
permissions
-rw-r--r--

error message when syntactically validating a King's move into a check position is now correct

     1 /*
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * Copyright 2016 Mike Becker. All rights reserved.
     5  *
     6  * Redistribution and use in source and binary forms, with or without
     7  * modification, are permitted provided that the following conditions are met:
     8  *
     9  *   1. Redistributions of source code must retain the above copyright
    10  *      notice, this list of conditions and the following disclaimer.
    11  *
    12  *   2. Redistributions in binary form must reproduce the above copyright
    13  *      notice, this list of conditions and the following disclaimer in the
    14  *      documentation and/or other materials provided with the distribution.
    15  *
    16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    17  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    19  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
    20  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    26  * POSSIBILITY OF SUCH DAMAGE.
    27  *
    28  */
    30 #include "rules.h"
    31 #include "chess.h"
    32 #include <string.h>
    33 #include <stdlib.h>
    34 #include <sys/time.h>
    36 static GameState gamestate_copy_sim(GameState *gamestate) {
    37     GameState simulation = *gamestate;
    38     simulation.movecount = 0; /* simulations do not count moves */
    39     if (simulation.lastmove) {
    40         MoveList *lastmovecopy = malloc(sizeof(MoveList));
    41         *lastmovecopy = *(simulation.lastmove);
    42         simulation.movelist = simulation.lastmove = lastmovecopy;
    43     }
    45     return simulation;
    46 }
    48 void gamestate_init(GameState *gamestate) {
    49     memset(gamestate, 0, sizeof(GameState));
    51     Board initboard = {
    52         {WROOK, WKNIGHT, WBISHOP, WQUEEN, WKING, WBISHOP, WKNIGHT, WROOK},
    53         {WPAWN, WPAWN,   WPAWN,   WPAWN,  WPAWN, WPAWN,   WPAWN,   WPAWN},
    54         {0,     0,       0,       0,      0,     0,       0,       0},
    55         {0,     0,       0,       0,      0,     0,       0,       0},
    56         {0,     0,       0,       0,      0,     0,       0,       0},
    57         {0,     0,       0,       0,      0,     0,       0,       0},
    58         {BPAWN, BPAWN,   BPAWN,   BPAWN,  BPAWN, BPAWN,   BPAWN,   BPAWN},
    59         {BROOK, BKNIGHT, BBISHOP, BQUEEN, BKING, BBISHOP, BKNIGHT, BROOK}
    60     };
    61     memcpy(gamestate->board, initboard, sizeof(Board));
    62 }
    64 void gamestate_cleanup(GameState *gamestate) {
    65     MoveList *elem;
    66     elem = gamestate->movelist;
    67     while (elem) {
    68         MoveList *cur = elem;
    69         elem = elem->next;
    70         free(cur);
    71     };
    72 }
    74 /* MUST be called BETWEEN validating AND applying a move to work correctly */
    75 static void format_move(GameState *gamestate, Move *move) {
    76     char *string = &(move->string[0]);
    78     /* at least 8 characters should be available, wipe them out */
    79     memset(string, 0, 8);
    81     unsigned int idx;
    82     if ((move->piece&PIECE_MASK) == KING &&
    83             abs(move->tofile-move->fromfile) == 2) {
    84         /* special formats for castling */
    85         if (move->tofile==fileidx('c')) {
    86             memcpy(string, "O-O-O", 5);
    87             idx = 5;
    88         } else {
    89             memcpy(string, "O-O", 3);
    90             idx = 3;
    91         }
    92     } else {
    93         /* start by notating the piece character */
    94         string[0] = getpiecechr(move->piece);
    95         idx = string[0] ? 1 : 0;
    97         /* find out how many source information we do need */
    98         uint8_t piece = move->piece & PIECE_MASK;
    99         if (piece == PAWN) {
   100             if (move->capture) {
   101                 string[idx++] = filechr(move->fromfile);
   102             }
   103         } else if (piece != KING) {
   104             /* resolve ambiguities, if any */
   105             Move threats[16];
   106             uint8_t threatcount;
   107             if (get_threats(gamestate, move->torow, move->tofile,
   108                     move->piece&COLOR_MASK, threats, &threatcount)) {
   109                 unsigned int ambrows = 0, ambfiles = 0, ambpiece = 0;
   110                 for (uint8_t i = 0 ; i < threatcount ; i++) {
   111                     if (threats[i].piece == move->piece) {
   112                         ambpiece++;
   113                         if (threats[i].fromrow == move->fromrow) {
   114                             ambrows++;
   115                         }
   116                         if (threats[i].fromfile == move->fromfile) {
   117                             ambfiles++;
   118                         }
   119                     }
   120                 }
   121                 /* neither file, nor row are ambiguous, name file */
   122                 if (ambpiece > 1 && ambrows == 1 && ambfiles == 1) {
   123                     /* this is most likely the case with Knights
   124                      * in diagonal opposition */
   125                     string[idx++] = filechr(move->fromfile);
   126                 } else {
   127                     /* ambiguous row, name file */
   128                     if (ambrows > 1) {
   129                         string[idx++] = filechr(move->fromfile);
   130                     }
   131                     /* ambiguous file, name row */
   132                     if (ambfiles > 1) {
   133                         string[idx++] = filechr(move->fromrow);
   134                     }
   135                 }
   136             }
   137         }
   139         /* capturing? */
   140         if (move->capture) {
   141             string[idx++] = 'x';
   142         }
   144         /* destination */
   145         string[idx++] = filechr(move->tofile);
   146         string[idx++] = rowchr(move->torow);
   148         /* promotion? */
   149         if (move->promotion) {
   150             string[idx++] = '=';
   151             string[idx++] = getpiecechr(move->promotion);
   152         }
   153     }
   155     /* check? */
   156     if (move->check) {
   157         string[idx++] = gamestate->checkmate?'#':'+';
   158     }
   159 }
   161 static void addmove(GameState* gamestate, Move *move) {
   162     MoveList *elem = malloc(sizeof(MoveList));
   163     elem->next = NULL;
   164     elem->move = *move;
   166     struct timeval curtimestamp;
   167     gettimeofday(&curtimestamp, NULL);
   168     elem->move.timestamp.tv_sec = curtimestamp.tv_sec;
   169     elem->move.timestamp.tv_usec = curtimestamp.tv_usec;
   171     if (gamestate->lastmove) {
   172         struct movetimeval *lasttstamp = &(gamestate->lastmove->move.timestamp);
   173         uint64_t sec = curtimestamp.tv_sec - lasttstamp->tv_sec;
   174         suseconds_t micros;
   175         if (curtimestamp.tv_usec < lasttstamp->tv_usec) {
   176             micros = 1e6L-(lasttstamp->tv_usec - curtimestamp.tv_usec);
   177             sec--;
   178         } else {
   179             micros = curtimestamp.tv_usec - lasttstamp->tv_usec;
   180         }
   182         elem->move.movetime.tv_sec = sec;
   183         elem->move.movetime.tv_usec = micros;
   185         gamestate->lastmove->next = elem;
   186         gamestate->lastmove = elem;
   187         gamestate->movecount++;
   188     } else {
   189         elem->move.movetime.tv_usec = 0;
   190         elem->move.movetime.tv_sec = 0;
   191         gamestate->movelist = gamestate->lastmove = elem;
   192         gamestate->movecount = 1;
   193     }
   194 }
   196 char getpiecechr(uint8_t piece) {
   197     switch (piece & PIECE_MASK) {
   198     case ROOK: return 'R';
   199     case KNIGHT: return 'N';
   200     case BISHOP: return 'B';
   201     case QUEEN: return 'Q';
   202     case KING: return 'K';
   203     default: return '\0';
   204     }
   205 }
   207 uint8_t getpiece(char c) {
   208     switch (c) {
   209         case 'R': return ROOK;
   210         case 'N': return KNIGHT;
   211         case 'B': return BISHOP;
   212         case 'Q': return QUEEN;
   213         case 'K': return KING;
   214         default: return 0;
   215     }
   216 }
   218 static void apply_move_impl(GameState *gamestate, Move *move, _Bool simulate) {
   219     /* format move before moving (s.t. ambiguities can be resolved) */
   220     if (!simulate) {
   221         if (!move->string[0]) {
   222             format_move(gamestate, move);
   223         }
   224     }
   226     uint8_t piece = move->piece & PIECE_MASK;
   227     uint8_t color = move->piece & COLOR_MASK;
   229     /* en passant capture */
   230     if (move->capture && piece == PAWN &&
   231         mdst(gamestate->board, move) == 0) {
   232         gamestate->board[move->fromrow][move->tofile] = 0;
   233     }
   235     /* remove old en passant threats */
   236     for (uint8_t file = 0 ; file < 8 ; file++) {
   237         gamestate->board[3][file] &= ~ENPASSANT_THREAT;
   238         gamestate->board[4][file] &= ~ENPASSANT_THREAT;
   239     }
   241     /* add new en passant threat */
   242     if (piece == PAWN && (
   243         (move->fromrow == 1 && move->torow == 3) ||
   244         (move->fromrow == 6 && move->torow == 4))) {
   245         move->piece |= ENPASSANT_THREAT;
   246     }
   248     /* move (and maybe capture or promote) */
   249     msrc(gamestate->board, move) = 0;
   250     if (move->promotion) {
   251         mdst(gamestate->board, move) = move->promotion;
   252     } else {
   253         mdst(gamestate->board, move) = move->piece;
   254     }
   256     /* castling */
   257     if (piece == KING && move->fromfile == fileidx('e')) {
   258         if (move->tofile == fileidx('g')) {
   259             gamestate->board[move->torow][fileidx('h')] = 0;
   260             gamestate->board[move->torow][fileidx('f')] = color|ROOK;
   261         } else if (move->tofile == fileidx('c')) {
   262             gamestate->board[move->torow][fileidx('a')] = 0;
   263             gamestate->board[move->torow][fileidx('d')] = color|ROOK;
   264         }
   265     }
   267     /* add move, even in simulation (checkmate test needs it) */
   268     addmove(gamestate, move);
   269 }
   271 void apply_move(GameState *gamestate, Move *move) {
   272     apply_move_impl(gamestate, move, 0);
   273 }
   275 static int validate_move_rules(GameState *gamestate, Move *move) {
   276     /* validate indices (don't trust opponent) */
   277     if (!chkidx(move)) {
   278         return INVALID_POSITION;
   279     }
   281     /* must move */
   282     if (move->fromfile == move->tofile && move->fromrow == move->torow) {
   283         return INVALID_MOVE_SYNTAX;
   284     }
   286     /* does piece exist */
   287     if ((msrc(gamestate->board, move)&(PIECE_MASK|COLOR_MASK))
   288            != (move->piece&(PIECE_MASK|COLOR_MASK))) {
   289         return INVALID_POSITION;
   290     }
   292     /* can't capture own pieces */
   293     if ((mdst(gamestate->board, move) & COLOR_MASK)
   294             == (move->piece & COLOR_MASK)) {
   295         return RULES_VIOLATED;
   296     }
   298     /* must capture, if and only if destination is occupied */
   299     if ((mdst(gamestate->board, move) == 0 && move->capture) ||
   300             (mdst(gamestate->board, move) != 0 && !move->capture)) {
   301         return INVALID_MOVE_SYNTAX;
   302     }
   304     /* validate individual rules */
   305     _Bool chkrules;
   306     switch (move->piece & PIECE_MASK) {
   307     case PAWN:
   308         chkrules = pawn_chkrules(gamestate, move) &&
   309             !pawn_isblocked(gamestate, move);
   310         break;
   311     case ROOK:
   312         chkrules = rook_chkrules(move) &&
   313             !rook_isblocked(gamestate, move);
   314         break;
   315     case KNIGHT:
   316         chkrules = knight_chkrules(move); /* knight is never blocked */
   317         break;
   318     case BISHOP:
   319         chkrules = bishop_chkrules(move) &&
   320             !bishop_isblocked(gamestate, move);
   321         break;
   322     case QUEEN:
   323         chkrules = queen_chkrules(move) &&
   324             !queen_isblocked(gamestate, move);
   325         break;
   326     case KING:
   327         chkrules = king_chkrules(gamestate, move) &&
   328             !king_isblocked(gamestate, move);
   329         break;
   330     default:
   331         return INVALID_MOVE_SYNTAX;
   332     }
   334     return chkrules ? VALID_MOVE_SEMANTICS : RULES_VIOLATED;
   335 }
   337 int validate_move(GameState *gamestate, Move *move) {
   339     int result = validate_move_rules(gamestate, move);
   341     /* cancel processing to save resources */
   342     if (result != VALID_MOVE_SEMANTICS) {
   343         return result;
   344     }
   346     /* simulate move for check validation */
   347     GameState simulation = gamestate_copy_sim(gamestate);
   348     Move simmove = *move;
   349     apply_move_impl(&simulation, &simmove, 1);
   351     /* find kings for check validation */
   352     uint8_t piececolor = (move->piece & COLOR_MASK);
   354     uint8_t mykingfile = 0, mykingrow = 0, opkingfile = 0, opkingrow = 0;
   355     for (uint8_t row = 0 ; row < 8 ; row++) {
   356         for (uint8_t file = 0 ; file < 8 ; file++) {
   357             if (simulation.board[row][file] ==
   358                     (piececolor == WHITE?WKING:BKING)) {
   359                 mykingfile = file;
   360                 mykingrow = row;
   361             } else if (simulation.board[row][file] ==
   362                     (piececolor == WHITE?BKING:WKING)) {
   363                 opkingfile = file;
   364                 opkingrow = row;
   365             }
   366         }
   367     }
   369     /* don't move into or stay in check position */
   370     if (is_covered(&simulation, mykingrow, mykingfile,
   371         opponent_color(piececolor))) {
   373         gamestate_cleanup(&simulation);
   374         if ((move->piece & PIECE_MASK) == KING) {
   375             return KING_MOVES_INTO_CHECK;
   376         } else {
   377             /* last move is always not null in this case */
   378             return gamestate->lastmove->move.check ?
   379                 KING_IN_CHECK : PIECE_PINNED;
   380         }
   381     }
   383     /* correct check and checkmate flags (move is still valid) */
   384     Move threats[16];
   385     uint8_t threatcount;
   386     move->check = get_threats(&simulation, opkingrow, opkingfile,
   387         piececolor, threats, &threatcount);
   389     if (move->check) {
   390         /* determine possible escape fields */
   391         _Bool canescape = 0;
   392         for (int dr = -1 ; dr <= 1 && !canescape ; dr++) {
   393             for (int df = -1 ; df <= 1 && !canescape ; df++) {
   394                 if (!(dr == 0 && df == 0)  &&
   395                         isidx(opkingrow + dr) && isidx(opkingfile + df)) {
   397                     /* escape field neither blocked nor covered */
   398                     if ((simulation.board[opkingrow + dr][opkingfile + df]
   399                             & COLOR_MASK) != opponent_color(piececolor)) {
   400                         canescape |= !is_covered(&simulation,
   401                             opkingrow + dr, opkingfile + df, piececolor);
   402                     }
   403                 }
   404             }
   405         }
   406         /* can't escape, can he capture? */
   407         if (!canescape && threatcount == 1) {
   408             canescape = is_attacked(&simulation, threats[0].fromrow,
   409                 threats[0].fromfile, opponent_color(piececolor));
   410         }
   412         /* can't capture, can he block? */
   413         if (!canescape && threatcount == 1) {
   414             Move *threat = &(threats[0]);
   415             uint8_t threatpiece = threat->piece & PIECE_MASK;
   417             /* knight, pawns and the king cannot be blocked */
   418             if (threatpiece == BISHOP || threatpiece == ROOK
   419                 || threatpiece == QUEEN) {
   420                 if (threat->fromrow == threat->torow) {
   421                     /* rook aspect (on row) */
   422                     int d = threat->tofile > threat->fromfile ? 1 : -1;
   423                     uint8_t file = threat->fromfile;
   424                     while (!canescape && file != threat->tofile - d) {
   425                         file += d;
   426                         canescape |= is_protected(&simulation,
   427                             threat->torow, file, opponent_color(piececolor));
   428                     }
   429                 } else if (threat->fromfile == threat->tofile) {
   430                     /* rook aspect (on file) */
   431                     int d = threat->torow > threat->fromrow ? 1 : -1;
   432                     uint8_t row = threat->fromrow;
   433                     while (!canescape && row != threat->torow - d) {
   434                         row += d;
   435                         canescape |= is_protected(&simulation,
   436                             row, threat->tofile, opponent_color(piececolor));
   437                     }
   438                 } else {
   439                     /* bishop aspect */
   440                     int dr = threat->torow > threat->fromrow ? 1 : -1;
   441                     int df = threat->tofile > threat->fromfile ? 1 : -1;
   443                     uint8_t row = threat->fromrow;
   444                     uint8_t file = threat->fromfile;
   445                     while (!canescape && file != threat->tofile - df
   446                         && row != threat->torow - dr) {
   447                         row += dr;
   448                         file += df;
   449                         canescape |= is_protected(&simulation, row, file,
   450                             opponent_color(piececolor));
   451                     }
   452                 }
   453             }
   454         }
   456         if (!canescape) {
   457             gamestate->checkmate = 1;
   458         }
   459     }
   461     gamestate_cleanup(&simulation);
   463     return VALID_MOVE_SEMANTICS;
   464 }
   466 _Bool get_threats(GameState *gamestate, uint8_t row, uint8_t file,
   467         uint8_t color, Move *threats, uint8_t *threatcount) {
   468     Move candidates[32];
   469     int candidatecount = 0;
   470     for (uint8_t r = 0 ; r < 8 ; r++) {
   471         for (uint8_t f = 0 ; f < 8 ; f++) {
   472             if ((gamestate->board[r][f] & COLOR_MASK) == color) {
   473                 /* non-capturing move */
   474                 memset(&(candidates[candidatecount]), 0, sizeof(Move));
   475                 candidates[candidatecount].piece = gamestate->board[r][f];
   476                 candidates[candidatecount].fromrow = r;
   477                 candidates[candidatecount].fromfile = f;
   478                 candidates[candidatecount].torow = row;
   479                 candidates[candidatecount].tofile = file;
   480                 candidatecount++;
   482                 /* capturing move */
   483                 memcpy(&(candidates[candidatecount]),
   484                     &(candidates[candidatecount-1]), sizeof(Move));
   485                 candidates[candidatecount].capture = 1;
   486                 candidatecount++;
   487             }
   488         }
   489     }
   491     if (threatcount) {
   492         *threatcount = 0;
   493     }
   496     _Bool result = 0;
   498     for (int i = 0 ; i < candidatecount ; i++) {
   499         if (validate_move_rules(gamestate, &(candidates[i]))
   500                 == VALID_MOVE_SEMANTICS) {
   501             result = 1;
   502             if (threats && threatcount) {
   503                 threats[(*threatcount)++] = candidates[i];
   504             }
   505         }
   506     }
   508     return result;
   509 }
   511 _Bool is_pinned(GameState *gamestate, Move *move) {
   512     uint8_t color = move->piece & COLOR_MASK;
   514     GameState simulation = gamestate_copy_sim(gamestate);
   515     Move simmove = *move;
   516     apply_move(&simulation, &simmove);
   518     uint8_t kingfile = 0, kingrow = 0;
   519     for (uint8_t row = 0 ; row < 8 ; row++) {
   520         for (uint8_t file = 0 ; file < 8 ; file++) {
   521             if (simulation.board[row][file] == (color|KING)) {
   522                 kingfile = file;
   523                 kingrow = row;
   524             }
   525         }
   526     }
   528     _Bool covered = is_covered(&simulation,
   529         kingrow, kingfile, opponent_color(color));
   530     gamestate_cleanup(&simulation);
   532     return covered;
   533 }
   535 _Bool get_real_threats(GameState *gamestate, uint8_t row, uint8_t file,
   536         uint8_t color, Move *threats, uint8_t *threatcount) {
   538     if (threatcount) {
   539         *threatcount = 0;
   540     }
   542     Move candidates[16];
   543     uint8_t candidatecount;
   544     if (get_threats(gamestate, row, file, color, candidates, &candidatecount)) {
   546         _Bool result = 0;
   547         uint8_t kingfile = 0, kingrow = 0;
   548         for (uint8_t row = 0 ; row < 8 ; row++) {
   549             for (uint8_t file = 0 ; file < 8 ; file++) {
   550                 if (gamestate->board[row][file] == (color|KING)) {
   551                     kingfile = file;
   552                     kingrow = row;
   553                 }
   554             }
   555         }
   557         for (uint8_t i = 0 ; i < candidatecount ; i++) {
   558             GameState simulation = gamestate_copy_sim(gamestate);
   559             Move simmove = candidates[i];
   560             apply_move(&simulation, &simmove);
   561             if (!is_covered(&simulation, kingrow, kingfile,
   562                     opponent_color(color))) {
   563                 result = 1;
   564                 if (threats && threatcount) {
   565                     threats[(*threatcount)++] = candidates[i];
   566                 }
   567             }
   568         }
   570         return result;
   571     } else {
   572         return 0;
   573     }
   574 }
   576 static int getlocation(GameState *gamestate, Move *move) {   
   578     uint8_t color = move->piece & COLOR_MASK;
   579     uint8_t piece = move->piece & PIECE_MASK;
   580     _Bool incheck = gamestate->lastmove?gamestate->lastmove->move.check:0;
   582     Move threats[16], *threat = NULL;
   583     uint8_t threatcount;
   585     if (get_threats(gamestate, move->torow, move->tofile, color,
   586             threats, &threatcount)) {
   588         int reason = INVALID_POSITION;
   590         /* find threats for the specified position */
   591         for (uint8_t i = 0 ; i < threatcount ; i++) {            
   592             if ((threats[i].piece & PIECE_MASK) == piece
   593                     && (threats[i].piece & COLOR_MASK) == color &&
   594                     (move->fromrow == POS_UNSPECIFIED ||
   595                     move->fromrow == threats[i].fromrow) &&
   596                     (move->fromfile == POS_UNSPECIFIED ||
   597                     move->fromfile == threats[i].fromfile)) {
   599                 if (threat) {
   600                     return AMBIGUOUS_MOVE;
   601                 } else {
   602                     /* found threat is no real threat */
   603                     if (is_pinned(gamestate, &(threats[i]))) {
   604                         reason = incheck?KING_IN_CHECK:
   605                             (piece==KING?KING_MOVES_INTO_CHECK:PIECE_PINNED);
   606                     } else {
   607                         threat = &(threats[i]);
   608                     }
   609                 }
   610             }
   611         }
   613         /* can't threaten specified position */
   614         if (!threat) {
   615             return reason;
   616         }
   618         memcpy(move, threat, sizeof(Move));
   619         return VALID_MOVE_SYNTAX;
   620     } else {
   621         return INVALID_POSITION;
   622     }
   623 }
   625 int eval_move(GameState *gamestate, char *mstr, Move *move, uint8_t color) {
   626     memset(move, 0, sizeof(Move));
   627     move->fromfile = POS_UNSPECIFIED;
   628     move->fromrow = POS_UNSPECIFIED;
   630     size_t len = strlen(mstr);
   631     if (len < 1 || len > 6) {
   632         return INVALID_MOVE_SYNTAX;
   633     }
   635     /* evaluate check/checkmate flags */
   636     if (mstr[len-1] == '+') {
   637         len--; mstr[len] = '\0';
   638         move->check = 1;
   639     } else if (mstr[len-1] == '#') {
   640         len--; mstr[len] = '\0';
   641         /* ignore - validation should set game state */
   642     }
   644     /* evaluate promotion */
   645     if (len > 3 && mstr[len-2] == '=') {
   646         move->promotion = getpiece(mstr[len-1]);
   647         if (!move->promotion) {
   648             return INVALID_MOVE_SYNTAX;
   649         } else {
   650             move->promotion |= color;
   651             len -= 2;
   652             mstr[len] = 0;
   653         }
   654     }
   656     if (len == 2) {
   657         /* pawn move (e.g. "e4") */
   658         move->piece = PAWN;
   659         move->tofile = fileidx(mstr[0]);
   660         move->torow = rowidx(mstr[1]);
   661     } else if (len == 3) {
   662         if (strcmp(mstr, "O-O") == 0) {
   663             /* king side castling */
   664             move->piece = KING;
   665             move->fromfile = fileidx('e');
   666             move->tofile = fileidx('g');
   667             move->fromrow = move->torow = color == WHITE ? 0 : 7;
   668         } else {
   669             /* move (e.g. "Nf3") */
   670             move->piece = getpiece(mstr[0]);
   671             move->tofile = fileidx(mstr[1]);
   672             move->torow = rowidx(mstr[2]);
   673         }
   674     } else if (len == 4) {
   675         move->piece = getpiece(mstr[0]);
   676         if (!move->piece) {
   677             move->piece = PAWN;
   678             move->fromfile = fileidx(mstr[0]);
   679         }
   680         if (mstr[1] == 'x') {
   681             /* capture (e.g. "Nxf3", "dxe5") */
   682             move->capture = 1;
   683         } else {
   684             /* move (e.g. "Ndf3", "N2c3", "e2e4") */
   685             if (isfile(mstr[1])) {
   686                 move->fromfile = fileidx(mstr[1]);
   687                 if (move->piece == PAWN) {
   688                     move->piece = 0;
   689                 }
   690             } else {
   691                 move->fromrow = rowidx(mstr[1]);
   692             }
   693         }
   694         move->tofile = fileidx(mstr[2]);
   695         move->torow = rowidx(mstr[3]);
   696     } else if (len == 5) {
   697         if (strcmp(mstr, "O-O-O") == 0) {
   698             /* queen side castling "O-O-O" */
   699             move->piece = KING;
   700             move->fromfile = fileidx('e');
   701             move->tofile = fileidx('c');
   702             move->fromrow = move->torow = color == WHITE ? 0 : 7;
   703         } else {
   704             move->piece = getpiece(mstr[0]);
   705             if (mstr[2] == 'x') {
   706                 move->capture = 1;
   707                 if (move->piece) {
   708                     /* capture (e.g. "Ndxf3") */
   709                     move->fromfile = fileidx(mstr[1]);
   710                 } else {
   711                     /* long notation capture (e.g. "e5xf6") */
   712                     move->piece = PAWN;
   713                     move->fromfile = fileidx(mstr[0]);
   714                     move->fromrow = rowidx(mstr[1]);
   715                 }
   716             } else {
   717                 /* long notation move (e.g. "Nc5a4") */
   718                 move->fromfile = fileidx(mstr[1]);
   719                 move->fromrow = rowidx(mstr[2]);
   720             }
   721             move->tofile = fileidx(mstr[3]);
   722             move->torow = rowidx(mstr[4]);
   723         }
   724     } else if (len == 6) {
   725         /* long notation capture (e.g. "Nc5xf3") */
   726         if (mstr[3] == 'x') {
   727             move->capture = 1;
   728             move->piece = getpiece(mstr[0]);
   729             move->fromfile = fileidx(mstr[1]);
   730             move->fromrow = rowidx(mstr[2]);
   731             move->tofile = fileidx(mstr[4]);
   732             move->torow = rowidx(mstr[5]);
   733         }
   734     }
   737     if (move->piece) {
   738         if (move->piece == PAWN
   739             && move->torow == (color==WHITE?7:0)
   740             && !move->promotion) {
   741             return NEED_PROMOTION;
   742         }
   744         move->piece |= color;
   745         if (move->fromfile == POS_UNSPECIFIED
   746             || move->fromrow == POS_UNSPECIFIED) {
   747             return getlocation(gamestate, move);
   748         } else {
   749             return chkidx(move) ? VALID_MOVE_SYNTAX : INVALID_POSITION;
   750         }
   751     } else {
   752         return INVALID_MOVE_SYNTAX;
   753     }
   754 }
   756 _Bool is_protected(GameState *gamestate, uint8_t row, uint8_t file,
   757         uint8_t color) {
   759     Move threats[16];
   760     uint8_t threatcount;
   761     if (get_real_threats(gamestate, row, file, color, threats, &threatcount)) {
   762         for (int i = 0 ; i < threatcount ; i++) {
   763             if (threats[i].piece != (color|KING)) {
   764                 return 1;
   765             }
   766         }
   767         return 0;
   768     } else {
   769         return 0;
   770     }
   771 }
   773 uint16_t remaining_movetime(GameInfo *gameinfo, GameState *gamestate,
   774         uint8_t color) {
   775     if (!gameinfo->timecontrol) {
   776         return 0;
   777     }
   779     if (gamestate->movelist) {
   780         uint16_t time = gameinfo->time;
   781         suseconds_t micros = 0;
   783         MoveList *movelist = color == WHITE ?
   784             gamestate->movelist : gamestate->movelist->next;
   786         while (movelist) {
   787             time += gameinfo->addtime;
   789             struct movetimeval *movetime = &(movelist->move.movetime);
   790             if (movetime->tv_sec >= time) {
   791                 return 0;
   792             }
   794             time -= movetime->tv_sec;
   795             micros += movetime->tv_usec;
   797             movelist = movelist->next ? movelist->next->next : NULL;
   798         }
   800         time_t sec;
   801         movelist = gamestate->lastmove;
   802         if ((movelist->move.piece & COLOR_MASK) != color) {
   803             struct movetimeval *lastmovetstamp = &(movelist->move.timestamp);
   804             struct timeval currenttstamp;
   805             gettimeofday(&currenttstamp, NULL);
   806             micros += currenttstamp.tv_usec - lastmovetstamp->tv_usec;
   807             sec = currenttstamp.tv_sec - lastmovetstamp->tv_sec;
   808             if (sec >= time) {
   809                 return 0;
   810             }
   812             time -= sec;
   813         }
   815         sec = micros / 1e6L;
   817         if (sec >= time) {
   818             return 0;
   819         }
   821         time -= sec;
   823         return time;
   824     } else {
   825         return gameinfo->time;
   826     }
   827 }

mercurial