src/game.c

Wed, 11 Jun 2014 15:38:01 +0200

author
Mike Becker <universe@uap-core.de>
date
Wed, 11 Jun 2014 15:38:01 +0200
changeset 48
0cedda2544da
parent 47
d726e4b46c33
child 49
02c509a44e98
permissions
-rw-r--r--

added return code to move validation (for more informative messages) + fixed a bug where simulations added movelist items to the original gamestate

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2014 Mike Becker. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   1. Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *   2. Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "game.h"
#include "network.h"
#include "input.h"
#include "colors.h"
#include <ncurses.h>
#include <string.h>
#include <inttypes.h>
#include <sys/select.h>

static const uint8_t boardx = 10, boardy = 10;
static int inputy = 21; /* should be overridden on game startup */

static int timecontrol(GameState *gamestate, GameInfo *gameinfo) {
    if (gameinfo->timecontrol) {
        uint16_t white = remaining_movetime(gameinfo, gamestate, WHITE);
        uint16_t black = remaining_movetime(gameinfo, gamestate, BLACK);
        mvprintw(boardy+4, boardx-1,
            "White time: %4" PRIu16 ":%02" PRIu16,
            white / 60, white % 60);
        mvprintw(boardy+5, boardx-1,
            "Black time: %4" PRIu16 ":%02" PRIu16,
            black / 60, black % 60);
    
        if (white == 0) {
            move(inputy, 0);
            printw("Time is over - Black wins!");
            clrtobot();
            refresh();
            return 1;
        }
        if (black == 0) {
            move(inputy, 0);
            printw("Time is over - White wins!");
            clrtobot();
            refresh();
            return 1;
        }
    }
    
    return 0;
}

static void draw_board(GameState *gamestate) {
    for (uint8_t y = 0 ; y < 8 ; y++) {
        for (uint8_t x = 0 ; x < 8 ; x++) {
            uint8_t col = gamestate->board[y][x] & COLOR_MASK;
            uint8_t piece = gamestate->board[y][x] & PIECE_MASK;
            char piecec;
            if (piece) {
                piecec = piece == PAWN ? 'P' : getpiecechr(piece);
            } else {
                piecec = ' ';
            }
            
            _Bool boardblack = (y&1)==(x&1);
            attrset((col==WHITE ? A_BOLD : A_DIM)|
                COLOR_PAIR(col == WHITE ?
                    (boardblack ? COL_WB : COL_WW) :
                    (boardblack ? COL_BB : COL_BW)
                )
            );
            
            int cy = gamestate->mycolor == WHITE ? boardy-y : boardy-7+y;
            int cx = gamestate->mycolor == WHITE ? boardx+x*3 : boardx+21-x*3;
            mvaddch(cy, cx, ' ');
            mvaddch(cy, cx+1, piecec);
            mvaddch(cy, cx+2, ' ');
        }
    }
    
    attrset(A_NORMAL);
    for (uint8_t i = 0 ; i < 8 ; i++) {
        int x = gamestate->mycolor == WHITE ? boardx+i*3+1 : boardx+22-i*3;
        int y = gamestate->mycolor == WHITE ? boardy-i : boardy-7+i;
        mvaddch(boardy+1, x, 'a'+i);
        mvaddch(y, boardx-2, '1'+i);
    }
    
    /* move log */
    // TODO: introduce window to avoid bugs with a long move log
    uint8_t logy = 0;
    const uint8_t logx = boardx + 30;
    int logi = 1;
    MoveList *logelem = gamestate->movelist;
    
    while (logelem) {
        logi++;
        if (logi % 2 == 0) {
            if ((logi - 2) % 4 == 0) {
                logy++;
                move(logy, logx);
            }
            printw("%d. ", logi / 2);
        }

        if (logelem) {
            Move move = logelem->move;
            if ((move.piece&PIECE_MASK) == KING &&
                abs(move.tofile-move.fromfile) == 2) {
                addstr(move.tofile==fileidx('c')?"O-O-O":"O-O");
            } else {
                char logstr[] = {
                    getpiecechr(move.piece),
                    filechr(move.fromfile), rowchr(move.fromrow),
                    move.capture ? 'x':'\0',
                    filechr(move.tofile), rowchr(move.torow),
                    move.check ? '+' : (move.promotion ? '=' : '\0'),
                    move.promotion ? getpiecechr(move.promotion) : '\0'
                };
                for (int stri = 0 ; stri < sizeof(logstr) ; stri++) {
                    if (logstr[stri]) {
                        addch(logstr[stri]);
                    }
                }
            }
            if (!logelem->next) {
                if (gamestate->checkmate) {
                    addstr("\b#");
                } else if (gamestate->stalemate) {
                    addstr(" stalemate");
                }
            }
            addch(' ');
            
            logelem = logelem->next;
        }
    }
}

static void eval_move_failed_msg(int code) {
    switch (code) {
    case AMBIGUOUS_MOVE:
        printw("Ambiguous move - please specify the piece to move.");
        break;
    case INVALID_POSITION:
        printw("No piece can be moved this way.");
        break;
    case NEED_PROMOTION:
        printw("You need to promote the pawn (append \"=Q\" e.g.)!");
        break;
    case KING_IN_CHECK:
        printw("Your king is in check!");
        break;
    case PIECE_PINNED:
        printw("This piece is pinned!");
        break;
    case INVALID_MOVE_SYNTAX:
        printw("Can't interpret move - please use algebraic notation.");
        break;
    case RULES_VIOLATED:
        printw("Move does not comply chess rules.");
        break;
    case KING_MOVES_INTO_CHECK:
        printw("Can't move the king into a check position.");
        break;
    default:
        printw("Unknown move parser error.");
    }
}

#define MOVESTR_BUFLEN 8
static int domove_singlemachine(GameState *gamestate, GameInfo *gameinfo) {
    

    size_t bufpos = 0;
    char movestr[MOVESTR_BUFLEN];
    
    flushinp();
    while (1) {
        if (timecontrol(gamestate, gameinfo)) {
            return 1;
        }
        
        move(inputy, 0);
        printw(
            "Use chess notation to enter your move.\n"
            "Or type 'resign' to resign or 'remis' to end with remis.\n\n"
            "Type your move: ");
        clrtoeol();
        
        if (asyncgetnstr(movestr, &bufpos, MOVESTR_BUFLEN)) {
            if (strncmp(movestr, "resign", MOVESTR_BUFLEN) == 0) {
                printw("%s resigned!",
                    gamestate->mycolor==WHITE?"White":"Black");
                clrtoeol();
                refresh();
                return 1;
            } else if (strncmp(movestr, "remis", MOVESTR_BUFLEN) == 0) {
                printw("Game ends remis.");
                clrtoeol();
                refresh();
                return 1;
            } else {
                Move move;
                int eval_result = eval_move(gamestate, movestr, &move);
                switch (eval_result) {
                case VALID_MOVE_SYNTAX:
                    eval_result = validate_move(gamestate, &move);
                    if (eval_result == VALID_MOVE_SEMANTICS) {
                        apply_move(gamestate, &move);
                        if (gamestate->checkmate) {
                            printw("Checkmate!");
                            clrtoeol();
                            return 1;
                        } else if (gamestate->stalemate) {
                            printw("Stalemate!");
                            clrtoeol();
                            return 1;
                        } else {
                            return 0;
                        }
                    } else {
                        eval_move_failed_msg(eval_result);
                    }
                    break;
                default:
                    eval_move_failed_msg(eval_result);
                }
                clrtoeol();
            }
        }
    }
}

static int sendmove(GameState *gamestate, GameInfo *gameinfo, int opponent) {
    
    size_t bufpos = 0;
    char movestr[MOVESTR_BUFLEN];
    _Bool remisrejected = FALSE;
    uint8_t code;
    
    flushinp();
    while (1) {
        if (timecontrol(gamestate, gameinfo)) {
            net_send_code(opponent, NETCODE_TIMEOVER);
            return 1;
        }
        
        move(inputy, 0);
        if (remisrejected) {
            printw(
                "Use chess notation to enter your move.\n"
                "Remis offer rejected - type 'resign' to resign.      \n\n"
                "Type your move: ");
        } else {
            printw(
                "Use chess notation to enter your move.\n"
                "Or type 'resign' to resign or 'remis' to offer remis.\n\n"
                "Type your move: ");
        }
        clrtoeol();
        
        if (asyncgetnstr(movestr, &bufpos, MOVESTR_BUFLEN)) {
            if (strncmp(movestr, "resign", MOVESTR_BUFLEN) == 0) {
                printw("You resigned!");
                clrtoeol();
                refresh();
                net_send_code(opponent, NETCODE_RESIGN);
                return 1;
            } else if (strncmp(movestr, "remis", MOVESTR_BUFLEN) == 0) {
                if (!remisrejected) {
                    net_send_code(opponent, NETCODE_REMIS);
                    printw("Remis offer sent - waiting for acceptance...");
                    refresh();
                    code = net_recieve_code(opponent);
                    if (code == NETCODE_ACCEPT) {
                        printw("\rRemis accepted!");
                        clrtoeol();
                        refresh();
                        return 1;
                    } else if (code == NETCODE_CONNLOST) {
                        printw("\rYour opponent left the game.");
                        clrtoeol();
                        refresh();
                        return 1;
                    } else {
                        remisrejected = TRUE;
                    }
                }
            } else {
                Move move;
                int eval_result = eval_move(gamestate, movestr, &move);
                switch (eval_result) {
                case VALID_MOVE_SYNTAX:
                    net_send_data(opponent, NETCODE_MOVE, &move, sizeof(Move));
                    code = net_recieve_code(opponent);
                    move.check = code == NETCODE_CHECK ||
                        code == NETCODE_CHECKMATE;
                    gamestate->checkmate = code == NETCODE_CHECKMATE;
                    gamestate->stalemate = code == NETCODE_STALEMATE;
                    if (code == NETCODE_DECLINE) {
                        uint32_t reason;
                        net_recieve_data(opponent, &reason, sizeof(uint32_t));
                        reason = ntohl(reason);
                        eval_move_failed_msg(reason);
                    } else if (code == NETCODE_ACCEPT
                            || code == NETCODE_CHECK
                            || code == NETCODE_CHECKMATE
                            || code == NETCODE_STALEMATE) {
                        apply_move(gamestate, &move);
                        if (gamestate->checkmate) {
                            printw("Checkmate!");
                            clrtoeol();
                            return 1;
                        } else if (gamestate->stalemate) {
                            printw("Stalemate!");
                            clrtoeol();
                            return 1;
                        } else {
                            return 0;
                        }
                    } else if (code == NETCODE_CONNLOST) {
                        printw("Your opponent left the game.");
                        return 1;
                    } else {
                        printw("Invalid network response.");
                    }
                    break;
                default:
                    eval_move_failed_msg(eval_result);
                }
                clrtoeol();
            }
        }
    }
}

static int recvmove(GameState *gamestate, GameInfo *gameinfo, int opponent) {
    
    struct timeval timeout;
    while (1) {
        timecontrol(gamestate, gameinfo);
        
        move(inputy, 0);
        printw("Awaiting opponent move...");
        clrtoeol();
        refresh();

        fd_set readfds;
        
        FD_ZERO(&readfds);
        FD_SET(opponent, &readfds);
        timeout.tv_sec = 0;
        timeout.tv_usec = 1e5;
        
        int result = select(opponent+1, &readfds, NULL, NULL, &timeout);
        if (result == -1) {
            printw("\rCannot perform asynchronous network IO");
            cbreak(); getch();
            exit(EXIT_FAILURE);
        }
        if (result > 0) {
            uint8_t code = net_recieve_code(opponent);

            Move move;
            switch (code) {
            case NETCODE_TIMEOVER:
                printw("\rYour opponent's time ran out - you win!");
                clrtoeol();
                return 1;
            case NETCODE_RESIGN:
                printw("\rYour opponent resigned!");
                clrtoeol();
                return 1;
            case NETCODE_CONNLOST:
                printw("\rYour opponent has left the game.");
                clrtoeol();
                return 1;
            case NETCODE_REMIS:
                if (prompt_yesno(
                    "\rYour opponent offers remis - do you accept")) {
                    printw("\rRemis accepted!");
                    clrtoeol();
                    net_send_code(opponent, NETCODE_ACCEPT);
                    return 1;
                } else {
                    net_send_code(opponent, NETCODE_DECLINE);
                }
                break;
            case NETCODE_MOVE:
                net_recieve_data(opponent, &move, sizeof(Move));
                code = validate_move(gamestate, &move);
                if (code == VALID_MOVE_SEMANTICS) {
                    apply_move(gamestate, &move);
                    if (move.check) {
                        net_send_code(opponent, NETCODE_CHECK);
                    } else if (gamestate->checkmate) {
                        net_send_code(opponent, NETCODE_CHECKMATE);
                        printw("\rCheckmate!");
                        clrtoeol();
                        return 1;
                    } else if (gamestate->stalemate) {
                        net_send_code(opponent, NETCODE_STALEMATE);
                        printw("\rStalemate!");
                        clrtoeol();
                        return 1;
                    } else {
                        net_send_code(opponent, NETCODE_ACCEPT);
                    }
                    return 0;
                } else {
                    uint32_t reason = htonl(code);
                    net_send_data(opponent, NETCODE_DECLINE,
                        &reason, sizeof(uint32_t));
                }
                break;
            default:
                printw("\nInvalid network request.");
            }
        }
    }
}

static void init_board(GameState *gamestate) {
    Board initboard = {
        {WROOK, WKNIGHT, WBISHOP, WQUEEN, WKING, WBISHOP, WKNIGHT, WROOK},
        {WPAWN, WPAWN,   WPAWN,   WPAWN,  WPAWN, WPAWN,   WPAWN,   WPAWN},
        {0,     0,       0,       0,      0,     0,       0,       0},
        {0,     0,       0,       0,      0,     0,       0,       0},
        {0,     0,       0,       0,      0,     0,       0,       0},
        {0,     0,       0,       0,      0,     0,       0,       0},
        {BPAWN, BPAWN,   BPAWN,   BPAWN,  BPAWN, BPAWN,   BPAWN,   BPAWN},
        {BROOK, BKNIGHT, BBISHOP, BQUEEN, BKING, BBISHOP, BKNIGHT, BROOK}
    };
    memcpy(gamestate->board, initboard, sizeof(Board));
}

void game_start_singlemachine(Settings *settings) {
    inputy = getmaxy(stdscr) - 6;
    
    GameState gamestate;
    memset(&gamestate, 0, sizeof(GameState));
    init_board(&gamestate);
    gamestate.mycolor = WHITE;

    _Bool running;
    do {
        clear();
        draw_board(&gamestate);
        running = !domove_singlemachine(&gamestate, &(settings->gameinfo));
        gamestate.mycolor = opponent_color(gamestate.mycolor);
    }  while (running);
    move(0,0);
    draw_board(&gamestate);
    
    gamestate_cleanup(&gamestate);
}

void game_start(Settings *settings, int opponent) {
    inputy = getmaxy(stdscr) - 6;
    
    _Bool myturn = is_server(settings) ==
        (settings->gameinfo.servercolor == WHITE);
    
    GameState gamestate;
    memset(&gamestate, 0, sizeof(GameState));
    init_board(&gamestate);
    gamestate.mycolor = myturn ? WHITE:BLACK;
    
    _Bool running;
    do {
        clear();
        draw_board(&gamestate);
        if (myturn) {
            running = !sendmove(&gamestate, &(settings->gameinfo), opponent);
        } else {
            running = !recvmove(&gamestate, &(settings->gameinfo), opponent);
        }
        myturn ^= TRUE;
    }  while (running);
    
    move(0,0);
    draw_board(&gamestate);
    
    gamestate_cleanup(&gamestate);
}

mercurial