src/game.c

Thu, 17 Apr 2014 12:16:14 +0200

author
Mike Becker <universe@uap-core.de>
date
Thu, 17 Apr 2014 12:16:14 +0200
changeset 46
4dcfb4c58b6d
parent 45
e14a1d9aa91d
child 47
d726e4b46c33
permissions
-rw-r--r--

netcode is now aware of connection losses

     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     default:
   171         printw("Can't interpret move - please use algebraic notation.");
   172     }
   173 }
   175 #define MOVESTR_BUFLEN 8
   176 static int domove_singlemachine(GameState *gamestate, GameInfo *gameinfo) {
   179     size_t bufpos = 0;
   180     char movestr[MOVESTR_BUFLEN];
   182     flushinp();
   183     while (1) {
   184         if (timecontrol(gamestate, gameinfo)) {
   185             return 1;
   186         }
   188         move(inputy, 0);
   189         printw(
   190             "Use chess notation to enter your move.\n"
   191             "Or type 'resign' to resign or 'remis' to end with remis.\n\n"
   192             "Type your move: ");
   193         clrtoeol();
   195         if (asyncgetnstr(movestr, &bufpos, MOVESTR_BUFLEN)) {
   196             if (strncmp(movestr, "resign", MOVESTR_BUFLEN) == 0) {
   197                 printw("%s resigned!",
   198                     gamestate->mycolor==WHITE?"White":"Black");
   199                 clrtoeol();
   200                 refresh();
   201                 return 1;
   202             } else if (strncmp(movestr, "remis", MOVESTR_BUFLEN) == 0) {
   203                 printw("Game ends remis.");
   204                 clrtoeol();
   205                 refresh();
   206                 return 1;
   207             } else {
   208                 Move move;
   209                 int eval_result = eval_move(gamestate, movestr, &move);
   210                 switch (eval_result) {
   211                 case VALID_MOVE_SYNTAX:
   212                     if (validate_move(gamestate, &move)) {
   213                         apply_move(gamestate, &move);
   214                         if (gamestate->checkmate) {
   215                             printw("Checkmate!");
   216                             clrtoeol();
   217                             return 1;
   218                         } else if (gamestate->stalemate) {
   219                             printw("Stalemate!");
   220                             clrtoeol();
   221                             return 1;
   222                         } else {
   223                             return 0;
   224                         }
   225                     } else {
   226                         printw("Invalid move.");
   227                     }
   228                     break;
   229                 default:
   230                     eval_move_failed_msg(eval_result);
   231                 }
   232                 clrtoeol();
   233             }
   234         }
   235     }
   236 }
   238 static int sendmove(GameState *gamestate, GameInfo *gameinfo, int opponent) {
   240     size_t bufpos = 0;
   241     char movestr[MOVESTR_BUFLEN];
   242     _Bool remisrejected = FALSE;
   243     uint8_t code;
   245     flushinp();
   246     while (1) {
   247         if (timecontrol(gamestate, gameinfo)) {
   248             net_send_code(opponent, NETCODE_TIMEOVER);
   249             return 1;
   250         }
   252         move(inputy, 0);
   253         if (remisrejected) {
   254             printw(
   255                 "Use chess notation to enter your move.\n"
   256                 "Remis offer rejected - type 'resign' to resign.      \n\n"
   257                 "Type your move: ");
   258         } else {
   259             printw(
   260                 "Use chess notation to enter your move.\n"
   261                 "Or type 'resign' to resign or 'remis' to offer remis.\n\n"
   262                 "Type your move: ");
   263         }
   264         clrtoeol();
   266         if (asyncgetnstr(movestr, &bufpos, MOVESTR_BUFLEN)) {
   267             if (strncmp(movestr, "resign", MOVESTR_BUFLEN) == 0) {
   268                 printw("You resigned!");
   269                 clrtoeol();
   270                 refresh();
   271                 net_send_code(opponent, NETCODE_RESIGN);
   272                 return 1;
   273             } else if (strncmp(movestr, "remis", MOVESTR_BUFLEN) == 0) {
   274                 if (!remisrejected) {
   275                     net_send_code(opponent, NETCODE_REMIS);
   276                     printw("Remis offer sent - waiting for acceptance...");
   277                     refresh();
   278                     code = net_recieve_code(opponent);
   279                     if (code == NETCODE_ACCEPT) {
   280                         printw("\rRemis accepted!");
   281                         clrtoeol();
   282                         refresh();
   283                         return 1;
   284                     } else if (code == NETCODE_CONNLOST) {
   285                         printw("\rYour opponent left the game.");
   286                         clrtoeol();
   287                         refresh();
   288                         return 1;
   289                     } else {
   290                         remisrejected = TRUE;
   291                     }
   292                 }
   293             } else {
   294                 Move move;
   295                 int eval_result = eval_move(gamestate, movestr, &move);
   296                 switch (eval_result) {
   297                 case VALID_MOVE_SYNTAX:
   298                     net_send_data(opponent, NETCODE_MOVE, &move, sizeof(Move));
   299                     code = net_recieve_code(opponent);
   300                     move.check = code == NETCODE_CHECK;
   301                     gamestate->checkmate = code == NETCODE_CHECKMATE;
   302                     gamestate->stalemate = code == NETCODE_STALEMATE;
   303                     if (code == NETCODE_DECLINE) {
   304                         printw("Invalid move.");
   305                     } else if (code == NETCODE_ACCEPT
   306                             || code == NETCODE_CHECK
   307                             || code == NETCODE_CHECKMATE
   308                             || code == NETCODE_STALEMATE) {
   309                         apply_move(gamestate, &move);
   310                         if (gamestate->checkmate) {
   311                             printw("Checkmate!");
   312                             clrtoeol();
   313                             return 1;
   314                         } else if (gamestate->stalemate) {
   315                             printw("Stalemate!");
   316                             clrtoeol();
   317                             return 1;
   318                         } else {
   319                             return 0;
   320                         }
   321                     } else if (code == NETCODE_CONNLOST) {
   322                         printw("Your opponent left the game.");
   323                         return 1;
   324                     } else {
   325                         printw("Invalid network response.");
   326                     }
   327                     break;
   328                 default:
   329                     eval_move_failed_msg(eval_result);
   330                 }
   331                 clrtoeol();
   332             }
   333         }
   334     }
   335 }
   337 static int recvmove(GameState *gamestate, GameInfo *gameinfo, int opponent) {
   339     struct timeval timeout;
   340     while (1) {
   341         timecontrol(gamestate, gameinfo);
   343         move(inputy, 0);
   344         printw("Awaiting opponent move...");
   345         clrtoeol();
   346         refresh();
   348         fd_set readfds;
   350         FD_ZERO(&readfds);
   351         FD_SET(opponent, &readfds);
   352         timeout.tv_sec = 0;
   353         timeout.tv_usec = 1e5;
   355         int result = select(opponent+1, &readfds, NULL, NULL, &timeout);
   356         if (result == -1) {
   357             printw("\rCannot perform asynchronous network IO");
   358             cbreak(); getch();
   359             exit(EXIT_FAILURE);
   360         }
   361         if (result > 0) {
   362             uint8_t code = net_recieve_code(opponent);
   364             Move move;
   365             switch (code) {
   366             case NETCODE_TIMEOVER:
   367                 printw("\rYour opponent's time ran out - you win!");
   368                 clrtoeol();
   369                 return 1;
   370             case NETCODE_RESIGN:
   371                 printw("\rYour opponent resigned!");
   372                 clrtoeol();
   373                 return 1;
   374             case NETCODE_CONNLOST:
   375                 printw("\rYour opponent has left the game.");
   376                 clrtoeol();
   377                 return 1;
   378             case NETCODE_REMIS:
   379                 if (prompt_yesno(
   380                     "\rYour opponent offers remis - do you accept")) {
   381                     printw("\rRemis accepted!");
   382                     clrtoeol();
   383                     net_send_code(opponent, NETCODE_ACCEPT);
   384                     return 1;
   385                 } else {
   386                     net_send_code(opponent, NETCODE_DECLINE);
   387                 }
   388                 break;
   389             case NETCODE_MOVE:
   390                 net_recieve_data(opponent, &move, sizeof(Move));
   391                 if (validate_move(gamestate, &move)) {
   392                     apply_move(gamestate, &move);
   393                     if (move.check) {
   394                         net_send_code(opponent, NETCODE_CHECK);
   395                     } else if (gamestate->checkmate) {
   396                         net_send_code(opponent, NETCODE_CHECKMATE);
   397                         printw("\rCheckmate!");
   398                         clrtoeol();
   399                         return 1;
   400                     } else if (gamestate->stalemate) {
   401                         net_send_code(opponent, NETCODE_STALEMATE);
   402                         printw("\rStalemate!");
   403                         clrtoeol();
   404                         return 1;
   405                     } else {
   406                         net_send_code(opponent, NETCODE_ACCEPT);
   407                     }
   408                     return 0;
   409                 } else {
   410                     net_send_code(opponent, NETCODE_DECLINE);
   411                 }
   412                 break;
   413             default:
   414                 printw("\nInvalid network request.");
   415             }
   416         }
   417     }
   418 }
   420 static void init_board(GameState *gamestate) {
   421     Board initboard = {
   422         {WROOK, WKNIGHT, WBISHOP, WQUEEN, WKING, WBISHOP, WKNIGHT, WROOK},
   423         {WPAWN, WPAWN,   WPAWN,   WPAWN,  WPAWN, WPAWN,   WPAWN,   WPAWN},
   424         {0,     0,       0,       0,      0,     0,       0,       0},
   425         {0,     0,       0,       0,      0,     0,       0,       0},
   426         {0,     0,       0,       0,      0,     0,       0,       0},
   427         {0,     0,       0,       0,      0,     0,       0,       0},
   428         {BPAWN, BPAWN,   BPAWN,   BPAWN,  BPAWN, BPAWN,   BPAWN,   BPAWN},
   429         {BROOK, BKNIGHT, BBISHOP, BQUEEN, BKING, BBISHOP, BKNIGHT, BROOK}
   430     };
   431     memcpy(gamestate->board, initboard, sizeof(Board));
   432 }
   434 void game_start_singlemachine(Settings *settings) {
   435     inputy = getmaxy(stdscr) - 6;
   437     GameState gamestate;
   438     memset(&gamestate, 0, sizeof(GameState));
   439     init_board(&gamestate);
   440     gamestate.mycolor = WHITE;
   442     _Bool running;
   443     do {
   444         clear();
   445         draw_board(&gamestate);
   446         running = !domove_singlemachine(&gamestate, &(settings->gameinfo));
   447         gamestate.mycolor = opponent_color(gamestate.mycolor);
   448     }  while (running);
   449     move(0,0);
   450     draw_board(&gamestate);
   452     gamestate_cleanup(&gamestate);
   453 }
   455 void game_start(Settings *settings, int opponent) {
   456     inputy = getmaxy(stdscr) - 6;
   458     _Bool myturn = is_server(settings) ==
   459         (settings->gameinfo.servercolor == WHITE);
   461     GameState gamestate;
   462     memset(&gamestate, 0, sizeof(GameState));
   463     init_board(&gamestate);
   464     gamestate.mycolor = myturn ? WHITE:BLACK;
   466     _Bool running;
   467     do {
   468         clear();
   469         draw_board(&gamestate);
   470         if (myturn) {
   471             running = !sendmove(&gamestate, &(settings->gameinfo), opponent);
   472         } else {
   473             running = !recvmove(&gamestate, &(settings->gameinfo), opponent);
   474         }
   475         myturn ^= TRUE;
   476     }  while (running);
   478     move(0,0);
   479     draw_board(&gamestate);
   481     gamestate_cleanup(&gamestate);
   482 }

mercurial