1 /****************************************************************************
2 * Copyright (c) 1998-2018,2019 Free Software Foundation, Inc. *
4 * Permission is hereby granted, free of charge, to any person obtaining a *
5 * copy of this software and associated documentation files (the *
6 * "Software"), to deal in the Software without restriction, including *
7 * without limitation the rights to use, copy, modify, merge, publish, *
8 * distribute, distribute with modifications, sublicense, and/or sell *
9 * copies of the Software, and to permit persons to whom the Software is *
10 * furnished to do so, subject to the following conditions: *
12 * The above copyright notice and this permission notice shall be included *
13 * in all copies or substantial portions of the Software. *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS *
16 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. *
18 * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, *
19 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR *
20 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR *
21 * THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
23 * Except as contained in this notice, the name(s) of the above copyright *
24 * holders shall not be used in advertising or otherwise to promote the *
25 * sale, use or other dealings in this Software without prior written *
27 ****************************************************************************/
29 * Knight's Tour - a brain game
31 * The original of this game was anonymous. It had an unbelievably bogus
32 * interface, you actually had to enter square coordinates! Redesign by
33 * Eric S. Raymond <esr@snark.thyrsus.com> July 22 1995. Mouse support
34 * added September 20th 1995.
36 * $Id: knight.c,v 1.46 2019/08/24 22:40:52 tom Exp $
39 #include <test.priv.h>
44 #define MAXMOVES (ylimit * xlimit)
46 /* where to start the instructions */
54 /* notification line */
57 /* virtual color values */
62 #define CX(x) (2 + 4 * (x))
63 #define CY(y) (1 + 2 * (y))
64 #define cellmove(y, x) wmove(boardwin, CY(y), CX(x))
65 #define CXINV(x) (((x) - 1) / 4)
66 #define CYINV(y) (((y) - 2) / 2)
72 typedef int SQUARES[YLIMIT][XLIMIT];
74 static WINDOW *boardwin; /* the board window */
75 static WINDOW *helpwin; /* the help window */
76 static WINDOW *msgwin; /* the message window */
78 #if HAVE_USE_DEFAULT_COLORS
82 static chtype minus = '-'; /* possible-move character */
84 static chtype plus = '+'; /* cursor hot-spot character */
85 static chtype trail = '#'; /* trail character */
87 static int ylimit = YLIMIT;
88 static int xlimit = XLIMIT;
89 static int maxmoves = (YLIMIT * XLIMIT);
91 static int count_tries; /* count of trials so far */
92 static int test_test; /* FIXME */
107 #define MAX_OFFSET (unsigned)SIZEOF(offsets)
113 setlocale(LC_ALL, "");
115 srand((unsigned) getpid());
117 cbreak(); /* immediate char return */
118 noecho(); /* no immediate echo */
121 boardwin = newwin(ylimit * 2 + 1, xlimit * 4 + 1, BOARDY, BOARDX);
122 helpwin = newwin(0, 0, INSTRY, INSTRX);
123 msgwin = newwin(1, INSTRX - 1, NOTIFYY, 0);
125 scrollok(msgwin, TRUE);
126 keypad(boardwin, TRUE);
129 int bg = COLOR_BLACK;
132 #if HAVE_USE_DEFAULT_COLORS
133 if (d_option && (use_default_colors() == OK))
137 (void) init_pair(TRAIL_COLOR, (short) COLOR_CYAN, (short) bg);
138 (void) init_pair(PLUS_COLOR, (short) COLOR_RED, (short) bg);
139 (void) init_pair(MINUS_COLOR, (short) COLOR_GREEN, (short) bg);
141 trail |= (chtype) COLOR_PAIR(TRAIL_COLOR);
142 plus |= (chtype) COLOR_PAIR(PLUS_COLOR);
143 minus |= (chtype) COLOR_PAIR(MINUS_COLOR);
145 #ifdef NCURSES_MOUSE_VERSION
146 (void) mousemask(BUTTON1_CLICKED, (mmask_t *) NULL);
147 #endif /* NCURSES_MOUSE_VERSION */
148 #if defined(PDCURSES)
149 mouse_set(BUTTON1_RELEASED);
157 /* game explanation -- initial help screen */
159 (void) waddstr(helpwin, "Knight's move is a solitaire puzzle. Your\n");
160 (void) waddstr(helpwin, "objective is to visit each square of the \n");
161 (void) waddstr(helpwin, "chessboard exactly once by making knight's\n");
162 (void) waddstr(helpwin, "moves (one square right or left followed \n");
163 (void) waddstr(helpwin, "by two squares up or down, or two squares \n");
164 (void) waddstr(helpwin, "right or left followed by one square up or\n");
165 (void) waddstr(helpwin, "down). You may start anywhere.\n\n");
167 (void) waddstr(helpwin, "Use arrow keys to move the cursor around.\n");
168 (void) waddstr(helpwin, "When you want to move your knight to the \n");
169 (void) waddstr(helpwin, "cursor location, press <space> or Enter.\n");
170 (void) waddstr(helpwin, "Illegal moves will be rejected with an \n");
171 (void) waddstr(helpwin, "audible beep.\n\n");
172 (void) waddstr(helpwin, "The program will detect if you solve the\n");
173 (void) waddstr(helpwin, "puzzle; also inform you when you run out\n");
174 (void) waddstr(helpwin, "of legal moves.\n\n");
176 MvWAddStr(helpwin, NOTIFYY - INSTRY, 0,
177 "Press `?' to go to keystroke help.");
182 /* keystroke help screen */
184 (void) waddstr(helpwin, "Possible moves are shown with `-'.\n\n");
186 (void) waddstr(helpwin, "You can move around with the arrow keys or\n");
187 (void) waddstr(helpwin, "with the rogue/hack movement keys. Other\n");
188 (void) waddstr(helpwin, "commands allow you to undo moves or redraw.\n");
189 (void) waddstr(helpwin, "Your mouse may work; try left-button to\n");
190 (void) waddstr(helpwin, "move to the square under the pointer.\n\n");
192 (void) waddstr(helpwin, "x,q -- exit y k u 7 8 9\n");
193 (void) waddstr(helpwin, "r -- redraw screen \\|/ \\|/ \n");
194 (void) waddstr(helpwin, "bksp -- undo move h-+-l 4-+-6\n");
195 (void) waddstr(helpwin, "a -- autojump /|\\ /|\\ \n");
197 (void) waddstr(helpwin, "R -- solve (slow) b j n 1 2 3\n");
199 (void) waddstr(helpwin, " b j n 1 2 3\n");
202 (void) waddstr(helpwin, "\nYou can place your knight on the selected\n");
203 (void) waddstr(helpwin, "square with spacebar, Enter, or the keypad\n");
204 (void) waddstr(helpwin, "center key. Use F/B to review the path.\n");
206 MvWAddStr(helpwin, NOTIFYY - INSTRY, 0,
207 "Press `?' to go to game explanation");
211 show_help(bool * keyhelp)
225 isValidYX(int y, int x)
227 return (y >= 0 && y < ylimit && x >= 0 && x < xlimit) ? TRUE : FALSE;
231 isUnusedYX(SQUARES squares, int y, int x)
233 return (isValidYX(y, x) && (!squares[y][x]) ? TRUE : FALSE);
237 boardIsFilled(SQUARES squares, int y, int x)
241 for (n = 0; n < MAX_OFFSET; n++) {
242 if (isUnusedYX(squares, y + offsets[n].y, x + offsets[n].x)) {
254 MvAddStr(0, 20, "KNIGHT'S MOVE -- a logical solitaire");
256 move(BOARDY, BOARDX);
257 waddch(boardwin, ACS_ULCORNER);
258 for (j = 0; j < (ylimit - 1); j++) {
259 waddch(boardwin, ACS_HLINE);
260 waddch(boardwin, ACS_HLINE);
261 waddch(boardwin, ACS_HLINE);
262 waddch(boardwin, ACS_TTEE);
264 waddch(boardwin, ACS_HLINE);
265 waddch(boardwin, ACS_HLINE);
266 waddch(boardwin, ACS_HLINE);
267 waddch(boardwin, ACS_URCORNER);
269 for (i = 1; i < ylimit; i++) {
270 move(BOARDY + i * 2 - 1, BOARDX);
271 waddch(boardwin, ACS_VLINE);
272 for (j = 0; j < xlimit; j++) {
273 waddch(boardwin, ' ');
274 waddch(boardwin, ' ');
275 waddch(boardwin, ' ');
276 waddch(boardwin, ACS_VLINE);
278 move(BOARDY + i * 2, BOARDX);
279 waddch(boardwin, ACS_LTEE);
280 for (j = 0; j < xlimit - 1; j++) {
281 waddch(boardwin, ACS_HLINE);
282 waddch(boardwin, ACS_HLINE);
283 waddch(boardwin, ACS_HLINE);
284 waddch(boardwin, ACS_PLUS);
286 waddch(boardwin, ACS_HLINE);
287 waddch(boardwin, ACS_HLINE);
288 waddch(boardwin, ACS_HLINE);
289 waddch(boardwin, ACS_RTEE);
292 move(BOARDY + i * 2 - 1, BOARDX);
293 waddch(boardwin, ACS_VLINE);
294 for (j = 0; j < xlimit; j++) {
295 waddch(boardwin, ' ');
296 waddch(boardwin, ' ');
297 waddch(boardwin, ' ');
298 waddch(boardwin, ACS_VLINE);
301 move(BOARDY + i * 2, BOARDX);
302 waddch(boardwin, ACS_LLCORNER);
303 for (j = 0; j < xlimit - 1; j++) {
304 waddch(boardwin, ACS_HLINE);
305 waddch(boardwin, ACS_HLINE);
306 waddch(boardwin, ACS_HLINE);
307 waddch(boardwin, ACS_BTEE);
309 waddch(boardwin, ACS_HLINE);
310 waddch(boardwin, ACS_HLINE);
311 waddch(boardwin, ACS_HLINE);
312 waddch(boardwin, ACS_LRCORNER);
316 mark_possibles(SQUARES squares, int y, int x, chtype mark)
320 for (n = 0; n < MAX_OFFSET; n++) {
321 if (isUnusedYX(squares, y + offsets[n].y, x + offsets[n].x)) {
322 cellmove(y + offsets[n].y, x + offsets[n].x);
323 waddch(boardwin, mark);
329 find_next_move(SQUARES squares, HISTORY * doneData, int doneSize, int *y, int *x)
335 int oldy = doneData[doneSize - 1].y;
336 int oldx = doneData[doneSize - 1].x;
341 for (j = 0; j < MAX_OFFSET * 2; j++) {
342 unsigned k = j % MAX_OFFSET;
343 int newy = oldy + offsets[k].y;
344 int newx = oldx + offsets[k].x;
345 if (isUnusedYX(squares, newy, newx)) {
351 } else if (found >= 0) {
360 *y = oldy + offsets[next].y;
361 *x = oldx + offsets[next].x;
369 count_next_moves(SQUARES squares, int count_moves, int y, int x)
374 wprintw(msgwin, "\nMove %d", count_moves);
375 for (j = 0; j < MAX_OFFSET; j++) {
376 int newy = y + offsets[j].y;
377 int newx = x + offsets[j].x;
378 if (isUnusedYX(squares, newy, newx)) {
382 wprintw(msgwin, ", gives %d choices", count);
387 unmarkcell(int row, int column)
389 cellmove(row, column);
390 waddch(boardwin, '\b');
391 waddch(boardwin, ' ');
392 waddch(boardwin, minus);
393 waddch(boardwin, ' ');
397 markcell(chtype tchar, int row, int column)
399 cellmove(row, column);
400 waddch(boardwin, '\b');
401 waddch(boardwin, tchar);
402 waddch(boardwin, tchar);
403 waddch(boardwin, tchar);
407 drawMove(SQUARES squares, int count_moves, chtype tchar, int oldy, int oldx, int
409 /* place the stars, update board & currents */
411 if (count_moves <= 1) {
414 for (i = 0; i < ylimit; i++) {
415 for (j = 0; j < xlimit; j++) {
416 if (count_moves == 0) {
420 if (winch(boardwin) == minus)
421 waddch(boardwin, ' ');
426 markcell(tchar, oldy, oldx);
427 mark_possibles(squares, oldy, oldx, ' ');
430 if (row >= 0 && column >= 0) {
431 markcell(trail, row, column);
432 mark_possibles(squares, row, column, minus);
433 squares[row][column] = TRUE;
436 wprintw(msgwin, "\nMove %d", count_moves);
437 if (count_tries != count_moves)
438 wprintw(msgwin, " (%d tries)", count_tries);
452 evaluate_move(SQUARES squares, HISTORY * doneData, int doneSize, int row, int column)
456 else if (squares[row][column] == TRUE) {
457 waddstr(msgwin, "\nYou've already been there.");
460 int rdif = iabs(row - doneData[doneSize - 1].y);
461 int cdif = iabs(column - doneData[doneSize - 1].x);
463 if (!((rdif == 1) && (cdif == 2)) && !((rdif == 2) && (cdif == 1))) {
464 waddstr(msgwin, "\nThat's not a legal knight's move.");
473 completed(SQUARES squares)
477 for (i = 0; i < ylimit; i++) {
478 for (j = 0; j < xlimit; j++) {
479 if (squares[i][j] != 0) {
484 return ((count == maxmoves) ? -1 : count);
488 no_previous_move(void)
490 waddstr(msgwin, "\nNo previous move.");
494 /* Recursively try all possible moves, starting from (y,x) */
496 recurBack(SQUARES squares, int y, int x, int total)
503 if (total < maxmoves) {
506 for (k = 0; k < MAX_OFFSET; k++) {
507 int try_x = x + offsets[k].x;
508 int try_y = y + offsets[k].y;
509 if (isUnusedYX(squares, try_y, try_x)) {
511 squares[try_y][try_x] = total + 1;
512 result = recurBack(squares, try_y, try_x, total + 1);
513 if (result > longest) {
518 if (result >= maxmoves)
520 squares[try_y][try_x] = 0; /* allow retry... */
526 if (longest > total) {
528 squares[best_y][best_x] = total + 1;
529 (void) recurBack(squares, best_y, best_x, total + 1);
530 if (result < maxmoves)
531 squares[best_y][best_x] = 0;
538 * Solve the Knight Tour problem using backtracking, returning the length of
539 * the resulting solution. If this is invoked from a point where the remaining
540 * choices cannot complete the tour, the result will fall short.
543 useBacktracking(SQUARES result, HISTORY * doneData, int doneSize)
548 int actual = doneSize - 1;
550 memset(squares, 0, sizeof(squares));
551 for (n = 1; n <= actual; ++n) {
557 total = recurBack(squares, y, x, actual);
558 if (total > actual) {
559 for (y = 0; y < ylimit; ++y) {
560 for (x = 0; x < xlimit; ++x) {
561 result[y][x] = squares[y][x];
562 if ((n = squares[y][x]) != 0) {
573 reviewHistory(HISTORY * history, int count_moves, int review, int *ny, int *nx)
578 } else if (review > count_moves - 2) {
580 review = count_moves - 2;
582 *ny = history[count_moves - review - 1].y;
583 *nx = history[count_moves - review - 1].x;
584 wprintw(msgwin, "\nReview %d:%d.", count_moves - review - 1,
595 bool keyhelp; /* TRUE if keystroke help is up */
597 int lastcol = 0; /* last location visited */
600 int review = 0; /* review history */
602 int rw = 0, col = 0; /* current row and column */
606 HISTORY history[(YLIMIT * XLIMIT) + 1];
607 int count_moves = 0; /* count of moves so far */
609 /* clear screen and draw board */
615 wnoutrefresh(stdscr);
616 wnoutrefresh(helpwin);
617 wnoutrefresh(msgwin);
618 wnoutrefresh(boardwin);
621 for (i = 0; i < ylimit; i++) {
622 for (j = 0; j < xlimit; j++) {
623 squares[i][j] = FALSE;
627 memset(history, 0, sizeof(history));
628 history[0].y = history[0].x = -1;
629 history[1].y = history[1].x = -1;
630 lastrow = lastcol = -2;
637 if (rw != lastrow || col != lastcol) {
638 if (lastrow >= 0 && lastcol >= 0) {
639 cellmove(lastrow, lastcol);
640 if (squares[lastrow][lastcol])
641 waddch(boardwin, trail);
643 waddch(boardwin, oldch);
647 oldch = winch(boardwin);
653 waddch(boardwin, plus);
658 switch (wgetch(boardwin)) {
662 ny = rw + ylimit - 1;
675 nx = col + xlimit - 1;
686 ny = rw + ylimit - 1;
687 nx = col + xlimit - 1;
693 nx = col + xlimit - 1;
698 ny = rw + ylimit - 1;
710 #ifdef NCURSES_MOUSE_VERSION
715 if (myevent.y >= CY(0) && myevent.y <= CY(ylimit)
716 && myevent.x >= CX(0) && myevent.x <= CX(xlimit)) {
717 nx = CXINV(myevent.x);
718 ny = CYINV(myevent.y);
726 #endif /* NCURSES_MOUSE_VERSION */
731 test_y = MOUSE_Y_POS + 0;
732 test_x = MOUSE_X_POS + 1;
733 if (test_y >= CY(0) && test_y <= CY(ylimit)
734 && test_x >= CX(0) && test_x <= CX(xlimit)) {
737 wmove(helpwin, 0, 0);
743 #endif /* PDCURSES */
744 #endif /* KEY_MOUSE */
750 if (evaluate_move(squares, history, count_moves, rw, col)) {
754 history[count_moves - 1].y,
755 history[count_moves - 1].x,
757 history[count_moves].y = (short) rw;
758 history[count_moves].x = (short) col;
762 if (boardIsFilled(squares, rw, col)) {
763 if (completed(squares) < 0) {
764 waddstr(msgwin, "\nYou won.");
767 "\nNo further moves are possible.");
779 if (count_moves <= 0) {
781 } else if (count_moves <= 1) {
782 ny = history[count_moves].y;
783 nx = history[count_moves].x;
784 if (nx < 0 || ny < 0) {
785 ny = (lastrow >= 0) ? lastrow : 0;
786 nx = (lastcol >= 0) ? lastcol : 0;
789 squares[ny][nx] = FALSE;
791 drawMove(squares, count_moves, ' ', ny, nx, -1, -1);
796 int oldy = history[count_moves - 1].y;
797 int oldx = history[count_moves - 1].x;
799 if (!squares[rw][col]) {
801 waddch(boardwin, ' ');
804 squares[oldy][oldx] = FALSE;
806 ny = history[count_moves - 1].y;
807 nx = history[count_moves - 1].x;
808 if (nx < 0 || ny < 0) {
812 drawMove(squares, count_moves, ' ', oldy, oldx, ny, nx);
814 /* avoid problems if we just changed the current cell */
815 cellmove(lastrow, lastcol);
816 oldch = winch(boardwin);
823 if (find_next_move(squares, history, count_moves, &ny, &nx))
824 count_next_moves(squares, count_moves, ny, nx);
830 review = reviewHistory(history, count_moves, review - 1,
835 review = reviewHistory(history, count_moves, review + 1,
841 wprintw(msgwin, "\nworking...");
844 test_size = useBacktracking(squares, history, count_moves);
845 wprintw(msgwin, "\nOk %d:%d (%d tests)",
846 test_size, maxmoves, test_test);
848 while (count_moves <= test_size) {
850 ny = history[count_moves].y,
851 nx = history[count_moves].x);
855 wprintw(msgwin, "\nBoard is too large.");
864 clearok(curscr, TRUE);
865 wnoutrefresh(stdscr);
866 wnoutrefresh(boardwin);
867 wnoutrefresh(msgwin);
868 wnoutrefresh(helpwin);
891 if ((count = completed(squares)) < 0)
892 wprintw(msgwin, "\nYou won. Care to try again? ");
894 wprintw(msgwin, "\n%d squares filled. Try again? ", count);
897 (tolower(wgetch(msgwin)) == 'y');
903 static const char *msg[] =
905 "Usage: knight [options]"
908 #if HAVE_USE_DEFAULT_COLORS
909 ," -d invoke use_default_colors"
911 ," -n NUM set board-size to NUM*NUM (default 8x8)"
915 for (n = 0; n < SIZEOF(msg); n++)
916 fprintf(stderr, "%s\n", msg[n]);
918 ExitProgram(EXIT_FAILURE);
922 main(int argc, char *argv[])
926 while ((ch = getopt(argc, argv, "dn:")) != -1) {
928 #if HAVE_USE_DEFAULT_COLORS
935 if (ch < 3 || ch > 8) {
936 fprintf(stderr, "board size %d is outside [3..8]\n", ch);
939 xlimit = ylimit = ch;
954 ExitProgram(EXIT_SUCCESS);