4 * ----------------------------------------------------------------------
5 * Copyright (c) 1993, 1994, 1995 Matthias Mutz
6 * Copyright (c) 1999 Michael Vanier and the Free Software Foundation
7 * Copyright (c) 2008, 2013, 2014 Yann Dirson and the Free Software Foundation
9 * GNU SHOGI is based on GNU CHESS
11 * Copyright (c) 1988, 1989, 1990 John Stanback
12 * Copyright (c) 1992 Free Software Foundation
14 * This file is part of GNU SHOGI.
16 * GNU Shogi is free software; you can redistribute it and/or modify it
17 * under the terms of the GNU General Public License as published by the
18 * Free Software Foundation; either version 3 of the License,
19 * or (at your option) any later version.
21 * GNU Shogi is distributed in the hope that it will be useful, but WITHOUT
22 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
23 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
26 * You should have received a copy of the GNU General Public License along
27 * with GNU Shogi; see the file COPYING. If not, see
28 * <http://www.gnu.org/licenses/>.
29 * ----------------------------------------------------------------------
38 /* Declarations of read(), write(), close(), and lseek(). */
48 unsigned booksize = BOOKSIZE;
49 unsigned short bookmaxply = BOOKMAXPLY;
50 unsigned bookcount = 0;
53 char *bookfile = BOOK;
55 char *bookfile = NULL;
59 char *binbookfile = BINBOOK;
61 char *binbookfile = NULL;
64 static char bmvstr[3][7];
67 static ULONG bhashkey;
73 * Generate move strings in different formats.
77 Balgbr(short f, short t, short flag)
79 short promoted = false;
90 piece = f - NO_SQUARES;
92 if (f > (NO_SQUARES + NO_PIECES))
95 flag = (dropmask | piece);
104 if ((f == t) && ((f != 0) || (t != 0)))
107 * error in algbr: FROM=TO=t
110 bmvstr[0][0] = bmvstr[1][0] = bmvstr[2][0] = '\0';
114 if ((flag & dropmask) != 0)
116 /* bmvstr[0]: P*3c bmvstr[1]: P'3c */
117 short piece = flag & pmask;
118 bmvstr[0][0] = pxx[piece];
120 bmvstr[0][2] = COL_NAME(column(t));
121 bmvstr[0][3] = ROW_NAME(row(t));
122 bmvstr[0][4] = bmvstr[2][0] = '\0';
123 strcpy(bmvstr[1], bmvstr[0]);
128 if ((f != 0) || (t != 0))
130 /* algebraic notation */
131 /* bmvstr[0]: 7g7f bmvstr[1]:
132 * (+)P7g7f(+) bmvstr[2]: (+)P7f(+) */
133 bmvstr[0][0] = COL_NAME(column(f));
134 bmvstr[0][1] = ROW_NAME(row(f));
135 bmvstr[0][2] = COL_NAME(column(t));
136 bmvstr[0][3] = ROW_NAME(row(t));
141 bmvstr[1][0] = bmvstr[2][0] = '+';
142 bmvstr[1][1] = bmvstr[2][1] = pxx[board[f]];
143 strcpy(&bmvstr[1][2], &bmvstr[0][0]);
144 strcpy(&bmvstr[2][2], &bmvstr[0][2]);
148 bmvstr[1][0] = bmvstr[2][0] = pxx[board[f]];
149 strcpy(&bmvstr[1][1], &bmvstr[0][0]);
150 strcpy(&bmvstr[2][1], &bmvstr[0][2]);
155 strcat(bmvstr[0], "+");
156 strcat(bmvstr[1], "+");
157 strcat(bmvstr[2], "+");
162 bmvstr[0][0] = bmvstr[1][0] = bmvstr[2][0] = '\0';
173 bkdisplay(char *s, int cnt, int moveno)
180 printf("matches = %d\n", cnt);
181 printf("inout move is :%s: move number %d side %s\n",
182 s, moveno / 2 + 1, (moveno & 1) ? "white" : "black");
184 #ifndef SEMIQUIETBOOKGEN
185 printf("legal moves are \n");
187 while (pnt < TrPnt[3])
191 if (is_promoted[board[node->f]] )
192 Balgbr(node->f | 0x80, node->t, (short) node->flags);
194 Balgbr(node->f, node->t, (short) node->flags);
197 bmvstr[0], bmvstr[1], bmvstr[2]);
200 printf("\n current board is\n");
202 for (r = (NO_ROWS - 1); r >= 0; r--)
204 for (c = 0; c <= (NO_COLS - 1); c++)
209 pc = (is_promoted[board[l]] ? '+' : ' ');
211 if (color[l] == neutral)
213 else if (color[l] == black)
214 printf("%c%c", pc, qxx[board[l]]);
216 printf("%c%c", pc, pxx[board[l]]);
226 for (color = black; color <= white; color++)
230 printf((color == black) ? "black " : "white ");
232 for (piece = pawn; piece <= king; piece++)
234 if ((c = Captured[color][piece]))
235 printf("%i%c ", c, pxx[piece]);
241 #endif /* SEMIQUIETBOOKGEN */
244 #endif /* QUIETBOOKGEN */
249 * BVerifyMove(s, mv, moveno)
251 * Compare the string 's' to the list of legal moves available for the
252 * opponent. If a match is found, make the move on the board.
256 BVerifyMove(char *s, unsigned short *mv, int moveno)
258 static short pnt, tempb, tempc, tempsf, tempst, cnt;
259 static struct leaf xnode;
264 MoveList(opponent, 2, -2, true);
267 while (pnt < TrPnt[3])
271 if (is_promoted[board[node->f]] )
272 Balgbr(node->f | 0x80, node->t, (short) node->flags);
274 Balgbr(node->f, node->t, (short) node->flags);
276 if (strcmp(s, bmvstr[0]) == 0 || strcmp(s, bmvstr[1]) == 0 ||
277 strcmp(s, bmvstr[2]) == 0)
288 MakeMove(opponent, &xnode, &tempb,
289 &tempc, &tempsf, &tempst, &INCscore);
291 if (SqAttacked(PieceList[opponent][0], computer, &blockable))
293 UnmakeMove(opponent, &xnode, &tempb, &tempc, &tempsf, &tempst);
294 /* Illegal move in check */
295 #if !defined QUIETBOOKGEN
296 puts("Illegal move (in check): %s");
297 bkdisplay(s, cnt, moveno);
303 *mv = (xnode.f << 8) | xnode.t;
305 if (is_promoted[board[xnode.t]] )
306 Balgbr(xnode.f | 0x80, xnode.t, false);
308 Balgbr(xnode.f, xnode.t, false);
315 #if !defined QUIETBOOKGEN
316 printf("Illegal move (no match): %s\n", s);
317 bkdisplay(s, cnt, moveno);
328 * Reset the board and other variables to start a new game.
337 flag.illegal = flag.mate = flag.quit
338 = flag.reverse = flag.bothsides = flag.onemove = flag.force
341 flag.post &= xboard; /* [HGM] xboard: do not clear in XBoard mode */
343 flag.material = flag.coords = flag.hash = flag.easy
344 = flag.beep = flag.rcptr
347 flag.stars = flag.shade = flag.back = flag.musttimeout = false;
351 CptrFlag[0] = TesujiFlag[0] = false;
355 for (l = 0; l < NO_SQUARES; l++)
357 board[l] = Stboard[l];
358 color[l] = Stcolor[l];
364 hashbd = hashkey = 0;
371 Vparse (FILE * fd, USHORT *mv, USHORT *flags, int moveno)
380 while (((c = getc(fd)) == ' ')
381 || (c == '!') || (c == '/') || (c == '\n'));
385 /* amount of time spent for the last move */
386 while (((c = getc(fd)) != ')') && (c != EOF));
390 while (((c = getc(fd)) == ' ') || (c == '\n'));
396 /* comment for the actual game */
397 while (((c = getc(fd))) != ']' && (c != EOF));
401 while (((c = getc(fd))) == ' ' || (c == '\n'));
417 /* goes to end of line */
430 while ((c >= '0') && (c <= '9'))
438 while (((c = getc(fd)) == ' ') || (c == '.') || (c == '\n'));
442 while (((c = getc(fd)) != '?') && (c != '!') && (c != ' ')
443 && (c != '(') && (c != '\n') && (c != '\t') && (c != EOF))
448 if ((c != 'x') && (c != '-') && (c != ',')
449 && (c != ';') && (c != '='))
459 while (((c = getc(fd)) != ')') && (c != EOF));
470 while ((c != '\n') && (c != EOF))
479 if (strcmp(s, "draw") == 0)
481 else if (strcmp(s, "1-0") == 0)
483 else if (strcmp(s, "0-1") == 0)
485 else if (strcmp(s, "Resigns") == 0)
487 else if (strcmp(s, "Resigns.") == 0)
489 else if (strcmp(s, "Sennichite") == 0)
491 else if (strcmp(s, "Sennichite.") == 0)
493 else if (strcmp(s, "Jishogi") == 0)
495 else if (strcmp(s, "Jishogi.") == 0)
501 i = BVerifyMove(s, mv, moveno);
505 /* Bad move, not for the program to play */
506 *flags |= BADMOVE; /* Flag it ! */
507 while (((c = getc(fd)) == '?') || (c == '!') || (c == '/'));
512 /* Do not use by computer */
513 *flags |= BADMOVE; /* Flag it ! */
515 while (((c = getc(fd)) == '?') || (c == '!') || (c == '/'));
521 *flags |= GOODMOVE; /* Flag it ! */
523 while (((c = getc(fd)) == '?') || (c == '!') || (c == '/'));
531 while (((c = getc(fd)) != ')') && (c != EOF));
535 /* flush to start of next */
536 while (((c = getc(fd)) != '#') && (c != EOF));
554 static struct gdxadmin ADMIN;
556 static struct gdxdata DATA;
558 /* lts(l) returns most significant 16 bits of l */
560 #if SIZEOF_LONG == 8 /* 64-bit long i.e. 8 bytes */
561 # define lts(x) (USHORT)(((x >> 48) & 0xfffe) | side)
563 # if defined USE_LTSIMP
564 static USHORT ltsimp(long x)
567 n = (((x >> 16) & 0xfffe));
570 # define lts(x) (USHORT)(ltsimp(x) | side)
572 # define lts(x) (USHORT)(((x >> 16)&0xfffe) | side)
577 /* #define HashValue(l) lts(l) */
578 #define HashValue(l) (USHORT)(l & 0xffff)
582 static ULONG currentoffset;
585 #define MAXOFFSET(B) ((B.booksize - 1) * sizeof_gdxdata + sizeof_gdxadmin)
587 #define HashOffset(hashkey, B) \
589 currentoffset = ((ULONG)hashkey % B.booksize) \
590 * sizeof_gdxdata + sizeof_gdxadmin; \
594 #define NextOffset(B) \
596 currentoffset += sizeof_gdxdata; \
597 if (currentoffset > B.maxoffset) \
598 currentoffset = sizeof_gdxadmin; \
602 #define WriteAdmin() \
605 write(gfd, (char *)&ADMIN, sizeof_gdxadmin); \
608 #define WriteData() \
612 lseek(gfd, currentoffset, 0); \
613 write(gfd, (char *)&DATA, sizeof_gdxdata); \
618 static int ReadAdmin(void)
621 return (sizeof_gdxadmin == read(gfd, (char *)&ADMIN, sizeof_gdxadmin));
624 static int ReadData(struct gdxdata *DATA)
626 lseek(gfd, currentoffset, 0);
627 return (sizeof_gdxdata == read(gfd, (char *)DATA, sizeof_gdxdata));
634 * CHECKME: is this still valid esp. wrt gnushogi.book?
636 * Read in the Opening Book file and parse the algebraic notation for a move
637 * into an unsigned integer format indicating the from and to square. Create
638 * a linked list of opening lines of play, with entry->next pointing to the
639 * next line and entry->move pointing to a chunk of memory containing the
640 * moves. More Opening lines of up to 100 half moves may be added to
641 * gnushogi.book. But now it's a hashed table by position which yields a move
642 * or moves for each position. It no longer knows about openings per se only
643 * positions and recommended moves in those positions.
651 int mustwrite = false, first;
656 unsigned int games = 0;
662 if ((fd = fopen(bookfile, "r")) == NULL)
663 fd = fopen("gnushogi.tbk", "r");
667 /* yes add to book */
668 /* open book as writer */
669 gfd = open(binbookfile, O_RDONLY | O_BINARY);
675 B.bookcount = ADMIN.bookcount;
676 B.booksize = ADMIN.booksize;
677 B.maxoffset = ADMIN.maxoffset;
679 if (B.booksize && !(B.maxoffset == MAXOFFSET(B)))
681 printf("bad format %s\n", binbookfile);
687 printf("bad format %s\n", binbookfile);
691 gfd = open(binbookfile, O_RDWR | O_BINARY);
696 gfd = open(binbookfile, O_RDWR | O_CREAT | O_BINARY, 0644);
698 ADMIN.bookcount = B.bookcount = 0;
699 ADMIN.booksize = B.booksize = booksize;
700 B.maxoffset = ADMIN.maxoffset = MAXOFFSET(B);
707 write(gfd, (char *)&ADMIN, sizeof_gdxadmin);
708 printf("creating bookfile %s %ld %ld\n",
709 binbookfile, B.maxoffset, B.booksize);
711 for (x = 0; x < B.booksize; x++)
713 write(gfd, (char *)&DATA, sizeof_gdxdata);
719 /* setvbuf(fd, buffr, _IOFBF, 2048); */
721 hashbd = hashkey = 0;
724 while ((c = Vparse(fd, &mv, &flags, i)) >= 0)
729 * If this is not the first move of an opening and
730 * if it's the first time we have seen it then
731 * save the next move as a hint.
735 if (i < bookmaxply + 2)
737 if (i > 1 && !(flags & BADMOVE))
740 if (i < bookmaxply + 1)
743 * See if this position and move already
744 * exist from some other opening.
748 HashOffset(bhashkey, B);
753 if (!ReadData(&DATA))
754 break; /* corrupted binbook file */
757 break; /* free entry */
759 if (DATA.hashkey == HashValue(bhashkey)
760 && DATA.hashbd == bhashbd)
762 if (DATA.bmove == mv)
765 * Yes, so just bump count - count
766 * is used to choose the opening
767 * move in proportion to its
768 * presence in the book.
781 if (DATA.flags & LASTMOVE)
783 DATA.flags &= (~LASTMOVE);
795 * Doesn't exist so add it to the book.
802 if ((B.bookcount % 1000) == 0)
804 /* CHECKME: may want to get rid of this,
805 * especially for xshogi. */
806 printf("%ld rec %d openings "
811 /* initialize a record */
812 DATA.hashbd = bhashbd;
813 DATA.hashkey = HashValue(bhashkey);
815 DATA.flags = flags | LASTMOVE;
824 opponent = computer ^ 1;
830 /* reset for next opening */
841 /* write admin rec with counts */
842 ADMIN.bookcount = B.bookcount;
849 if (binbookfile != NULL)
851 /* open book as reader */
852 gfd = open(binbookfile, O_RDONLY | O_BINARY);
856 if (ReadAdmin() && (!ADMIN.booksize
857 || (ADMIN.maxoffset == MAXOFFSET(ADMIN))))
859 B.bookcount = ADMIN.bookcount;
860 B.booksize = ADMIN.booksize;
861 B.maxoffset = ADMIN.maxoffset;
865 printf("bad format %s\n", binbookfile);
873 B.booksize = booksize;
877 sprintf(msg, "Book used %lu(%lu).", B.bookcount, B.booksize);
878 dsp->ShowMessage(msg);
881 /* Set everything back to start the game. */
885 /* Now get ready to play .*/
888 dsp->ShowMessage("Can't find book.");
898 * Go through each of the opening lines of play and check for a match with
899 * the current game listing. If a match occurs, generate a random
900 * number. If this number is the largest generated so far then the next
901 * move in this line becomes the current "candidate". After all lines are
902 * checked, the candidate move is put at the top of the Tree[] array and
903 * will be played by the program. Note that the program does not handle
904 * book transpositions.
908 OpeningBook(unsigned short *hint)
911 int possibles = TrPnt[2] - TrPnt[1];
913 gsrand((unsigned int) time((long *) 0));
917 * Find all the moves for this position - count them and get their
926 struct gdxdata OBB[128];
928 if (B.bookcount == 0)
935 HashOffset(hashkey, B);
937 printf("looking for book move, bhashbd = 0x%lx bhashkey = 0x%x\n",
938 (ULONG)hashbd, HashValue(hashkey));
942 if (!ReadData(&OBB[x]))
945 if (OBB[x].bmove == 0)
949 printf("compare with bhashbd = 0x%lx bhashkey = 0x%x\n",
950 OBB[x].hashbd, OBB[x].hashkey);
952 if ((OBB[x].hashkey == HashValue(hashkey))
953 && (OBB[x].hashbd == (ULONG)hashbd))
957 if (OBB[x-1].flags & LASTMOVE)
965 printf("%d book move(s) found.\n", x);
974 for (i = 0; i < x; i++)
976 if (OBB[i].flags & BADMOVE)
980 /* Is the move in the MoveList? */
981 for (b = TrPnt[1]; b < (unsigned) TrPnt[2]; b++)
983 if (((Tree[b].f << 8) | Tree[b].t) == m)
986 Tree[b].score = DONTUSE;
995 movealgbr(m = OBB[i].bmove, s);
996 printf("finding book move: %s\n", s);
998 summ += OBB[i].count;
1008 r = (urand() % summ);
1010 for (i = 0; i < x; i++)
1012 if (!(OBB[i].flags & BADMOVE))
1014 if (r < OBB[i].count)
1029 /* Make sure the move is in the MoveList. */
1030 for (b = TrPnt[1]; b < (unsigned) TrPnt[2]; b++)
1032 if (((Tree[b].f << 8) | Tree[b].t) == m)
1034 Tree[b].flags |= book;
1040 /* Make sure it's the best. */
1042 pick(TrPnt[1], TrPnt[2] - 1);
1044 if (Tree[TrPnt[1]].score)
1051 /* Ok, pick up the hint and go. */