4 * ----------------------------------------------------------------------
6 * Copyright (c) 2012 Free Software Foundation
8 * GNU SHOGI is based on GNU CHESS
10 * This file is part of GNU SHOGI.
12 * GNU Shogi is free software; you can redistribute it and/or modify it
13 * under the terms of the GNU General Public License as published by the
14 * Free Software Foundation; either version 3 of the License,
15 * or (at your option) any later version.
17 * GNU Shogi is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
22 * You should have received a copy of the GNU General Public License along
23 * with GNU Shogi; see the file COPYING. If not, see
24 * <http://www.gnu.org/licenses/>.
25 * ----------------------------------------------------------------------
34 /* Declarations of read(), write(), close(), and lseek(). */
44 unsigned booksize = BOOKSIZE;
45 unsigned short bookmaxply = BOOKMAXPLY;
46 unsigned bookcount = 0;
49 char *bookfile = BOOK;
51 char *bookfile = NULL;
55 char *binbookfile = BINBOOK;
57 char *binbookfile = NULL;
60 static char bmvstr[3][7];
63 static ULONG bhashkey;
69 * Generate move strings in different formats.
73 Balgbr(short f, short t, short flag)
75 short promoted = false;
86 piece = f - NO_SQUARES;
88 if (f > (NO_SQUARES + NO_PIECES))
91 flag = (dropmask | piece);
100 if ((f == t) && ((f != 0) || (t != 0)))
103 * error in algbr: FROM=TO=t
106 bmvstr[0][0] = bmvstr[1][0] = bmvstr[2][0] = '\0';
110 if ((flag & dropmask) != 0)
112 /* bmvstr[0]: P*3c bmvstr[1]: P'3c */
113 short piece = flag & pmask;
114 bmvstr[0][0] = pxx[piece];
116 bmvstr[0][2] = cxx[column(t)];
117 bmvstr[0][3] = rxx[row(t)];
118 bmvstr[0][4] = bmvstr[2][0] = '\0';
119 strcpy(bmvstr[1], bmvstr[0]);
124 if ((f != 0) || (t != 0))
126 /* algebraic notation */
127 /* bmvstr[0]: 7g7f bmvstr[1]:
128 * (+)P7g7f(+) bmvstr[2]: (+)P7f(+) */
129 bmvstr[0][0] = cxx[column(f)];
130 bmvstr[0][1] = rxx[row(f)];
131 bmvstr[0][2] = cxx[column(t)];
132 bmvstr[0][3] = rxx[row(t)];
137 bmvstr[1][0] = bmvstr[2][0] = '+';
138 bmvstr[1][1] = bmvstr[2][1] = pxx[board[f]];
139 strcpy(&bmvstr[1][2], &bmvstr[0][0]);
140 strcpy(&bmvstr[2][2], &bmvstr[0][2]);
144 bmvstr[1][0] = bmvstr[2][0] = pxx[board[f]];
145 strcpy(&bmvstr[1][1], &bmvstr[0][0]);
146 strcpy(&bmvstr[2][1], &bmvstr[0][2]);
151 strcat(bmvstr[0], "+");
152 strcat(bmvstr[1], "+");
153 strcat(bmvstr[2], "+");
158 bmvstr[0][0] = bmvstr[1][0] = bmvstr[2][0] = '\0';
169 bkdisplay(char *s, int cnt, int moveno)
176 printf("matches = %d\n", cnt);
177 printf("inout move is :%s: move number %d side %s\n",
178 s, moveno / 2 + 1, (moveno & 1) ? "white" : "black");
180 #ifndef SEMIQUIETBOOKGEN
181 printf("legal moves are \n");
183 while (pnt < TrPnt[3])
187 if (is_promoted[board[node->f]] )
188 Balgbr(node->f | 0x80, node->t, (short) node->flags);
190 Balgbr(node->f, node->t, (short) node->flags);
193 bmvstr[0], bmvstr[1], bmvstr[2]);
196 printf("\n current board is\n");
198 for (r = (NO_ROWS - 1); r >= 0; r--)
200 for (c = 0; c <= (NO_COLS - 1); c++)
205 pc = (is_promoted[board[l]] ? '+' : ' ');
207 if (color[l] == neutral)
209 else if (color[l] == black)
210 printf("%c%c", pc, qxx[board[l]]);
212 printf("%c%c", pc, pxx[board[l]]);
222 for (color = black; color <= white; color++)
226 printf((color == black) ? "black " : "white ");
228 for (piece = pawn; piece <= king; piece++)
230 if ((c = Captured[color][piece]))
231 printf("%i%c ", c, pxx[piece]);
237 #endif /* SEMIQUIETBOOKGEN */
240 #endif /* QUIETBOOKGEN */
245 * BVerifyMove(s, mv, moveno)
247 * Compare the string 's' to the list of legal moves available for the
248 * opponent. If a match is found, make the move on the board.
252 BVerifyMove(char *s, unsigned short *mv, int moveno)
254 static short pnt, tempb, tempc, tempsf, tempst, cnt;
255 static struct leaf xnode;
260 MoveList(opponent, 2, -2, true);
263 while (pnt < TrPnt[3])
267 if (is_promoted[board[node->f]] )
268 Balgbr(node->f | 0x80, node->t, (short) node->flags);
270 Balgbr(node->f, node->t, (short) node->flags);
272 if (strcmp(s, bmvstr[0]) == 0 || strcmp(s, bmvstr[1]) == 0 ||
273 strcmp(s, bmvstr[2]) == 0)
284 MakeMove(opponent, &xnode, &tempb,
285 &tempc, &tempsf, &tempst, &INCscore);
287 if (SqAttacked(PieceList[opponent][0], computer, &blockable))
289 UnmakeMove(opponent, &xnode, &tempb, &tempc, &tempsf, &tempst);
290 /* Illegal move in check */
291 #if !defined QUIETBOOKGEN
292 /* 077: "Illegal move (in check) %s" */
294 bkdisplay(s, cnt, moveno);
300 *mv = (xnode.f << 8) | xnode.t;
302 if (is_promoted[board[xnode.t]] )
303 Balgbr(xnode.f | 0x80, xnode.t, false);
305 Balgbr(xnode.f, xnode.t, false);
312 #if !defined QUIETBOOKGEN
313 /* 075: "Illegal move (no match)%s\n" */
315 bkdisplay(s, cnt, moveno);
326 * Reset the board and other variables to start a new game.
335 flag.illegal = flag.mate = flag.post = flag.quit
336 = flag.reverse = flag.bothsides = flag.onemove = flag.force
339 flag.material = flag.coords = flag.hash = flag.easy
340 = flag.beep = flag.rcptr
343 flag.stars = flag.shade = flag.back = flag.musttimeout = false;
347 CptrFlag[0] = TesujiFlag[0] = false;
351 for (l = 0; l < NO_SQUARES; l++)
353 board[l] = Stboard[l];
354 color[l] = Stcolor[l];
360 hashbd = hashkey = 0;
367 Vparse (FILE * fd, USHORT *mv, USHORT *flags, USHORT side, int moveno)
376 while (((c = getc(fd)) == ' ')
377 || (c == '!') || (c == '/') || (c == '\n'));
381 /* amount of time spent for the last move */
382 while (((c = getc(fd)) != ')') && (c != EOF));
386 while (((c = getc(fd)) == ' ') || (c == '\n'));
392 /* comment for the actual game */
393 while (((c = getc(fd))) != ']' && (c != EOF));
397 while (((c = getc(fd))) == ' ' || (c == '\n'));
413 /* goes to end of line */
426 while ((c >= '0') && (c <= '9'))
434 while (((c = getc(fd)) == ' ') || (c == '.') || (c == '\n'));
438 while (((c = getc(fd)) != '?') && (c != '!') && (c != ' ')
439 && (c != '(') && (c != '\n') && (c != '\t') && (c != EOF))
444 if ((c != 'x') && (c != '-') && (c != ',')
445 && (c != ';') && (c != '='))
455 while (((c = getc(fd)) != ')') && (c != EOF));
466 while ((c != '\n') && (c != EOF))
475 if (strcmp(s, "draw") == 0)
477 else if (strcmp(s, "1-0") == 0)
479 else if (strcmp(s, "0-1") == 0)
481 else if (strcmp(s, "Resigns") == 0)
483 else if (strcmp(s, "Resigns.") == 0)
485 else if (strcmp(s, "Sennichite") == 0)
487 else if (strcmp(s, "Sennichite.") == 0)
489 else if (strcmp(s, "Jishogi") == 0)
491 else if (strcmp(s, "Jishogi.") == 0)
497 i = BVerifyMove(s, mv, moveno);
501 /* Bad move, not for the program to play */
502 *flags |= BADMOVE; /* Flag it ! */
503 while (((c = getc(fd)) == '?') || (c == '!') || (c == '/'));
508 /* Do not use by computer */
509 *flags |= BADMOVE; /* Flag it ! */
511 while (((c = getc(fd)) == '?') || (c == '!') || (c == '/'));
517 *flags |= GOODMOVE; /* Flag it ! */
519 while (((c = getc(fd)) == '?') || (c == '!') || (c == '/'));
527 while (((c = getc(fd)) != ')') && (c != EOF));
531 /* flush to start of next */
532 while (((c = getc(fd)) != '#') && (c != EOF));
550 static struct gdxadmin ADMIN;
552 static struct gdxdata DATA;
554 /* lts(l) returns most significant 16 bits of l */
556 #if SIZEOF_LONG == 8 /* 64-bit long i.e. 8 bytes */
557 # define lts(x) (USHORT)(((x >> 48) & 0xfffe) | side)
559 # if defined USE_LTSIMP
560 static USHORT ltsimp(long x)
563 n = (((x >> 16) & 0xfffe));
566 # define lts(x) (USHORT)(ltsimp(x) | side)
568 # define lts(x) (USHORT)(((x >> 16)&0xfffe) | side)
573 /* #define HashValue(l) lts(l) */
574 #define HashValue(l) (USHORT)(l & 0xffff)
578 static ULONG currentoffset;
581 #define MAXOFFSET(B) ((B.booksize - 1) * sizeof_gdxdata + sizeof_gdxadmin)
583 #define HashOffset(hashkey, B) \
585 currentoffset = ((ULONG)hashkey % B.booksize) \
586 * sizeof_gdxdata + sizeof_gdxadmin; \
590 #define NextOffset(B) \
592 currentoffset += sizeof_gdxdata; \
593 if (currentoffset > B.maxoffset) \
594 currentoffset = sizeof_gdxadmin; \
598 #define WriteAdmin() \
601 write(gfd, (char *)&ADMIN, sizeof_gdxadmin); \
604 #define WriteData() \
608 lseek(gfd, currentoffset, 0); \
609 write(gfd, (char *)&DATA, sizeof_gdxdata); \
614 static int ReadAdmin(void)
617 return (sizeof_gdxadmin == read(gfd, (char *)&ADMIN, sizeof_gdxadmin));
620 static int ReadData(struct gdxdata *DATA)
622 lseek(gfd, currentoffset, 0);
623 return (sizeof_gdxdata == read(gfd, (char *)DATA, sizeof_gdxdata));
630 * CHECKME: is this still valid esp. wrt gnushogi.book?
632 * Read in the Opening Book file and parse the algebraic notation for a move
633 * into an unsigned integer format indicating the from and to square. Create
634 * a linked list of opening lines of play, with entry->next pointing to the
635 * next line and entry->move pointing to a chunk of memory containing the
636 * moves. More Opening lines of up to 100 half moves may be added to
637 * gnushogi.book. But now it's a hashed table by position which yields a move
638 * or moves for each position. It no longer knows about openings per se only
639 * positions and recommended moves in those positions.
647 int mustwrite = false, first;
648 unsigned short xside, side;
652 unsigned int games = 0;
658 if ((fd = fopen(bookfile, "r")) == NULL)
659 fd = fopen("gnushogi.tbk", "r");
663 /* yes add to book */
664 /* open book as writer */
665 gfd = open(binbookfile, O_RDONLY | O_BINARY);
671 B.bookcount = ADMIN.bookcount;
672 B.booksize = ADMIN.booksize;
673 B.maxoffset = ADMIN.maxoffset;
675 if (B.booksize && !(B.maxoffset == MAXOFFSET(B)))
677 printf("bad format %s\n", binbookfile);
683 printf("bad format %s\n", binbookfile);
687 gfd = open(binbookfile, O_RDWR | O_BINARY);
692 gfd = open(binbookfile, O_RDWR | O_CREAT | O_BINARY, 0644);
694 ADMIN.bookcount = B.bookcount = 0;
695 ADMIN.booksize = B.booksize = booksize;
696 B.maxoffset = ADMIN.maxoffset = MAXOFFSET(B);
703 write(gfd, (char *)&ADMIN, sizeof_gdxadmin);
704 printf("creating bookfile %s %ld %ld\n",
705 binbookfile, B.maxoffset, B.booksize);
707 for (x = 0; x < B.booksize; x++)
709 write(gfd, (char *)&DATA, sizeof_gdxdata);
715 /* setvbuf(fd, buffr, _IOFBF, 2048); */
718 hashbd = hashkey = 0;
721 while ((c = Vparse(fd, &mv, &flags, side, i)) >= 0)
726 * If this is not the first move of an opening and
727 * if it's the first time we have seen it then
728 * save the next move as a hint.
732 if (i < bookmaxply + 2)
734 if (i > 1 && !(flags & BADMOVE))
737 if (i < bookmaxply + 1)
740 * See if this position and move already
741 * exist from some other opening.
745 HashOffset(bhashkey, B);
750 if (!ReadData(&DATA))
751 break; /* corrupted binbook file */
754 break; /* free entry */
756 if (DATA.hashkey == HashValue(bhashkey)
757 && DATA.hashbd == bhashbd)
759 if (DATA.bmove == mv)
762 * Yes, so just bump count - count
763 * is used to choose the opening
764 * move in proportion to its
765 * presence in the book.
778 if (DATA.flags & LASTMOVE)
780 DATA.flags &= (~LASTMOVE);
792 * Doesn't exist so add it to the book.
799 if ((B.bookcount % 1000) == 0)
801 /* CHECKME: may want to get rid of this,
802 * especially for xshogi. */
803 printf("%ld rec %d openings "
808 /* initialize a record */
809 DATA.hashbd = bhashbd;
810 DATA.hashkey = HashValue(bhashkey);
812 DATA.flags = flags | LASTMOVE;
821 opponent = computer ^ 1;
828 /* 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 /* 213: "Book used %d(%d)." */
878 sprintf(msg, CP[213], B.bookcount, B.booksize);
882 /* Set everything back to start the game. */
886 /* Now get ready to play .*/
889 /* 212: "Can't find book." */
890 ShowMessage(CP[212]);
898 * OpeningBook(hint, side)
900 * Go through each of the opening lines of play and check for a match with
901 * the current game listing. If a match occurs, generate a random
902 * number. If this number is the largest generated so far then the next
903 * move in this line becomes the current "candidate". After all lines are
904 * checked, the candidate move is put at the top of the Tree[] array and
905 * will be played by the program. Note that the program does not handle
906 * book transpositions.
910 OpeningBook(unsigned short *hint, short side)
913 int possibles = TrPnt[2] - TrPnt[1];
915 gsrand((unsigned int) time((long *) 0));
919 * Find all the moves for this position - count them and get their
928 struct gdxdata OBB[128];
930 if (B.bookcount == 0)
937 HashOffset(hashkey, B);
939 printf("looking for book move, bhashbd = 0x%lx bhashkey = 0x%x\n",
940 (ULONG)hashbd, HashValue(hashkey));
944 if (!ReadData(&OBB[x]))
947 if (OBB[x].bmove == 0)
951 printf("compare with bhashbd = 0x%lx bhashkey = 0x%x\n",
952 OBB[x].hashbd, OBB[x].hashkey);
954 if ((OBB[x].hashkey == HashValue(hashkey))
955 && (OBB[x].hashbd == (ULONG)hashbd))
959 if (OBB[x-1].flags & LASTMOVE)
967 printf("%d book move(s) found.\n", x);
976 for (i = 0; i < x; i++)
978 if (OBB[i].flags & BADMOVE)
982 /* Is the move in the MoveList? */
983 for (b = TrPnt[1]; b < (unsigned) TrPnt[2]; b++)
985 if (((Tree[b].f << 8) | Tree[b].t) == m)
988 Tree[b].score = DONTUSE;
997 movealgbr(m = OBB[i].bmove, s);
998 printf("finding book move: %s\n", s);
1000 summ += OBB[i].count;
1010 r = (urand() % summ);
1012 for (i = 0; i < x; i++)
1014 if (!(OBB[i].flags & BADMOVE))
1016 if (r < OBB[i].count)
1031 /* Make sure the move is in the MoveList. */
1032 for (b = TrPnt[1]; b < (unsigned) TrPnt[2]; b++)
1034 if (((Tree[b].f << 8) | Tree[b].t) == m)
1036 Tree[b].flags |= book;
1042 /* Make sure it's the best. */
1044 pick(TrPnt[1], TrPnt[2] - 1);
1046 if (Tree[TrPnt[1]].score)
1053 /* Ok, pick up the hint and go. */