src/game.c

Wed, 28 May 2014 15:47:57 +0200

author
Mike Becker <universe@uap-core.de>
date
Wed, 28 May 2014 15:47:57 +0200
changeset 47
d726e4b46c33
parent 46
4dcfb4c58b6d
child 48
0cedda2544da
permissions
-rw-r--r--

refactoring of getlocation mechanism for better short algebraic notation support (does now respect pinned pieces) + fixed a bug where a pawn could advance through a piece (e.g. e2e4 could jump over a piece on e3)

     1 /*
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * Copyright 2014 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>
    39 static const uint8_t boardx = 10, boardy = 10;
    40 static int inputy = 21; /* should be overridden on game startup */
    42 static int timecontrol(GameState *gamestate, GameInfo *gameinfo) {
    43     if (gameinfo->timecontrol) {
    44         uint16_t white = remaining_movetime(gameinfo, gamestate, WHITE);
    45         uint16_t black = remaining_movetime(gameinfo, gamestate, BLACK);
    46         mvprintw(boardy+4, boardx-1,
    47             "White time: %4" PRIu16 ":%02" PRIu16,
    48             white / 60, white % 60);
    49         mvprintw(boardy+5, boardx-1,
    50             "Black time: %4" PRIu16 ":%02" PRIu16,
    51             black / 60, black % 60);
    53         if (white == 0) {
    54             move(inputy, 0);
    55             printw("Time is over - Black wins!");
    56             clrtobot();
    57             refresh();
    58             return 1;
    59         }
    60         if (black == 0) {
    61             move(inputy, 0);
    62             printw("Time is over - White wins!");
    63             clrtobot();
    64             refresh();
    65             return 1;
    66         }
    67     }
    69     return 0;
    70 }
    72 static void draw_board(GameState *gamestate) {
    73     for (uint8_t y = 0 ; y < 8 ; y++) {
    74         for (uint8_t x = 0 ; x < 8 ; x++) {
    75             uint8_t col = gamestate->board[y][x] & COLOR_MASK;
    76             uint8_t piece = gamestate->board[y][x] & PIECE_MASK;
    77             char piecec;
    78             if (piece) {
    79                 piecec = piece == PAWN ? 'P' : getpiecechr(piece);
    80             } else {
    81                 piecec = ' ';
    82             }
    84             _Bool boardblack = (y&1)==(x&1);
    85             attrset((col==WHITE ? A_BOLD : A_DIM)|
    86                 COLOR_PAIR(col == WHITE ?
    87                     (boardblack ? COL_WB : COL_WW) :
    88                     (boardblack ? COL_BB : COL_BW)
    89                 )
    90             );
    92             int cy = gamestate->mycolor == WHITE ? boardy-y : boardy-7+y;
    93             int cx = gamestate->mycolor == WHITE ? boardx+x*3 : boardx+21-x*3;
    94             mvaddch(cy, cx, ' ');
    95             mvaddch(cy, cx+1, piecec);
    96             mvaddch(cy, cx+2, ' ');
    97         }
    98     }
   100     attrset(A_NORMAL);
   101     for (uint8_t i = 0 ; i < 8 ; i++) {
   102         int x = gamestate->mycolor == WHITE ? boardx+i*3+1 : boardx+22-i*3;
   103         int y = gamestate->mycolor == WHITE ? boardy-i : boardy-7+i;
   104         mvaddch(boardy+1, x, 'a'+i);
   105         mvaddch(y, boardx-2, '1'+i);
   106     }
   108     /* move log */
   109     // TODO: introduce window to avoid bugs with a long move log
   110     uint8_t logy = 0;
   111     const uint8_t logx = boardx + 30;
   112     int logi = 1;
   113     MoveList *logelem = gamestate->movelist;
   115     while (logelem) {
   116         logi++;
   117         if (logi % 2 == 0) {
   118             if ((logi - 2) % 4 == 0) {
   119                 logy++;
   120                 move(logy, logx);
   121             }
   122             printw("%d. ", logi / 2);
   123         }
   125         if (logelem) {
   126             Move move = logelem->move;
   127             if ((move.piece&PIECE_MASK) == KING &&
   128                 abs(move.tofile-move.fromfile) == 2) {
   129                 addstr(move.tofile==fileidx('c')?"O-O-O":"O-O");
   130             } else {
   131                 char logstr[] = {
   132                     getpiecechr(move.piece),
   133                     filechr(move.fromfile), rowchr(move.fromrow),
   134                     move.capture ? 'x':'\0',
   135                     filechr(move.tofile), rowchr(move.torow),
   136                     move.check ? '+' : (move.promotion ? '=' : '\0'),
   137                     move.promotion ? getpiecechr(move.promotion) : '\0'
   138                 };
   139                 for (int stri = 0 ; stri < sizeof(logstr) ; stri++) {
   140                     if (logstr[stri]) {
   141                         addch(logstr[stri]);
   142                     }
   143                 }
   144             }
   145             if (!logelem->next) {
   146                 if (gamestate->checkmate) {
   147                     addstr("\b#");
   148                 } else if (gamestate->stalemate) {
   149                     addstr(" stalemate");
   150                 }
   151             }
   152             addch(' ');
   154             logelem = logelem->next;
   155         }
   156     }
   157 }
   159 static void eval_move_failed_msg(int code) {
   160     switch (code) {
   161     case AMBIGUOUS_MOVE:
   162         printw("Ambiguous move - please specify the piece to move.");
   163         break;
   164     case INVALID_POSITION:
   165         printw("Cannot find the piece that shall be moved.");
   166         break;
   167     case NEED_PROMOTION:
   168         printw("You need to promote the pawn (append \"=Q\" e.g.)!");
   169         break;
   170     case KING_IN_CHECK:
   171         printw("Your king is in check!");
   172         break;
   173     case PIECE_PINNED:
   174         printw("This piece is pinned!");
   175         break;
   176     case INVALID_MOVE_SYNTAX:
   177         printw("Can't interpret move - please use algebraic notation.");
   178         break;
   179     default:
   180         printw("Unknown move parser error.");
   181     }
   182 }
   184 #define MOVESTR_BUFLEN 8
   185 static int domove_singlemachine(GameState *gamestate, GameInfo *gameinfo) {
   188     size_t bufpos = 0;
   189     char movestr[MOVESTR_BUFLEN];
   191     flushinp();
   192     while (1) {
   193         if (timecontrol(gamestate, gameinfo)) {
   194             return 1;
   195         }
   197         move(inputy, 0);
   198         printw(
   199             "Use chess notation to enter your move.\n"
   200             "Or type 'resign' to resign or 'remis' to end with remis.\n\n"
   201             "Type your move: ");
   202         clrtoeol();
   204         if (asyncgetnstr(movestr, &bufpos, MOVESTR_BUFLEN)) {
   205             if (strncmp(movestr, "resign", MOVESTR_BUFLEN) == 0) {
   206                 printw("%s resigned!",
   207                     gamestate->mycolor==WHITE?"White":"Black");
   208                 clrtoeol();
   209                 refresh();
   210                 return 1;
   211             } else if (strncmp(movestr, "remis", MOVESTR_BUFLEN) == 0) {
   212                 printw("Game ends remis.");
   213                 clrtoeol();
   214                 refresh();
   215                 return 1;
   216             } else {
   217                 Move move;
   218                 int eval_result = eval_move(gamestate, movestr, &move);
   219                 switch (eval_result) {
   220                 case VALID_MOVE_SYNTAX:
   221                     if (validate_move(gamestate, &move)) {
   222                         apply_move(gamestate, &move);
   223                         if (gamestate->checkmate) {
   224                             printw("Checkmate!");
   225                             clrtoeol();
   226                             return 1;
   227                         } else if (gamestate->stalemate) {
   228                             printw("Stalemate!");
   229                             clrtoeol();
   230                             return 1;
   231                         } else {
   232                             return 0;
   233                         }
   234                     } else {
   235                         printw("Invalid move.");
   236                     }
   237                     break;
   238                 default:
   239                     eval_move_failed_msg(eval_result);
   240                 }
   241                 clrtoeol();
   242             }
   243         }
   244     }
   245 }
   247 static int sendmove(GameState *gamestate, GameInfo *gameinfo, int opponent) {
   249     size_t bufpos = 0;
   250     char movestr[MOVESTR_BUFLEN];
   251     _Bool remisrejected = FALSE;
   252     uint8_t code;
   254     flushinp();
   255     while (1) {
   256         if (timecontrol(gamestate, gameinfo)) {
   257             net_send_code(opponent, NETCODE_TIMEOVER);
   258             return 1;
   259         }
   261         move(inputy, 0);
   262         if (remisrejected) {
   263             printw(
   264                 "Use chess notation to enter your move.\n"
   265                 "Remis offer rejected - type 'resign' to resign.      \n\n"
   266                 "Type your move: ");
   267         } else {
   268             printw(
   269                 "Use chess notation to enter your move.\n"
   270                 "Or type 'resign' to resign or 'remis' to offer remis.\n\n"
   271                 "Type your move: ");
   272         }
   273         clrtoeol();
   275         if (asyncgetnstr(movestr, &bufpos, MOVESTR_BUFLEN)) {
   276             if (strncmp(movestr, "resign", MOVESTR_BUFLEN) == 0) {
   277                 printw("You resigned!");
   278                 clrtoeol();
   279                 refresh();
   280                 net_send_code(opponent, NETCODE_RESIGN);
   281                 return 1;
   282             } else if (strncmp(movestr, "remis", MOVESTR_BUFLEN) == 0) {
   283                 if (!remisrejected) {
   284                     net_send_code(opponent, NETCODE_REMIS);
   285                     printw("Remis offer sent - waiting for acceptance...");
   286                     refresh();
   287                     code = net_recieve_code(opponent);
   288                     if (code == NETCODE_ACCEPT) {
   289                         printw("\rRemis accepted!");
   290                         clrtoeol();
   291                         refresh();
   292                         return 1;
   293                     } else if (code == NETCODE_CONNLOST) {
   294                         printw("\rYour opponent left the game.");
   295                         clrtoeol();
   296                         refresh();
   297                         return 1;
   298                     } else {
   299                         remisrejected = TRUE;
   300                     }
   301                 }
   302             } else {
   303                 Move move;
   304                 int eval_result = eval_move(gamestate, movestr, &move);
   305                 switch (eval_result) {
   306                 case VALID_MOVE_SYNTAX:
   307                     net_send_data(opponent, NETCODE_MOVE, &move, sizeof(Move));
   308                     code = net_recieve_code(opponent);
   309                     move.check = code == NETCODE_CHECK;
   310                     gamestate->checkmate = code == NETCODE_CHECKMATE;
   311                     gamestate->stalemate = code == NETCODE_STALEMATE;
   312                     if (code == NETCODE_DECLINE) {
   313                         printw("Invalid move.");
   314                     } else if (code == NETCODE_ACCEPT
   315                             || code == NETCODE_CHECK
   316                             || code == NETCODE_CHECKMATE
   317                             || code == NETCODE_STALEMATE) {
   318                         apply_move(gamestate, &move);
   319                         if (gamestate->checkmate) {
   320                             printw("Checkmate!");
   321                             clrtoeol();
   322                             return 1;
   323                         } else if (gamestate->stalemate) {
   324                             printw("Stalemate!");
   325                             clrtoeol();
   326                             return 1;
   327                         } else {
   328                             return 0;
   329                         }
   330                     } else if (code == NETCODE_CONNLOST) {
   331                         printw("Your opponent left the game.");
   332                         return 1;
   333                     } else {
   334                         printw("Invalid network response.");
   335                     }
   336                     break;
   337                 default:
   338                     eval_move_failed_msg(eval_result);
   339                 }
   340                 clrtoeol();
   341             }
   342         }
   343     }
   344 }
   346 static int recvmove(GameState *gamestate, GameInfo *gameinfo, int opponent) {
   348     struct timeval timeout;
   349     while (1) {
   350         timecontrol(gamestate, gameinfo);
   352         move(inputy, 0);
   353         printw("Awaiting opponent move...");
   354         clrtoeol();
   355         refresh();
   357         fd_set readfds;
   359         FD_ZERO(&readfds);
   360         FD_SET(opponent, &readfds);
   361         timeout.tv_sec = 0;
   362         timeout.tv_usec = 1e5;
   364         int result = select(opponent+1, &readfds, NULL, NULL, &timeout);
   365         if (result == -1) {
   366             printw("\rCannot perform asynchronous network IO");
   367             cbreak(); getch();
   368             exit(EXIT_FAILURE);
   369         }
   370         if (result > 0) {
   371             uint8_t code = net_recieve_code(opponent);
   373             Move move;
   374             switch (code) {
   375             case NETCODE_TIMEOVER:
   376                 printw("\rYour opponent's time ran out - you win!");
   377                 clrtoeol();
   378                 return 1;
   379             case NETCODE_RESIGN:
   380                 printw("\rYour opponent resigned!");
   381                 clrtoeol();
   382                 return 1;
   383             case NETCODE_CONNLOST:
   384                 printw("\rYour opponent has left the game.");
   385                 clrtoeol();
   386                 return 1;
   387             case NETCODE_REMIS:
   388                 if (prompt_yesno(
   389                     "\rYour opponent offers remis - do you accept")) {
   390                     printw("\rRemis accepted!");
   391                     clrtoeol();
   392                     net_send_code(opponent, NETCODE_ACCEPT);
   393                     return 1;
   394                 } else {
   395                     net_send_code(opponent, NETCODE_DECLINE);
   396                 }
   397                 break;
   398             case NETCODE_MOVE:
   399                 net_recieve_data(opponent, &move, sizeof(Move));
   400                 if (validate_move(gamestate, &move)) {
   401                     apply_move(gamestate, &move);
   402                     if (move.check) {
   403                         net_send_code(opponent, NETCODE_CHECK);
   404                     } else if (gamestate->checkmate) {
   405                         net_send_code(opponent, NETCODE_CHECKMATE);
   406                         printw("\rCheckmate!");
   407                         clrtoeol();
   408                         return 1;
   409                     } else if (gamestate->stalemate) {
   410                         net_send_code(opponent, NETCODE_STALEMATE);
   411                         printw("\rStalemate!");
   412                         clrtoeol();
   413                         return 1;
   414                     } else {
   415                         net_send_code(opponent, NETCODE_ACCEPT);
   416                     }
   417                     return 0;
   418                 } else {
   419                     net_send_code(opponent, NETCODE_DECLINE);
   420                 }
   421                 break;
   422             default:
   423                 printw("\nInvalid network request.");
   424             }
   425         }
   426     }
   427 }
   429 static void init_board(GameState *gamestate) {
   430     Board initboard = {
   431         {WROOK, WKNIGHT, WBISHOP, WQUEEN, WKING, WBISHOP, WKNIGHT, WROOK},
   432         {WPAWN, WPAWN,   WPAWN,   WPAWN,  WPAWN, WPAWN,   WPAWN,   WPAWN},
   433         {0,     0,       0,       0,      0,     0,       0,       0},
   434         {0,     0,       0,       0,      0,     0,       0,       0},
   435         {0,     0,       0,       0,      0,     0,       0,       0},
   436         {0,     0,       0,       0,      0,     0,       0,       0},
   437         {BPAWN, BPAWN,   BPAWN,   BPAWN,  BPAWN, BPAWN,   BPAWN,   BPAWN},
   438         {BROOK, BKNIGHT, BBISHOP, BQUEEN, BKING, BBISHOP, BKNIGHT, BROOK}
   439     };
   440     memcpy(gamestate->board, initboard, sizeof(Board));
   441 }
   443 void game_start_singlemachine(Settings *settings) {
   444     inputy = getmaxy(stdscr) - 6;
   446     GameState gamestate;
   447     memset(&gamestate, 0, sizeof(GameState));
   448     init_board(&gamestate);
   449     gamestate.mycolor = WHITE;
   451     _Bool running;
   452     do {
   453         clear();
   454         draw_board(&gamestate);
   455         running = !domove_singlemachine(&gamestate, &(settings->gameinfo));
   456         gamestate.mycolor = opponent_color(gamestate.mycolor);
   457     }  while (running);
   458     move(0,0);
   459     draw_board(&gamestate);
   461     gamestate_cleanup(&gamestate);
   462 }
   464 void game_start(Settings *settings, int opponent) {
   465     inputy = getmaxy(stdscr) - 6;
   467     _Bool myturn = is_server(settings) ==
   468         (settings->gameinfo.servercolor == WHITE);
   470     GameState gamestate;
   471     memset(&gamestate, 0, sizeof(GameState));
   472     init_board(&gamestate);
   473     gamestate.mycolor = myturn ? WHITE:BLACK;
   475     _Bool running;
   476     do {
   477         clear();
   478         draw_board(&gamestate);
   479         if (myturn) {
   480             running = !sendmove(&gamestate, &(settings->gameinfo), opponent);
   481         } else {
   482             running = !recvmove(&gamestate, &(settings->gameinfo), opponent);
   483         }
   484         myturn ^= TRUE;
   485     }  while (running);
   487     move(0,0);
   488     draw_board(&gamestate);
   490     gamestate_cleanup(&gamestate);
   491 }

mercurial