]> ncurses.scripts.mit.edu Git - ncurses.git/blob - test/blue.c
ncurses 6.1 - patch 20190302
[ncurses.git] / test / blue.c
1 /****************************************************************************
2  * Copyright (c) 1998-2016,2017 Free Software Foundation, Inc.              *
3  *                                                                          *
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:                 *
11  *                                                                          *
12  * The above copyright notice and this permission notice shall be included  *
13  * in all copies or substantial portions of the Software.                   *
14  *                                                                          *
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.                               *
22  *                                                                          *
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       *
26  * authorization.                                                           *
27  ****************************************************************************/
28 /*****************************************************************************
29  *                                                                           *
30  *                         B l u e   M o o n                                 *
31  *                         =================                                 *
32  *                               V2.2                                        *
33  *                   A patience game by T.A.Lister                           *
34  *            Integral screen support by Eric S. Raymond                     *
35  *                                                                           *
36  *****************************************************************************/
37
38 /*
39  * $Id: blue.c,v 1.51 2017/09/30 17:43:18 tom Exp $
40  */
41
42 #include <test.priv.h>
43
44 #include <time.h>
45
46 #if HAVE_LANGINFO_CODESET
47 #include <langinfo.h>
48 #endif
49
50 #define NOCARD          (-1)
51
52 #define ACE             0
53 #define KING            12
54 #define SUIT_LENGTH     13
55
56 #define HEARTS          0
57 #define SPADES          1
58 #define DIAMONDS        2
59 #define CLUBS           3
60 #define NSUITS          4
61
62 #define GRID_WIDTH      14      /*    13+1  */
63 #define GRID_LENGTH     56      /* 4*(13+1) */
64 #define PACK_SIZE       52
65
66 #define BASEROW         1
67 #define PROMPTROW       11
68
69 #define RED_ON_WHITE    1
70 #define BLACK_ON_WHITE  2
71 #define BLUE_ON_WHITE   3
72
73 static void die(int onsig) GCC_NORETURN;
74
75 static int deck_size = PACK_SIZE;       /* initial deck */
76 static int deck[PACK_SIZE];
77
78 static int grid[GRID_LENGTH];   /* card layout grid */
79 static int freeptr[4];          /* free card space pointers */
80
81 static int deal_number = 0;
82
83 static chtype ranks[SUIT_LENGTH][2] =
84 {
85     {' ', 'A'},
86     {' ', '2'},
87     {' ', '3'},
88     {' ', '4'},
89     {' ', '5'},
90     {' ', '6'},
91     {' ', '7'},
92     {' ', '8'},
93     {' ', '9'},
94     {'1', '0'},
95     {' ', 'J'},
96     {' ', 'Q'},
97     {' ', 'K'}
98 };
99
100 static int letters[4] =
101 {
102     'h',                        /* hearts */
103     's',                        /* spades */
104     'd',                        /* diamonds */
105     'c',                        /* clubs */
106 };
107
108 #if HAVE_LANGINFO_CODESET
109
110 #if HAVE_TIGETSTR
111 static int glyphs[] =
112 {
113     '\003',                     /* hearts */
114     '\006',                     /* spades */
115     '\004',                     /* diamonds */
116     '\005',                     /* clubs */
117 };
118 #endif
119
120 #if USE_WIDEC_SUPPORT
121 static int uglyphs[] =
122 {
123     0x2665,                     /* hearts */
124     0x2660,                     /* spades */
125     0x2666,                     /* diamonds */
126     0x2663                      /* clubs */
127 };
128 #endif
129 #endif /* HAVE_LANGINFO_CODESET */
130
131 static int *suits = letters;    /* this may change to glyphs below */
132
133 static void
134 die(int onsig)
135 {
136     (void) signal(onsig, SIG_IGN);
137     endwin();
138     ExitProgram(EXIT_SUCCESS);
139 }
140
141 static void
142 init_vars(void)
143 {
144     int i;
145
146     deck_size = PACK_SIZE;
147     for (i = 0; i < PACK_SIZE; i++)
148         deck[i] = i;
149     for (i = 0; i < 4; i++)
150         freeptr[i] = i * GRID_WIDTH;
151 }
152
153 static void
154 shuffle(int size)
155 {
156     int i, j, numswaps, swapnum, temp;
157
158     numswaps = size * 10;       /* an arbitrary figure */
159
160     for (swapnum = 0; swapnum < numswaps; swapnum++) {
161         i = rand() % size;
162         j = rand() % size;
163         temp = deck[i];
164         deck[i] = deck[j];
165         deck[j] = temp;
166     }
167 }
168
169 static void
170 deal_cards(void)
171 {
172     int ptr, card = 0, value, csuit, crank, suit, aces[4];
173
174     memset(aces, 0, sizeof(aces));
175     for (suit = HEARTS; suit <= CLUBS; suit++) {
176         ptr = freeptr[suit];
177         grid[ptr++] = NOCARD;   /* 1st card space is blank */
178         while ((ptr % GRID_WIDTH) != 0) {
179             value = deck[card++];
180             crank = value % SUIT_LENGTH;
181             csuit = value / SUIT_LENGTH;
182             if (crank == ACE)
183                 aces[csuit] = ptr;
184             grid[ptr++] = value;
185         }
186     }
187
188     if (deal_number == 1)       /* shift the aces down to the 1st column */
189         for (suit = HEARTS; suit <= CLUBS; suit++) {
190             grid[suit * GRID_WIDTH] = suit * SUIT_LENGTH;
191             grid[aces[suit]] = NOCARD;
192             freeptr[suit] = aces[suit];
193         }
194 }
195
196 static void
197 printcard(int value)
198 {
199     AddCh(' ');
200     if (value == NOCARD) {
201         (void) addstr("   ");
202     } else {
203         int which = (value / SUIT_LENGTH);
204         int isuit = (value % SUIT_LENGTH);
205         chtype color = (chtype) COLOR_PAIR(((which % 2) == 0)
206                                            ? RED_ON_WHITE
207                                            : BLACK_ON_WHITE);
208
209         AddCh(ranks[isuit][0] | (chtype) COLOR_PAIR(BLUE_ON_WHITE));
210         AddCh(ranks[isuit][1] | (chtype) COLOR_PAIR(BLUE_ON_WHITE));
211
212 #ifdef NCURSES_VERSION
213         (attron) ((int) color); /* quieter compiler warnings */
214 #else
215         attron(color);          /* PDCurses, etc., either no macro or wrong */
216 #endif
217 #if USE_WIDEC_SUPPORT
218         {
219             wchar_t values[2];
220             values[0] = (wchar_t) suits[which];
221             values[1] = 0;
222             addwstr(values);
223         }
224 #else
225         AddCh(suits[which]);
226 #endif
227 #ifdef NCURSES_VERSION
228         (attroff) ((int) color);
229 #else
230         attroff(color);
231 #endif
232     }
233     AddCh(' ');
234 }
235
236 static void
237 display_cards(int deal)
238 {
239     int row, card;
240
241     clear();
242     (void) printw(
243                      "Blue Moon 2.1 - by Tim Lister & Eric Raymond - Deal %d.\n",
244                      deal);
245     for (row = HEARTS; row <= CLUBS; row++) {
246         move(BASEROW + row + row + 2, 1);
247         for (card = 0; card < GRID_WIDTH; card++)
248             printcard(grid[row * GRID_WIDTH + card]);
249     }
250
251     move(PROMPTROW + 2, 0);
252     refresh();
253 #define P(x)    (void)printw("%s\n", x)
254     P("   This 52-card solitaire starts with  the entire deck shuffled and dealt");
255     P("out in four rows.  The aces are then moved to the left end of the layout,");
256     P("making 4 initial free spaces.  You may move to a space only the card that");
257     P("matches the left neighbor in suit, and is one greater in rank.  Kings are");
258     P("high, so no cards may be placed to their right (they create dead spaces).");
259     P("  When no moves can be made,  cards still out of sequence are  reshuffled");
260     P("and dealt face up after the ends of the partial sequences, leaving a card");
261     P("space after each sequence, so that each row looks like a partial sequence");
262     P("followed by a space, followed by enough cards to make a row of 14.       ");
263     P("  A moment's reflection will show that this game cannot take more than 13");
264     P("deals. A good score is 1-3 deals, 4-7 is average, 8 or more is poor.     ");
265 #undef P
266     refresh();
267 }
268
269 static int
270 find(int card)
271 {
272     int i;
273
274     if ((card < 0) || (card >= PACK_SIZE))
275         return (NOCARD);
276     for (i = 0; i < GRID_LENGTH; i++)
277         if (grid[i] == card)
278             return i;
279     return (NOCARD);
280 }
281
282 static void
283 movecard(int src, int dst)
284 {
285     grid[dst] = grid[src];
286     grid[src] = NOCARD;
287
288     move(BASEROW + (dst / GRID_WIDTH) * 2 + 2, (dst % GRID_WIDTH) * 5 + 1);
289     printcard(grid[dst]);
290
291     move(BASEROW + (src / GRID_WIDTH) * 2 + 2, (src % GRID_WIDTH) * 5 + 1);
292     printcard(grid[src]);
293
294     refresh();
295 }
296
297 static void
298 play_game(void)
299 {
300     int dead = 0, i, j;
301     char c;
302     int selection[4], card;
303
304     while (dead < 4) {
305         dead = 0;
306         for (i = 0; i < 4; i++) {
307             card = grid[freeptr[i] - 1];
308
309             if (((card % SUIT_LENGTH) == KING)
310                 ||
311                 (card == NOCARD))
312                 selection[i] = NOCARD;
313             else
314                 selection[i] = find(card + 1);
315
316             if (selection[i] == NOCARD)
317                 dead++;
318         };
319
320         if (dead < 4) {
321             char live[NSUITS + 1], *lp = live;
322
323             for (i = 0; i < 4; i++) {
324                 if (selection[i] != NOCARD) {
325                     move(BASEROW + (selection[i] / GRID_WIDTH) * 2 + 3,
326                          (selection[i] % GRID_WIDTH) * 5);
327                     (void) printw("   %c ", (*lp++ = (char) ('a' + i)));
328                 }
329             };
330             *lp = '\0';
331
332             if (strlen(live) == 1) {
333                 move(PROMPTROW, 0);
334                 (void) printw(
335                                  "Making forced moves...                                 ");
336                 refresh();
337                 (void) sleep(1);
338                 c = live[0];
339             } else {
340                 char buf[BUFSIZ];
341
342                 _nc_SPRINTF(buf, _nc_SLIMIT(sizeof(buf))
343                             "Type [%s] to move, r to redraw, q or INTR to quit: ",
344                             live);
345
346                 do {
347                     move(PROMPTROW, 0);
348                     (void) addstr(buf);
349                     move(PROMPTROW, (int) strlen(buf));
350                     clrtoeol();
351                     AddCh(' ');
352                 } while
353                     (((c = (char) getch()) < 'a' || c > 'd')
354                      && (c != 'r')
355                      && (c != 'q'));
356             }
357
358             for (j = 0; j < 4; j++)
359                 if (selection[j] != NOCARD) {
360                     move(BASEROW + (selection[j] / GRID_WIDTH) * 2 + 3,
361                          (selection[j] % GRID_WIDTH) * 5);
362                     (void) printw("     ");
363                 }
364
365             if (c == 'r')
366                 display_cards(deal_number);
367             else if (c == 'q')
368                 die(SIGINT);
369             else {
370                 i = c - 'a';
371                 if (selection[i] == NOCARD)
372                     beep();
373                 else {
374                     movecard(selection[i], freeptr[i]);
375                     freeptr[i] = selection[i];
376                 }
377             }
378         }
379     }
380
381     move(PROMPTROW, 0);
382     (void) standout();
383     (void) printw("Finished deal %d - type any character to continue...", deal_number);
384     (void) standend();
385     (void) getch();
386 }
387
388 static int
389 collect_discards(void)
390 {
391     int row, col, cardno = 0, finish, gridno;
392
393     for (row = HEARTS; row <= CLUBS; row++) {
394         finish = 0;
395         for (col = 1; col < GRID_WIDTH; col++) {
396             gridno = row * GRID_WIDTH + col;
397
398             if ((grid[gridno] != (grid[gridno - 1] + 1)) && (finish == 0)) {
399                 finish = 1;
400                 freeptr[row] = gridno;
401             };
402
403             if ((finish != 0) && (grid[gridno] != NOCARD))
404                 deck[cardno++] = grid[gridno];
405         }
406     }
407     return cardno;
408 }
409
410 static void
411 game_finished(int deal)
412 {
413     clear();
414     (void) printw("You finished the game in %d deals. This is ", deal);
415     (void) standout();
416     if (deal < 2)
417         (void) addstr("excellent");
418     else if (deal < 4)
419         (void) addstr("good");
420     else if (deal < 8)
421         (void) addstr("average");
422     else
423         (void) addstr("poor");
424     (void) standend();
425     (void) addstr(".         ");
426     refresh();
427 }
428
429 #if HAVE_LANGINFO_CODESET
430 /*
431  * This program first appeared in ncurses in January 1995.  At that point, the
432  * Linux console was able to display CP437 graphic characters, e.g., in the
433  * range 0-31.  As of 2016, most Linux consoles are running with the UTF-8
434  * (partial) support.  Incidentally, that makes all of the cards diamonds.
435  */
436 static void
437 use_pc_display(void)
438 {
439     char *check = nl_langinfo(CODESET);
440     if (!strcmp(check, "UTF-8")) {
441 #if USE_WIDEC_SUPPORT
442         suits = uglyphs;
443 #endif
444     } else {
445 #if HAVE_TIGETSTR
446         if (!strcmp(check, "IBM437") ||
447             !strcmp(check, "CP437") ||
448             !strcmp(check, "IBM850") ||
449             !strcmp(check, "CP850")) {
450             char *smacs = tigetstr("smacs");
451             char *smpch = tigetstr("smpch");
452             /*
453              * The ncurses library makes this check to decide whether to allow
454              * the alternate character set for the (normally) nonprinting codes.
455              */
456             if (smacs != 0 && smpch != 0 && !strcmp(smacs, smpch)) {
457                 suits = glyphs;
458             }
459         }
460 #endif
461     }
462 }
463 #else
464 #define use_pc_display()        /* nothing */
465 #endif /* HAVE_LANGINFO_CODESET */
466
467 int
468 main(int argc, char *argv[])
469 {
470     setlocale(LC_ALL, "");
471
472     use_pc_display();
473
474     InitAndCatch(initscr(), die);
475
476     start_color();
477     init_pair(RED_ON_WHITE, COLOR_RED, COLOR_WHITE);
478     init_pair(BLUE_ON_WHITE, COLOR_BLUE, COLOR_WHITE);
479     init_pair(BLACK_ON_WHITE, COLOR_BLACK, COLOR_WHITE);
480
481     cbreak();
482
483     if (argc == 2)
484         srand((unsigned) atoi(argv[1]));
485     else
486         srand((unsigned) time((time_t *) 0));
487
488     init_vars();
489
490     do {
491         deal_number++;
492         shuffle(deck_size);
493         deal_cards();
494         display_cards(deal_number);
495         play_game();
496     }
497     while
498         ((deck_size = collect_discards()) != 0);
499
500     game_finished(deal_number);
501
502     die(SIGINT);
503     /*NOTREACHED */
504 }
505
506 /* blue.c ends here */