src/game.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 63
611332453da0
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 "game.h"
    31 #include "network.h"
    32 #include "input.h"
    33 #include "colors.h"
    34 #include <ncurses.h>
    35 #include <string.h>
    36 #include <inttypes.h>
    37 #include <sys/select.h>
    38 #include <stdio.h>
    39 #include <errno.h>
    41 static const uint8_t boardx = 4, boardy = 10;
    42 static int inputy = 21; /* should be overridden on game startup */
    44 static int timecontrol(GameState *gamestate, GameInfo *gameinfo) {
    45     if (gameinfo->timecontrol) {
    46         uint16_t white = remaining_movetime(gameinfo, gamestate, WHITE);
    47         uint16_t black = remaining_movetime(gameinfo, gamestate, BLACK);
    48         mvprintw(boardy+4, boardx-1,
    49             "White time: %4" PRIu16 ":%02" PRIu16,
    50             white / 60, white % 60);
    51         mvprintw(boardy+5, boardx-1,
    52             "Black time: %4" PRIu16 ":%02" PRIu16,
    53             black / 60, black % 60);
    55         if (white == 0) {
    56             move(inputy, 0);
    57             printw("Time is over - Black wins!");
    58             clrtobot();
    59             refresh();
    60             return 1;
    61         }
    62         if (black == 0) {
    63             move(inputy, 0);
    64             printw("Time is over - White wins!");
    65             clrtobot();
    66             refresh();
    67             return 1;
    68         }
    69     }
    71     return 0;
    72 }
    74 static void draw_board(GameState *gamestate, uint8_t perspective) {
    75     char fen[90];
    76     compute_fen(fen, gamestate);
    77     mvaddstr(0, 0, fen);
    79     for (uint8_t y = 0 ; y < 8 ; y++) {
    80         for (uint8_t x = 0 ; x < 8 ; x++) {
    81             uint8_t col = gamestate->board[y][x] & COLOR_MASK;
    82             uint8_t piece = gamestate->board[y][x] & PIECE_MASK;
    83             char piecec;
    84             if (piece) {
    85                 piecec = piece == PAWN ? 'P' : getpiecechr(piece);
    86             } else {
    87                 piecec = ' ';
    88             }
    90             _Bool boardblack = (y&1)==(x&1);
    91             attrset((col==WHITE ? A_BOLD : A_DIM)|
    92                 COLOR_PAIR(col == WHITE ?
    93                     (boardblack ? COL_WB : COL_WW) :
    94                     (boardblack ? COL_BB : COL_BW)
    95                 )
    96             );
    98             int cy = perspective == WHITE ? boardy-y : boardy-7+y;
    99             int cx = perspective == WHITE ? boardx+x*3 : boardx+21-x*3;
   100             mvaddch(cy, cx, ' ');
   101             mvaddch(cy, cx+1, piecec);
   102             mvaddch(cy, cx+2, ' ');
   103         }
   104     }
   106     attrset(A_NORMAL);
   107     for (uint8_t i = 0 ; i < 8 ; i++) {
   108         int x = perspective == WHITE ? boardx+i*3+1 : boardx+22-i*3;
   109         int y = perspective == WHITE ? boardy-i : boardy-7+i;
   110         mvaddch(boardy+1, x, 'a'+i);
   111         mvaddch(y, boardx-2, '1'+i);
   112     }
   114     /* move log */
   115     uint8_t logy = 2;
   116     const uint8_t logx = boardx + 28;
   117     move(logy, logx);
   119     unsigned int logi = 0;
   120     MoveList *logelem = gamestate->movelist;
   122     /* wrap log after 45 moves */
   123     while (gamestate->movecount/6-logi/3 >= 15) {
   124         logelem = logelem->next->next;
   125         logi++;
   126     }
   128     while (logelem) {
   129         _Bool iswhite = (logelem->move.piece & COLOR_MASK) == WHITE;
   130         if (iswhite) {
   131             logi++;
   132             printw("%d. ", logi);
   133         }
   135         addstr(logelem->move.string);
   136         if (!iswhite && logi%3 == 0) {
   137             move(++logy, logx);
   138         } else {
   139             addch(' ');
   140         }
   142         logelem = logelem->next;
   143     }
   144 }
   146 static void eval_move_failed_msg(int code) {
   147     switch (code) {
   148     case AMBIGUOUS_MOVE:
   149         printw("Ambiguous move - please specify the piece to move.");
   150         break;
   151     case INVALID_POSITION:
   152         printw("No piece can be moved this way.");
   153         break;
   154     case NEED_PROMOTION:
   155         printw("You need to promote the pawn (append \"=Q\" e.g.)!");
   156         break;
   157     case KING_IN_CHECK:
   158         printw("Your king is in check!");
   159         break;
   160     case PIECE_PINNED:
   161         printw("This piece is pinned!");
   162         break;
   163     case INVALID_MOVE_SYNTAX:
   164         printw("Can't interpret move - please use algebraic notation.");
   165         break;
   166     case RULES_VIOLATED:
   167         printw("Move does not comply chess rules.");
   168         break;
   169     case KING_MOVES_INTO_CHECK:
   170         printw("Can't move the king into a check position.");
   171         break;
   172     default:
   173         printw("Unknown move parser error.");
   174     }
   175 }
   177 static void save_pgn(GameState *gamestate, GameInfo *gameinfo) {
   178     printw("Filename: ");
   179     clrtoeol();
   180     refresh();
   182     char filename[64];
   183     int y = getcury(stdscr);
   184     if (getnstr(filename, 64) == OK && filename[0] != '\0') {
   185         move(y, 0);
   186         FILE *file = fopen(filename, "w");
   187         if (file) {
   188             write_pgn(file, gamestate, gameinfo);
   189             fclose(file);
   190             printw("File saved.");
   191         } else {
   192             printw("Can't write to file (%s).", strerror(errno));
   193         }
   194         clrtoeol();
   195     }
   196 }
   198 #define MOVESTR_BUFLEN 10
   199 static int domove_singlemachine(GameState *gamestate,
   200         GameInfo *gameinfo, uint8_t curcolor) {
   203     size_t bufpos = 0;
   204     char movestr[MOVESTR_BUFLEN];
   206     flushinp();
   207     while (1) {
   208         if (timecontrol(gamestate, gameinfo)) {
   209             return 1;
   210         }
   212         move(inputy, 0);
   213         printw(
   214             "Use chess notation to enter your move.\n"
   215             "Or use a command: remis, resign, savepgn\n\n"
   216             "Type your move: ");
   217         clrtoeol();
   219         if (asyncgetnstr(movestr, &bufpos, MOVESTR_BUFLEN)) {
   220             if (strncmp(movestr, "resign", MOVESTR_BUFLEN) == 0) {
   221                 gamestate->resign = 1;
   222                 printw("%s resigned!",
   223                     curcolor==WHITE?"White":"Black");
   224                 clrtobot();
   225                 refresh();
   226                 return 1;
   227             } else if (strncmp(movestr, "remis", MOVESTR_BUFLEN) == 0) {
   228                 gamestate->remis = 1;
   229                 printw("Game ends remis.");
   230                 clrtobot();
   231                 refresh();
   232                 return 1;
   233             } else if (strncmp(movestr, "savepgn", MOVESTR_BUFLEN) == 0) {
   234                 save_pgn(gamestate, gameinfo);
   235             } else {
   236                 Move move;
   237                 int result = eval_move(gamestate, movestr, &move, curcolor);
   238                 if (result == VALID_MOVE_SYNTAX) {
   239                     result = validate_move(gamestate, &move);
   240                     if (result == VALID_MOVE_SEMANTICS) {
   241                         apply_move(gamestate, &move);
   242                         if (gamestate->checkmate) {
   243                             printw("Checkmate!");
   244                             clrtoeol();
   245                             return 1;
   246                         } else if (gamestate->stalemate) {
   247                             printw("Stalemate!");
   248                             clrtoeol();
   249                             return 1;
   250                         } else {
   251                             return 0;
   252                         }
   253                     } else {
   254                         eval_move_failed_msg(result);
   255                     }
   256                 } else {
   257                     eval_move_failed_msg(result);
   258                 }
   259                 clrtoeol();
   260             }
   261         }
   262     }
   263 }
   265 static int sendmove(GameState *gamestate, GameInfo *gameinfo,
   266         int opponent, uint8_t mycolor) {
   268     size_t bufpos = 0;
   269     char movestr[MOVESTR_BUFLEN];
   270     _Bool remisrejected = FALSE;
   271     uint8_t code;
   273     flushinp();
   274     while (1) {
   275         if (timecontrol(gamestate, gameinfo)) {
   276             net_send_code(opponent, NETCODE_TIMEOVER);
   277             return 1;
   278         }
   280         move(inputy, 0);
   281         if (remisrejected) {
   282             printw(
   283                 "Use chess notation to enter your move.\n"
   284                 "Remis offer rejected                    \n\n"
   285                 "Type your move: ");
   286         } else {
   287             printw(
   288                 "Use chess notation to enter your move.\n"
   289                 "Or use a command: remis, resign, savepgn\n\n"
   290                 "Type your move: ");
   291         }
   292         clrtoeol();
   294         if (asyncgetnstr(movestr, &bufpos, MOVESTR_BUFLEN)) {
   295             if (strncmp(movestr, "resign", MOVESTR_BUFLEN) == 0) {
   296                 gamestate->resign = 1;
   297                 printw("You resigned!");
   298                 clrtoeol();
   299                 refresh();
   300                 net_send_code(opponent, NETCODE_RESIGN);
   301                 return 1;
   302             } else if (strncmp(movestr, "savepgn", MOVESTR_BUFLEN) == 0) {
   303                 save_pgn(gamestate, gameinfo);
   304             } else if (strncmp(movestr, "remis", MOVESTR_BUFLEN) == 0) {
   305                 if (!remisrejected) {
   306                     net_send_code(opponent, NETCODE_REMIS);
   307                     printw("Remis offer sent - waiting for acceptance...");
   308                     refresh();
   309                     code = net_recieve_code(opponent);
   310                     if (code == NETCODE_ACCEPT) {
   311                         gamestate->remis = 1;
   312                         printw("\rRemis accepted!");
   313                         clrtoeol();
   314                         refresh();
   315                         return 1;
   316                     } else if (code == NETCODE_CONNLOST) {
   317                         printw("\rYour opponent left the game.");
   318                         clrtoeol();
   319                         refresh();
   320                         return 1;
   321                     } else {
   322                         remisrejected = TRUE;
   323                     }
   324                 }
   325             } else {
   326                 Move move;
   327                 int eval_result = eval_move(gamestate, movestr, &move, mycolor);
   328                 switch (eval_result) {
   329                 case VALID_MOVE_SYNTAX:
   330                     net_send_data(opponent, NETCODE_MOVE, &move, sizeof(Move));
   331                     code = net_recieve_code(opponent);
   332                     move.check = code == NETCODE_CHECK ||
   333                         code == NETCODE_CHECKMATE;
   334                     gamestate->checkmate = code == NETCODE_CHECKMATE;
   335                     gamestate->stalemate = code == NETCODE_STALEMATE;
   336                     if (code == NETCODE_DECLINE) {
   337                         uint32_t reason;
   338                         net_recieve_data(opponent, &reason, sizeof(uint32_t));
   339                         reason = ntohl(reason);
   340                         eval_move_failed_msg(reason);
   341                     } else if (code == NETCODE_ACCEPT
   342                             || code == NETCODE_CHECK
   343                             || code == NETCODE_CHECKMATE
   344                             || code == NETCODE_STALEMATE) {
   345                         apply_move(gamestate, &move);
   346                         if (gamestate->checkmate) {
   347                             printw("Checkmate!");
   348                             clrtoeol();
   349                             return 1;
   350                         } else if (gamestate->stalemate) {
   351                             printw("Stalemate!");
   352                             clrtoeol();
   353                             return 1;
   354                         } else {
   355                             return 0;
   356                         }
   357                     } else if (code == NETCODE_CONNLOST) {
   358                         printw("Your opponent left the game.");
   359                         return 1;
   360                     } else {
   361                         printw("Invalid network response.");
   362                     }
   363                     break;
   364                 default:
   365                     eval_move_failed_msg(eval_result);
   366                 }
   367                 clrtoeol();
   368             }
   369         }
   370     }
   371 }
   373 static int recvmove(GameState *gamestate, GameInfo *gameinfo, int opponent) {
   375     struct timeval timeout;
   376     while (1) {
   377         timecontrol(gamestate, gameinfo);
   379         move(inputy, 0);
   380         printw("Awaiting opponent move...");
   381         clrtoeol();
   382         refresh();
   384         fd_set readfds;
   386         FD_ZERO(&readfds);
   387         FD_SET(opponent, &readfds);
   388         timeout.tv_sec = 0;
   389         timeout.tv_usec = 1e5;
   391         // TODO: allow commands
   393         int result = select(opponent+1, &readfds, NULL, NULL, &timeout);
   394         if (result == -1) {
   395             printw("\rCannot perform asynchronous network IO");
   396             cbreak(); getch();
   397             exit(EXIT_FAILURE);
   398         }
   399         if (result > 0) {
   400             uint8_t code = net_recieve_code(opponent);
   402             Move move;
   403             switch (code) {
   404             case NETCODE_TIMEOVER:
   405                 printw("\rYour opponent's time ran out - you win!");
   406                 clrtoeol();
   407                 return 1;
   408             case NETCODE_RESIGN:
   409                 gamestate->resign = 1;
   410                 printw("\rYour opponent resigned!");
   411                 clrtoeol();
   412                 return 1;
   413             case NETCODE_CONNLOST:
   414                 printw("\rYour opponent has left the game.");
   415                 clrtoeol();
   416                 return 1;
   417             case NETCODE_REMIS:
   418                 if (prompt_yesno(
   419                     "\rYour opponent offers remis - do you accept")) {
   420                     gamestate->remis = 1;
   421                     printw("\rRemis accepted!");
   422                     clrtoeol();
   423                     net_send_code(opponent, NETCODE_ACCEPT);
   424                     return 1;
   425                 } else {
   426                     net_send_code(opponent, NETCODE_DECLINE);
   427                 }
   428                 break;
   429             case NETCODE_MOVE:
   430                 net_recieve_data(opponent, &move, sizeof(Move));
   431                 code = validate_move(gamestate, &move);
   432                 if (code == VALID_MOVE_SEMANTICS) {
   433                     apply_move(gamestate, &move);
   434                     if (gamestate->checkmate) {
   435                         net_send_code(opponent, NETCODE_CHECKMATE);
   436                         printw("\rCheckmate!");
   437                         clrtoeol();
   438                         return 1;
   439                     } else if (gamestate->stalemate) {
   440                         net_send_code(opponent, NETCODE_STALEMATE);
   441                         printw("\rStalemate!");
   442                         clrtoeol();
   443                         return 1;
   444                     } else if (move.check) {
   445                         net_send_code(opponent, NETCODE_CHECK);
   446                     } else {
   447                         net_send_code(opponent, NETCODE_ACCEPT);
   448                     }
   449                     return 0;
   450                 } else {
   451                     uint32_t reason = htonl(code);
   452                     net_send_data(opponent, NETCODE_DECLINE,
   453                         &reason, sizeof(uint32_t));
   454                 }
   455                 break;
   456             default:
   457                 printw("\nInvalid network request.");
   458             }
   459         }
   460     }
   461 }
   463 static void post_game(GameState *gamestate, GameInfo *gameinfo) {
   464     move(0,0);
   465     draw_board(gamestate, WHITE);
   467     // TODO: network connection is still open here - think about it!
   469     mvaddstr(getmaxy(stdscr)-1, 0,
   470         "Press 'q' to quit or 's' to save a PGN file...");
   471     refresh();
   472     flushinp();
   474     noecho();
   475     int c;
   476     do {
   477         c = getch();
   478         if (c == 's') {
   479             addch('\r');
   480             echo();
   481             save_pgn(gamestate, gameinfo);
   482             addstr(" Press 'q' to quit...");
   483             noecho();
   484         }
   485     } while (c != 'q');
   486     echo();
   488     gamestate_cleanup(gamestate);
   489 }
   491 void game_start_singlemachine(Settings *settings) {
   492     inputy = getmaxy(stdscr) - 6;
   494     GameState gamestate;
   495     gamestate_init(&gamestate);
   496     uint8_t curcol = WHITE;
   498     if (settings->continuepgn) {
   499         FILE *pgnfile = fopen(settings->continuepgn, "r");
   500         if (pgnfile) {
   501             int result = read_pgn(pgnfile, &gamestate, &(settings->gameinfo));
   502             long position = ftell(pgnfile);
   503             fclose(pgnfile);
   504             if (result) {
   505                 printw("Invalid PGN file content at position %ld:\n%s\n",
   506                         position, pgn_error_str(result));
   507                 return;
   508             }
   509             if (!is_game_running(&gamestate)) {
   510                 addstr("Game has ended. Use -S to analyze it.\n");
   511                 return;
   512             }
   513             curcol = opponent_color(gamestate.lastmove->move.piece&COLOR_MASK);
   514         } else {
   515             printw("Can't read PGN file (%s)\n", strerror(errno));
   516             return;
   517         }
   518     }
   520     _Bool running;
   521     do {
   522         clear();
   523         draw_board(&gamestate, curcol);
   524         running = !domove_singlemachine(&gamestate,
   525             &(settings->gameinfo), curcol);
   526         curcol = opponent_color(curcol);
   527     }  while (running);
   529     post_game(&gamestate, &(settings->gameinfo));
   530 }
   532 void game_continue(Settings *settings, int opponent, GameState *gamestate) {
   533     inputy = getmaxy(stdscr) - 6;
   535     uint8_t mycolor = is_server(settings) ? settings->gameinfo.servercolor :
   536         opponent_color(settings->gameinfo.servercolor);
   538     _Bool myturn = (gamestate->lastmove ?
   539         (gamestate->lastmove->move.piece & COLOR_MASK) : BLACK) != mycolor;
   541     _Bool running;
   542     do {
   543         clear();
   544         draw_board(gamestate, mycolor);
   545         if (myturn) {
   546             running = !sendmove(gamestate, &(settings->gameinfo),
   547                 opponent, mycolor);
   548         } else {
   549             running = !recvmove(gamestate, &(settings->gameinfo), opponent);
   550         }
   551         myturn ^= TRUE;
   552     }  while (running);
   554     post_game(gamestate, &(settings->gameinfo));
   555 }
   557 void game_start(Settings *settings, int opponent) {
   558     GameState gamestate;
   559     gamestate_init(&gamestate);
   561     game_continue(settings, opponent, &gamestate);
   562 }

mercurial