Thu, 17 Apr 2014 11:41:02 +0200
surrender is now resign
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 if (net_recieve_code(opponent) == NETCODE_ACCEPT) {
279 printw("\rRemis accepted!");
280 clrtoeol();
281 refresh();
282 return 1;
283 } else {
284 remisrejected = TRUE;
285 }
286 }
287 } else {
288 Move move;
289 int eval_result = eval_move(gamestate, movestr, &move);
290 switch (eval_result) {
291 case VALID_MOVE_SYNTAX:
292 net_send_data(opponent, NETCODE_MOVE, &move, sizeof(Move));
293 code = net_recieve_code(opponent);
294 move.check = code == NETCODE_CHECK;
295 gamestate->checkmate = code == NETCODE_CHECKMATE;
296 gamestate->stalemate = code == NETCODE_STALEMATE;
297 if (code == NETCODE_DECLINE) {
298 printw("Invalid move.");
299 } else if (code == NETCODE_ACCEPT
300 || code == NETCODE_CHECK
301 || code == NETCODE_CHECKMATE
302 || code == NETCODE_STALEMATE) {
303 apply_move(gamestate, &move);
304 if (gamestate->checkmate) {
305 printw("Checkmate!");
306 clrtoeol();
307 return 1;
308 } else if (gamestate->stalemate) {
309 printw("Stalemate!");
310 clrtoeol();
311 return 1;
312 } else {
313 return 0;
314 }
315 } else {
316 printw("Invalid network response.");
317 }
318 break;
319 default:
320 eval_move_failed_msg(eval_result);
321 }
322 clrtoeol();
323 }
324 }
325 }
326 }
328 static int recvmove(GameState *gamestate, GameInfo *gameinfo, int opponent) {
330 if (net_setnonblocking(opponent, 1)) {
331 printw("Cannot setup nonblocking IO on network socket");
332 cbreak(); getch();
333 exit(EXIT_FAILURE);
334 }
336 struct timeval timeout;
337 while (1) {
338 timecontrol(gamestate, gameinfo);
340 move(inputy, 0);
341 printw("Awaiting opponent move...");
342 clrtoeol();
343 refresh();
345 fd_set readfds;
347 FD_ZERO(&readfds);
348 FD_SET(opponent, &readfds);
349 timeout.tv_sec = 0;
350 timeout.tv_usec = 1e5;
352 int result = select(opponent+1, &readfds, NULL, NULL, &timeout);
353 if (result == -1) {
354 printw("\rCannot perform asynchronous network IO");
355 cbreak(); getch();
356 exit(EXIT_FAILURE);
357 }
358 if (result > 0) {
359 uint8_t code = net_recieve_code(opponent);
361 Move move;
362 switch (code) {
363 case NETCODE_TIMEOVER:
364 printw("\rYour opponent's time ran out - you win!");
365 clrtoeol();
366 return 1;
367 case NETCODE_RESIGN:
368 printw("\rYour opponent resigned!");
369 clrtoeol();
370 return 1;
371 case NETCODE_REMIS:
372 if (prompt_yesno(
373 "\rYour opponent offers remis - do you accept")) {
374 printw("\rRemis accepted!");
375 clrtoeol();
376 net_send_code(opponent, NETCODE_ACCEPT);
377 return 1;
378 } else {
379 net_send_code(opponent, NETCODE_DECLINE);
380 }
381 break;
382 case NETCODE_MOVE:
383 net_recieve_data(opponent, &move, sizeof(Move));
384 if (validate_move(gamestate, &move)) {
385 apply_move(gamestate, &move);
386 if (move.check) {
387 net_send_code(opponent, NETCODE_CHECK);
388 } else if (gamestate->checkmate) {
389 net_send_code(opponent, NETCODE_CHECKMATE);
390 printw("\rCheckmate!");
391 clrtoeol();
392 return 1;
393 } else if (gamestate->stalemate) {
394 net_send_code(opponent, NETCODE_STALEMATE);
395 printw("\rStalemate!");
396 clrtoeol();
397 return 1;
398 } else {
399 net_send_code(opponent, NETCODE_ACCEPT);
400 }
401 return 0;
402 } else {
403 net_send_code(opponent, NETCODE_DECLINE);
404 }
405 }
406 }
407 }
408 }
410 static void init_board(GameState *gamestate) {
411 Board initboard = {
412 {WROOK, WKNIGHT, WBISHOP, WQUEEN, WKING, WBISHOP, WKNIGHT, WROOK},
413 {WPAWN, WPAWN, WPAWN, WPAWN, WPAWN, WPAWN, WPAWN, WPAWN},
414 {0, 0, 0, 0, 0, 0, 0, 0},
415 {0, 0, 0, 0, 0, 0, 0, 0},
416 {0, 0, 0, 0, 0, 0, 0, 0},
417 {0, 0, 0, 0, 0, 0, 0, 0},
418 {BPAWN, BPAWN, BPAWN, BPAWN, BPAWN, BPAWN, BPAWN, BPAWN},
419 {BROOK, BKNIGHT, BBISHOP, BQUEEN, BKING, BBISHOP, BKNIGHT, BROOK}
420 };
421 memcpy(gamestate->board, initboard, sizeof(Board));
422 }
424 void game_start_singlemachine(Settings *settings) {
425 inputy = getmaxy(stdscr) - 6;
427 GameState gamestate;
428 memset(&gamestate, 0, sizeof(GameState));
429 init_board(&gamestate);
430 gamestate.mycolor = WHITE;
432 _Bool running;
433 do {
434 clear();
435 draw_board(&gamestate);
436 running = !domove_singlemachine(&gamestate, &(settings->gameinfo));
437 gamestate.mycolor = opponent_color(gamestate.mycolor);
438 } while (running);
439 move(0,0);
440 draw_board(&gamestate);
442 gamestate_cleanup(&gamestate);
444 mvaddstr(getmaxy(stdscr)-1, 0,
445 "Game has ended. Press any key to leave...");
446 refresh();
447 cbreak();
448 flushinp();
449 getch();
450 }
452 void game_start(Settings *settings, int opponent) {
453 inputy = getmaxy(stdscr) - 6;
455 _Bool myturn = is_server(settings) ==
456 (settings->gameinfo.servercolor == WHITE);
458 GameState gamestate;
459 memset(&gamestate, 0, sizeof(GameState));
460 init_board(&gamestate);
461 gamestate.mycolor = myturn ? WHITE:BLACK;
463 _Bool running;
464 do {
465 clear();
466 draw_board(&gamestate);
467 if (myturn) {
468 running = !sendmove(&gamestate, &(settings->gameinfo), opponent);
469 } else {
470 running = !recvmove(&gamestate, &(settings->gameinfo), opponent);
471 }
472 myturn ^= TRUE;
473 } while (running);
475 move(0,0);
476 draw_board(&gamestate);
478 gamestate_cleanup(&gamestate);
480 mvaddstr(getmaxy(stdscr)-1, 0,
481 "Game has ended. Press any key to leave...");
482 refresh();
483 cbreak();
484 flushinp();
485 getch();
486 }