]> git.gir.st - solVItaire.git/blob - sol.c
automagic conserve space
[solVItaire.git] / sol.c
1 #define _DEFAULT_SOURCE
2 #define _POSIX_C_SOURCE /* for sigaction */
3 #include <poll.h>
4 #include <signal.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <sys/ioctl.h>
8 #include <time.h>
9 #include <termios.h>
10 #include <unistd.h>
11
12 #include "sol.h"
13 #include "schemes.h"
14
15 struct playfield f;
16 struct opts op;
17
18 // action table {{{
19 /* stores a function pointer for every takeable action; called by game loop */
20 int (*action[NUM_PLACES][10])(int,int,int) = {
21 #ifdef KLONDIKE
22 /* 1 2 3 4 5 6 7 stk wst fnd*/
23 /* 1 */ { t2f, t2t, t2t, t2t, t2t, t2t, t2t, nop, nop, t2f },
24 /* 2 */ { t2t, t2f, t2t, t2t, t2t, t2t, t2t, nop, nop, t2f },
25 /* 3 */ { t2t, t2t, t2f, t2t, t2t, t2t, t2t, nop, nop, t2f },
26 /* 4 */ { t2t, t2t, t2t, t2f, t2t, t2t, t2t, nop, nop, t2f },
27 /* 5 */ { t2t, t2t, t2t, t2t, t2f, t2t, t2t, nop, nop, t2f },
28 /* 6 */ { t2t, t2t, t2t, t2t, t2t, t2f, t2t, nop, nop, t2f },
29 /* 7 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2f, nop, nop, t2f },
30 /*stk*/ { nop, nop, nop, nop, nop, nop, nop, nop, s2w, nop },
31 /*wst*/ { w2t, w2t, w2t, w2t, w2t, w2t, w2t, w2s, w2f, w2f },
32 /*fnd*/ { f2t, f2t, f2t, f2t, f2t, f2t, f2t, nop, nop, nop },
33 #elif defined SPIDER
34 /* 1 2 3 4 5 6 7 8 9 10*/
35 /* 1 */ { t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t },
36 /* 2 */ { t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t },
37 /* 3 */ { t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2t },
38 /* 4 */ { t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2t },
39 /* 5 */ { t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2t },
40 /* 6 */ { t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2t },
41 /* 7 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2t },
42 /* 8 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2t },
43 /* 9 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2t },
44 /*10 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2f },
45 /*stk*/ { s2t, s2t, s2t, s2t, s2t, s2t, s2t, s2t, s2t, s2t },
46 #endif
47 };
48 // }}}
49
50 // argv parsing, game loops, cleanup {{{
51 int main(int argc, char** argv) {
52 /* opinionated defaults: */
53 op.s = &unicode_large_color;
54 #ifdef SPIDER
55 op.m = MEDIUM;
56 #endif
57
58 int optget;
59 opterr = 0; /* don't print message on unrecognized option */
60 while ((optget = getopt (argc, argv, "+:hs:vbcm")) != -1) {
61 switch (optget) {
62 #ifdef SPIDER
63 case 's': /* number of suits */
64 switch (optarg[0]) {
65 case '1': op.m = EASY; break;
66 case '2': op.m = MEDIUM; break;
67 case '4': op.m = NORMAL; break;
68 default: goto error;
69 } break;
70 #endif
71 case 'b': op.s = &unicode_large_mono; break;
72 case 'c': op.s = &unicode_large_color; break;
73 case 'm': op.s = &unicode_small_mono; break; /* "mini" */
74 case 'h': default: goto error;
75 error:
76 fprintf (stderr, SHORTHELP LONGHELP KEYHELP, argv[0]);
77 return optget != 'h';
78 }
79 }
80
81 signal_setup();
82 atexit (*quit);
83
84 signal_handler(SIGWINCH); /* initialize window size */
85
86 newgame:
87 screen_setup(1);
88
89 switch(sol()) {
90 case GAME_NEW: goto newgame;
91 case GAME_WON:
92 print_table(NO_HI, NO_HI);
93 win_anim();
94 if (getchar()=='q') return 0;
95 goto newgame;
96 case GAME_QUIT: return 0;
97 }
98 }
99
100 int sol(void) {
101 /* clean undo (from previous game): */
102 free_undo(f.u);
103
104 deal();
105
106 int from, to, opt;
107 for(;;) {
108 switch (get_cmd(&from, &to, &opt)) {
109 case CMD_MOVE:
110 switch (action[from][to](from,to,opt)) {
111 case OK: break;
112 case ERR: visbell(); break;
113 case WON: return GAME_WON;
114 }
115 break;
116 case CMD_HINT: break;//TODO: show a possible (and sensible) move
117 case CMD_JOIN: break;//TODO: join any pile to here (longest if possible)
118 case CMD_UNDO: undo_pop(f.u); break;
119 case CMD_INVAL: visbell(); break;
120 case CMD_NEW: return GAME_NEW;
121 case CMD_AGAIN: //TODO: restart with same seed
122 case CMD_QUIT: return GAME_QUIT;
123 }
124 }
125 }
126
127 void quit(void) {
128 screen_setup(0);
129 /* free undo data structures: */
130 free_undo(f.u);
131 }
132 //}}}
133
134 // card games helper functions {{{
135 #define get_suit(card) \
136 ((card-1) % NUM_SUITS)
137 #define get_rank(card) \
138 ((card-1) / NUM_SUITS)
139 #define get_color(card) \
140 ((get_suit(card) ^ get_suit(card)>>1) & 1)
141
142 #define is_tableu(where) (where <= TAB_MAX)
143
144 int find_top(card_t* pile) {
145 int i;
146 for(i=PILE_SIZE-1; i>=0 && !pile[i]; i--);
147 return i;
148 }
149 int first_movable(card_t* pile) {
150 int i = 0;
151 for (;pile[i] && !is_movable(pile, i); i++);
152 return i;
153 }
154 int turn_over(card_t* pile) {
155 int top = find_top(pile);
156 if (pile[top] < 0) {
157 pile[top] *= -1;
158 return 1;
159 } else return 0;
160 }
161 int check_won(void) {
162 for (int pile = 0; pile < NUM_DECKS*NUM_SUITS; pile++)
163 if (f.f[pile][NUM_RANKS-1] == NO_CARD) return 0;
164
165 return 1;
166 }
167 int rank_next (card_t a, card_t b) {
168 return get_rank(a) == get_rank(b)-1;
169 }
170 int is_consecutive (card_t* pile, int pos) {
171 if (pos+1 >= PILE_SIZE) return 1; /* card is last */
172 if (pile[pos+1] == NO_CARD) return 1; /* card is first */
173
174 #ifdef KLONDIKE
175 /* ranks consecutive? */
176 if (!rank_next(pile[pos+1], pile[pos])) return 0;
177 /* color opposite? */
178 if (get_color(pile[pos+1]) == get_color(pile[pos])) return 0;
179 #elif defined SPIDER
180 /* ranks consecutive? */
181 if (!rank_next(pile[pos+1], pile[pos])) return 0;
182 /* same suit? */
183 if (get_suit(pile[pos+1]) != get_suit(pile[pos])) return 0;
184 #endif
185
186 return 1;
187 }
188
189 int is_movable(card_t* pile, int n) {
190 #ifdef KLONDIKE
191 return(pile[n] > NO_CARD); /*non-movable cards don't exist in klondike*/
192 #elif defined SPIDER
193 int top = find_top(pile);
194 for (int i = top; i >= 0; i--) {
195 if (pile[i] <= NO_CARD) return 0; /*no card or card face down?*/
196 if (!is_consecutive(pile, i)) return 0;
197 if (i == n) return 1; /* card reached, must be movable */
198 }
199 return 0;
200 #endif
201 }
202 //}}}
203
204 // takeable actions {{{
205 #ifdef KLONDIKE
206 card_t stack_take(void) { /*NOTE: assert(f.w >= 0) */
207 card_t card = f.s[f.w];
208 /* move stack one over, so there are no gaps in it: */
209 for (int i = f.w; i < f.z-1; i++)
210 f.s[i] = f.s[i+1];
211 f.z--;
212 f.w--; /* make previous card visible again */
213 return card;
214 }
215 int t2f(int from, int to, int opt) { /* tableu to foundation */
216 (void) to; (void) opt; /* don't need */
217 int top_from = find_top(f.t[from]);
218 to = get_suit(f.t[from][top_from]);
219 int top_to = find_top(f.f[to]);
220 if ((top_to < 0 && get_rank(f.t[from][top_from]) == RANK_A)
221 || (top_to >= 0 && rank_next(f.f[to][top_to],f.t[from][top_from]))) {
222 f.f[to][top_to+1] = f.t[from][top_from];
223 f.t[from][top_from] = NO_CARD;
224 undo_push(from, FOUNDATION, to,
225 turn_over(f.t[from]));
226 if (check_won()) return WON;
227 return OK;
228 } else return ERR;
229 }
230 int w2f(int from, int to, int opt) { /* waste to foundation */
231 (void) from; (void) to; (void) opt; /* don't need */
232 if (f.w < 0) return ERR;
233 to = get_suit(f.s[f.w]);
234 int top_to = find_top(f.f[to]);
235 if ((top_to < 0 && get_rank(f.s[f.w]) == RANK_A)
236 || (top_to >= 0 && rank_next(f.f[to][top_to], f.s[f.w]))) {
237 undo_push(WASTE, FOUNDATION, f.w | to<<16, 0);//ugly encoding :|
238 f.f[to][top_to+1] = stack_take();
239 if (check_won()) return WON;
240 return OK;
241 } else return ERR;
242
243 }
244 int s2w(int from, int to, int opt) { /* stock to waste */
245 (void) from; (void) to; (void) opt; /* don't need */
246 if (f.z == 0) return ERR;
247 f.w++;
248 if (f.w == f.z) f.w = -1;
249 return OK;
250 }
251 int w2s(int from, int to, int opt) { /* waste to stock (undo stock to waste) */
252 (void) from; (void) to; (void) opt; /* don't need */
253 if (f.z == 0) return ERR;
254 f.w--;
255 if (f.w < -1) f.w = f.z-1;
256 return OK;
257 }
258 int f2t(int from, int to, int opt) { /* foundation to tableu */
259 (void) from; /* don't need */
260 int top_to = find_top(f.t[to]);
261 from = opt;
262 int top_from = find_top(f.f[from]);
263
264 if ((get_color(f.t[to][top_to]) != get_color(f.f[from][top_from]))
265 && (rank_next(f.f[from][top_from], f.t[to][top_to]))) {
266 f.t[to][top_to+1] = f.f[from][top_from];
267 f.f[from][top_from] = NO_CARD;
268 undo_push(FOUNDATION, to, from, 0);
269 return OK;
270 } else return ERR;
271 }
272 int w2t(int from, int to, int opt) { /* waste to tableu */
273 (void) from; (void) opt; /* don't need */
274 int top_to = find_top(f.t[to]);
275 if (((get_color(f.t[to][top_to]) != get_color(f.s[f.w]))
276 && (rank_next(f.s[f.w], f.t[to][top_to])))
277 || (top_to < 0 && get_rank(f.s[f.w]) == RANK_K)) {
278 undo_push(WASTE, to, f.w, 0);
279 f.t[to][top_to+1] = stack_take();
280 return OK;
281 } else return ERR;
282 }
283 int t2t(int from, int to, int opt) { /* tableu to tableu */
284 (void) opt; /* don't need */
285 int top_to = find_top(f.t[to]);
286 int top_from = find_top(f.t[from]);
287 int count = 0; //NOTE: could probably be factored out
288 for (int i = top_from; i >=0; i--) {
289 if (((get_color(f.t[to][top_to]) != get_color(f.t[from][i]))
290 && (rank_next(f.t[from][i], f.t[to][top_to]))
291 && f.t[from][i] > NO_CARD) /* card face up? */
292 || (top_to < 0 && get_rank(f.t[from][i]) == RANK_K)) {
293 /* move cards [i..top_from] to their destination */
294 for (;i <= top_from; i++) {
295 top_to++;
296 f.t[to][top_to] = f.t[from][i];
297 f.t[from][i] = NO_CARD;
298 count++;
299 }
300 undo_push(from, to, count,
301 turn_over(f.t[from]));
302 return OK;
303 }
304 }
305 return ERR; /* no such move possible */
306 }
307 #elif defined SPIDER
308 int remove_if_complete (int pileno) { //cleanup!
309 card_t* pile = f.t[pileno];
310 /* test if K...A complete; move to foundation if so */
311 int top_from = find_top(pile);
312 if (get_rank(pile[top_from]) != RANK_A) return 0;
313 for (int i = top_from; i>=0; i--) {
314 if (!is_consecutive (pile, i)) return 0;
315 if (i+RANK_K == top_from /* if ace to king: remove it */
316 && get_rank(pile[top_from-RANK_K]) == RANK_K) {
317 for(int i=top_from, j=0; i>top_from-NUM_RANKS; i--,j++){
318 f.f[f.w][j] = pile[i];
319 pile[i] = NO_CARD;
320 }
321 undo_push(pileno, FOUNDATION, f.w,
322 turn_over(pile));
323 f.w++;
324 return 1;
325 }
326 }
327
328 return 0;
329 }
330 int t2t(int from, int to, int opt) { //in dire need of cleanup
331 int top_from = find_top(f.t[from]);
332 int top_to = find_top(f.t[to]);
333 int empty_to = (top_to < 0)? opt: -1; /* empty pile? */
334 int count = 0; //NOTE: could probably be factored out
335
336 for (int i = top_from; i >= 0; i--) {
337 if (!is_consecutive(f.t[from], i)) break;
338
339 /* is consecutive OR to empty pile and rank ok? */
340 if (rank_next(f.t[from][i], f.t[to][top_to])
341 || (empty_to >= RANK_A && get_rank(f.t[from][i]) == empty_to)) {
342 for (;i <= top_from; i++) {
343 top_to++;
344 f.t[to][top_to] = f.t[from][i];
345 f.t[from][i] = NO_CARD;
346 count++;
347 }
348 undo_push(from, to, count,
349 turn_over(f.t[from]));
350 remove_if_complete(to);
351 if (check_won()) return WON;
352 return OK;
353 }
354 }
355
356 return ERR; /* no such move possible */
357 }
358 int s2t(int from, int to, int opt) {
359 (void) from; (void) to; (void) opt; /* don't need */
360 if (f.z <= 0) return ERR; /* stack out of cards */
361 for (int pile = 0; pile < NUM_PILES; pile++)
362 if (f.t[pile][0]==NO_CARD) return ERR; /*no piles may be empty*/
363 for (int pile = 0; pile < NUM_PILES; pile++) {
364 f.t[pile][find_top(f.t[pile])+1] = f.s[--f.z];
365 remove_if_complete(pile);
366 if (check_won()) return WON;
367 }
368 undo_push(STOCK, TABLEU, 1, 0); /*NOTE: puts 1 card on each tableu pile*/
369 return OK;
370 }
371 int t2f(int from, int to, int opt) {
372 (void) to; (void) opt; /* don't need */
373 /* manually retrigger remove_if_complete() (e.g. after undo_pop) */
374 return remove_if_complete(from)?OK:ERR;
375 }
376 #endif
377 int nop(int from, int to, int opt) { (void)from;(void)to;(void)opt;return ERR; }
378 // }}}
379
380 // keyboard input handling {{{
381 // cursor functions{{{
382 #pragma GCC diagnostic ignored "-Wswitch" //not ideal :|
383 #ifdef KLONDIKE
384 void cursor_left (struct cursor* cursor) {
385 if (is_tableu(cursor->pile)) {
386 if (cursor->pile > 0) cursor->pile--;
387 cursor->opt = 0;
388 } else { /* stock/waste/foundation*/
389 switch (cursor->pile) {
390 case WASTE: cursor->pile = STOCK; cursor->opt = 0; break;
391 case FOUNDATION:
392 if (cursor->opt <= 0)
393 cursor->pile = WASTE;
394 else
395 cursor->opt--;
396 }
397 }
398 }
399 void cursor_down (struct cursor* cursor) {
400 if (!is_tableu(cursor->pile)) {
401 switch (cursor->pile) {
402 case STOCK: cursor->pile = TAB_1; break;
403 case WASTE: cursor->pile = TAB_2; break;
404 case FOUNDATION:
405 cursor->pile = TAB_4 + cursor->opt;
406 }
407 cursor->opt = 0;
408 }
409 }
410 void cursor_up (struct cursor* cursor) {
411 if (is_tableu(cursor->pile)) {
412 switch (cursor->pile) { //ugly :|
413 case TAB_1: cursor->pile = STOCK; break;
414 case TAB_2: cursor->pile = WASTE; break;
415 case TAB_3: cursor->pile = WASTE; break;
416 case TAB_4: case TAB_5: case TAB_6: case TAB_7:
417 cursor->opt=cursor->pile-TAB_4;
418 cursor->pile = FOUNDATION;
419 break;
420 }
421 }
422 }
423 void cursor_right (struct cursor* cursor) {
424 if (is_tableu(cursor->pile)) {
425 if (cursor->pile < TAB_MAX) cursor->pile++;
426 } else {
427 switch (cursor->pile) {
428 case STOCK: cursor->pile = WASTE; break;
429 case WASTE: cursor->pile = FOUNDATION;cursor->opt = 0; break;
430 case FOUNDATION:
431 if (cursor->opt < NUM_DECKS*NUM_SUITS)
432 cursor->opt++;
433 }
434 }
435 }
436 #elif defined SPIDER
437 /*NOTE: one can't highlight the stock due to me being too lazy to implement it*/
438 void cursor_left (struct cursor* cursor) {
439 if (cursor->pile > 0) cursor->pile--;
440 cursor->opt = 0;
441 }
442 void cursor_down (struct cursor* cursor) {
443 int first = first_movable(f.t[cursor->pile]);
444 int top = find_top(f.t[cursor->pile]);
445 if (first + cursor->opt < top)
446 cursor->opt++;
447 }
448 void cursor_up (struct cursor* cursor) {
449 if (cursor->opt > 0) cursor->opt--;
450 }
451 void cursor_right (struct cursor* cursor) {
452 if (cursor->pile < TAB_MAX) cursor->pile++;
453 cursor->opt = 0;
454 }
455 #endif
456 void cursor_to (struct cursor* cursor, int pile) {
457 cursor->pile = pile;
458 cursor->opt = 0;
459 }
460 #pragma GCC diagnostic pop
461 //}}}
462 int get_cmd (int* from, int* to, int* opt) {
463 //TODO: escape sequences (mouse, cursor keys)
464 int _f, t;
465 struct cursor inactive = {-1,-1};
466 static struct cursor active = {0,0};
467 active.opt = 0; /* always reset offset, but keep pile */
468
469 /***/
470 from_l: print_table(&active, &inactive);
471 _f = getchar();
472
473 switch (_f) {
474 /* direct addressing: */
475 case '1': *from = TAB_1; break;
476 case '2': *from = TAB_2; break;
477 case '3': *from = TAB_3; break;
478 case '4': *from = TAB_4; break;
479 case '5': *from = TAB_5; break;
480 case '6': *from = TAB_6; break;
481 case '7': *from = TAB_7; break;
482 #ifdef SPIDER
483 case '8': *from = TAB_8; break;
484 case '9': *from = TAB_9; break;
485 case '0': *from = TAB_10;break;
486 #elif defined KLONDIKE
487 case '9': *from = WASTE; break;
488 case '0': *from = FOUNDATION; break;
489 case '8': /* fallthrough */
490 #endif
491 case '\n': /* shortcut for dealing from stock */
492 *from = STOCK;
493 *to = WASTE;
494 return CMD_MOVE;
495 /* cursor keys addressing: */
496 case 'h': cursor_left (&active); goto from_l;
497 case 'j': cursor_down (&active); goto from_l;
498 case 'k': cursor_up (&active); goto from_l;
499 case 'l': cursor_right(&active); goto from_l;
500 case 'H': cursor_to(&active,TAB_1); goto from_l; /* leftmost tableu */
501 case 'L': cursor_to(&active,TAB_MAX);goto from_l; /* rigthmost tableu */
502 case 'M': cursor_to(&active,TAB_MAX/2); goto from_l; /* center tableu */
503 //TODO: real cursor keys, home/end
504 case ' ': /* continue with second cursor */
505 *from = active.pile;
506 if (*from == STOCK) {
507 *to = WASTE;
508 return CMD_MOVE;
509 }
510 #ifdef KLONDIKE
511 *opt = active.opt; /* when FOUNDATION */
512 #endif
513 inactive = active;
514 break;
515 /* misc keys: */
516 case ':':
517 {char buf[256];
518 fprintf (stderr, ":");
519 raw_mode(0); /* turn on echo */
520 fgets (buf, 256, stdin);
521 raw_mode(1);
522 switch(buf[0]) {
523 case 'q': return CMD_QUIT;
524 case 'n': return CMD_NEW;
525 case 'r': return CMD_AGAIN;
526 default: return CMD_INVAL;
527 }}
528 case 'J': return CMD_JOIN;
529 case 'K': /* fallthrough */
530 case '?': return CMD_HINT;
531 case 'u': return CMD_UNDO;
532 case EOF: return CMD_NONE; /* sent by SIGCONT */
533 default: return CMD_INVAL;
534 }
535 inactive.pile = *from; /* for direct addressing highlighting */
536 if (is_tableu(*from) && f.t[*from][0] == NO_CARD) return CMD_INVAL;
537
538 /***/
539 to_l: print_table(&active, &inactive);
540 t = getchar();
541
542 switch (t) {
543 case 'h': cursor_left (&active); goto to_l;
544 case 'j': cursor_down (&active); goto to_l;
545 case 'k': cursor_up (&active); goto to_l;
546 case 'l': cursor_right(&active); goto to_l;
547 case 'H': cursor_to(&active,TAB_1); goto to_l;
548 case 'L': cursor_to(&active,TAB_MAX); goto to_l;
549 case 'M': cursor_to(&active,TAB_MAX/2); goto to_l;
550 case 'J': /* fallthrough; key makes no sense on destination */
551 case ' ':
552 *to = active.pile;
553 break; /* continues with the foundation/empty tableu check */
554 case 'K': /* fallthrough */
555 case '?': return CMD_HINT;
556 case 'u': return CMD_NONE; /* cancel selection */
557 case EOF: return CMD_NONE; /* sent by SIGCONT */
558 default:
559 if (t < '0' || t > '9') return CMD_INVAL;
560 if (t == '0')
561 #ifdef KLONDIKE
562 *to = FOUNDATION;
563 #elif defined SPIDER
564 *to = TAB_10;
565 #endif
566 else
567 *to = t-'1';
568 }
569
570 /***/
571 #ifdef KLONDIKE
572 if (*from == FOUNDATION) {
573 int top = find_top(f.t[*to]);
574 if (top < 0) return CMD_INVAL;
575 int color = get_color(f.t[*to][top]);
576 int choice_1 = 1-color; /* selects piles of */
577 int choice_2 = 2+color; /* the opposite color */
578 int top_c1 = find_top(f.f[choice_1]);
579 int top_c2 = find_top(f.f[choice_2]);
580
581 switch ((rank_next(f.f[choice_1][top_c1], f.t[*to][top])
582 && top_c1 >= 0 ) << 0
583 |(rank_next(f.f[choice_2][top_c2], f.t[*to][top])
584 && top_c2 >= 0 ) << 1) {
585 case ( 1<<0): *opt = choice_1; break; /* choice_1 only */
586 case (1<<1 ): *opt = choice_2; break; /* choice_2 only */
587 case (1<<1 | 1<<0): /* both, ask user which to pick from */
588 printf ("take from (1-4): "); fflush (stdout);
589 *opt = getchar() - '1';
590 if (*opt < 0 || *opt > 3) return CMD_INVAL;
591 break;
592 default: return CMD_INVAL; /* none matched */
593 }
594 /* `opt` is the foundation index (0..3) */
595 }
596 #elif defined SPIDER
597 /* moving to empty tableu? */
598 if (is_tableu(*to) && f.t[*to][0] == NO_CARD) {
599 int bottom = first_movable(f.t[*from]);
600 if (inactive.opt >= 0) { /*if from was cursor addressed: */
601 *opt = get_rank(f.t[*from][bottom + inactive.opt]);
602 return CMD_MOVE;
603 }
604 int top = find_top(f.t[*from]);
605 if (top < 0) return CMD_INVAL;
606 if (top >= 0 && !is_movable(f.t[*from], top-1)) {
607 *opt = get_rank(f.t[*from][top]);
608 } else { /* only ask the user if it's unclear: */
609 printf ("\rup to ([a23456789xjqk] or space/return): ");
610 *opt = getchar();
611 switch (*opt) {
612 case ' ': *opt = get_rank(f.t[*from][top]); break;
613 case'\n': *opt = get_rank(f.t[*from][bottom]); break;
614 case 'a': case 'A': *opt = RANK_A; break;
615 case '0': /* fallthrough */
616 case 'x': case 'X': *opt = RANK_X; break;
617 case 'j': case 'J': *opt = RANK_J; break;
618 case 'q': case 'Q': *opt = RANK_Q; break;
619 case 'k': case 'K': *opt = RANK_K; break;
620 default: *opt -= '1';
621 }
622 if (*opt < RANK_A || *opt > RANK_K) return ERR;
623 }
624 /* `opt` is the rank of the highest card to move */
625 }
626 #endif
627 return CMD_MOVE;
628 }
629 // }}}
630
631 // shuffling and dealing {{{
632 void deal(void) {
633 f = (const struct playfield){0}; /* clear playfield */
634 card_t deck[DECK_SIZE*NUM_DECKS];
635 int avail = DECK_SIZE*NUM_DECKS;
636 for (int i = 0; i < DECK_SIZE*NUM_DECKS; i++) deck[i] = (i%DECK_SIZE)+1;
637 #ifdef SPIDER
638 if (op.m != NORMAL) for (int i = 0; i < DECK_SIZE*NUM_DECKS; i++) {
639 if (op.m == MEDIUM) deck[i] = 1+((deck[i]-1) | 2);
640 if (op.m == EASY) deck[i] = 1+((deck[i]-1) | 2 | 1);
641 /* the 1+ -1 dance gets rid of the offset created by NO_CARD */
642 }
643 #endif
644 srandom (time(NULL));
645 long seed = time(NULL);
646 srandom (seed);
647 for (int i = DECK_SIZE*NUM_DECKS-1; i > 0; i--) { /* fisher-yates */
648 int j = random() % (i+1);
649 if (j-i) deck[i]^=deck[j],deck[j]^=deck[i],deck[i]^=deck[j];
650 }
651
652 /* deal cards: */
653 for (int i = 0; i < NUM_PILES; i++) {
654 #ifdef KLONDIKE
655 int closed = i; /* pile n has n closed cards, then 1 open */
656 #elif defined SPIDER
657 int closed = i<4?5:4; /* pile 1-4 have 5, 5-10 have 4 closed */
658 #endif
659 /* face down cards are negated: */
660 for (int j = 0; j < closed; j++) f.t[i][j] = -deck[--avail];
661 f.t[i][closed] = deck[--avail]; /* the face-up card */
662 }
663 /* rest of the cards to the stock; NOTE: assert(avail==50) for spider */
664 for (f.z = 0; avail; f.z++) f.s[f.z] = deck[--avail];
665 #ifdef KLONDIKE
666 f.w = -1; /* @start: nothing on waste */
667 #elif defined SPIDER
668 f.w = 0; /* number of used foundations */
669 #endif
670
671 f.u = &undo_sentinel;
672 }
673 //}}}
674
675 // screen drawing routines {{{
676 void print_hi(int invert, int grey_bg, int bold, char* str) {
677 if (bold && op.s == &unicode_large_color){//ARGH! awful hack for bold with faint
678 int offset = str[3]==017?16:str[4]==017?17:0;
679 printf ("%s%s%s""%.*s%s%s""%s%s%s",
680 bold?"\033[1m":"", invert?"\033[7m":"", grey_bg?"\033[100m":"",
681 offset, str, bold?"\033[1m":"", str+offset,
682 grey_bg?"\033[49m":"", invert?"\033[27m":"",bold?"\033[22m":"");
683 return;
684 }
685 printf ("%s%s%s%s%s%s%s",
686 bold?"\033[1m":"", invert?"\033[7m":"", grey_bg?"\033[100m":"",
687 str,
688 grey_bg?"\033[49m":"", invert?"\033[27m":"",bold?"\033[22m":"");
689 }
690 void print_table(const struct cursor* active, const struct cursor* inactive) {
691 printf("\033[2J\033[H"); /* clear screen, reset cursor */
692 #ifdef KLONDIKE
693 /* print stock, waste and foundation: */
694 for (int line = 0; line < op.s->height; line++) {
695 /* stock: */
696 print_hi (active->pile == STOCK, inactive->pile == STOCK, 1, (
697 (f.w < f.z-1)?op.s->facedown
698 :op.s->placeholder)[line]);
699 /* waste: */
700 print_hi (active->pile == WASTE, inactive->pile == WASTE, 1, (
701 /* NOTE: cast, because f.w sometimes is (short)-1 !? */
702 ((short)f.w >= 0)?op.s->card[f.s[f.w]]
703 :op.s->placeholder)[line]);
704 printf ("%s", op.s->card[NO_CARD][line]); /* spacer */
705 /* foundation: */
706 for (int pile = 0; pile < NUM_SUITS; pile++) {
707 int card = find_top(f.f[pile]);
708 print_hi (active->pile==FOUNDATION && active->opt==pile,
709 inactive->pile==FOUNDATION && (
710 /* cursor addr. || direct addr. */
711 inactive->opt==pile || inactive->opt < 0
712 ), 1,
713 (card < 0)?op.s->placeholder[line]
714 :op.s->card[f.f[pile][card]][line]);
715 }
716 printf("\n");
717 }
718 printf("\n");
719 #elif defined SPIDER
720 int fdone; for (fdone = NUM_DECKS*NUM_SUITS; fdone; fdone--)
721 if (f.f[fdone-1][RANK_K]) break; /*number of completed stacks*/
722 int spacer_from = f.z?(f.z/10-1) * op.s->halfwidth[0] + op.s->width:0;
723 int spacer_to = NUM_PILES*op.s->width -
724 ((fdone?(fdone-1) * op.s->halfwidth[1]:0)+op.s->width);
725 for (int line = 0; line < op.s->height; line++) {
726 /* available stock: */
727 for (int i = f.z/10; i; i--) {
728 if (i==1) printf ("%s", op.s->facedown[line]);
729 else printf ("%s", op.s->halfstack[line]);
730 }
731 /* spacer: */
732 for (int i = spacer_from; i < spacer_to; i++) printf (" ");
733 /* foundation (overlapping): */
734 for (int i = 0; i < NUM_DECKS*NUM_SUITS; i++) { //TODO: print in revrse order (otherwise new piles get put 'below' older ones)
735 int overlap = i? op.s->halfcard[line]: 0;
736 if (f.f[i][RANK_K]) printf ("%.*s", op.s->halfwidth[2],
737 op.s->card[f.f[i][RANK_K]][line]+overlap);
738 }
739 printf("\n");
740 }
741 printf("\n");
742 #endif
743 #ifdef KLONDIKE
744 #define DO_HI(cursor) (cursor->pile == pile && (movable || empty))
745 #define TOP_HI(c) 1 /* can't select partial stacks in KLONDIKE */
746 #define INC_OFFSET
747 #elif defined SPIDER
748 int offset[NUM_PILES]={1,1,1,1,1,1,1,1,1,1}; // :|
749 #define DO_HI(cursor) (cursor->pile == pile && (movable || empty) \
750 && offset[pile] > cursor->opt)
751 #define TOP_HI(cursor) (cursor->pile == pile && movable \
752 && offset[pile]-1 == cursor->opt)
753 #define INC_OFFSET if (movable) offset[pile]++
754 #endif
755 /* print tableu piles: */
756 int row[NUM_PILES] = {0};
757 int line[NUM_PILES]= {0};
758 int label[NUM_PILES]={0};
759 int line_had_card;
760 int did_placeholders = 0;
761 do {
762 line_had_card = 0;
763 for (int pile = 0; pile < NUM_PILES; pile++) {
764 card_t card = f.t[pile][row[pile]];
765 card_t next = f.t[pile][row[pile]+1];
766 int movable = is_movable(f.t[pile], row[pile]);
767 int empty = !card && row[pile] == 0;
768
769 print_hi (DO_HI(active), DO_HI(inactive), movable, (
770 (!card && row[pile] == 0)?op.s->placeholder
771 :(card<0)?op.s->facedown
772 :op.s->card[card]
773 )[line[pile]]);
774
775 int extreme_overlap = ( 3 /* spacer, labels, status */
776 + 2 * op.s->height /* stock, top tableu card */
777 + find_top(f.t[pile]) * op.s->overlap) >op.w[0];
778 /* normal overlap: */
779 if (++line[pile] >= (next?op.s->overlap:op.s->height)
780 /* extreme overlap on closed cards: */
781 || (extreme_overlap &&
782 line[pile] >= 1 &&
783 f.t[pile][row[pile]] < 0 &&
784 f.t[pile][row[pile]+1] <0)
785 /* extreme overlap on sequences: */
786 || (extreme_overlap &&
787 !TOP_HI(active) && /*always show top selected card*/
788 line[pile] >= 1 && row[pile] > 0 &&
789 f.t[pile][row[pile]-1] > NO_CARD &&
790 is_consecutive (f.t[pile], row[pile]) &&
791 is_consecutive (f.t[pile], row[pile]-1) &&
792 f.t[pile][row[pile]+1] != NO_CARD)
793 ) {
794 line[pile]=0;
795 row[pile]++;
796 INC_OFFSET;
797 }
798 /* tableu labels: */
799 if(!card && !label[pile] && row[pile]>0&&line[pile]>0) {
800 label[pile] = 1;
801 printf ("\b\b%d ", (pile+1) % 10); //XXX: hack
802 }
803 line_had_card |= !!card;
804 did_placeholders |= row[pile] > 0;
805 }
806 printf ("\n");
807 } while (line_had_card || !did_placeholders);
808 }
809
810 void visbell (void) {
811 printf ("\033[?5h"); fflush (stdout);
812 usleep (100000);
813 printf ("\033[?5l"); fflush (stdout);
814 }
815 void win_anim(void) {
816 printf ("\033[?25l"); /* hide cursor */
817 for (;;) {
818 /* set cursor to random location */
819 int row = 1+random()%(24-op.s->width);
820 int col = 1+random()%(80-op.s->height);
821
822 /* draw random card */
823 int face = 1 + random() % 52;
824 for (int l = 0; l < op.s->height; l++) {
825 printf ("\033[%d;%dH", row+l, col);
826 printf ("%s", op.s->card[face][l]);
827 }
828 fflush (stdout);
829
830 /* exit on keypress */
831 struct pollfd p = {STDIN_FILENO, POLLIN, 0};
832 if (poll (&p, 1, 80)) goto fin;
833 }
834 fin:
835 printf ("\033[?25h"); /* show cursor */
836 return;
837 }
838 //}}}
839
840 // undo logic {{{
841 void undo_push (int _f, int t, int n, int o) {
842 struct undo* new = malloc(sizeof(struct undo));
843 new->f = _f;
844 new->t = t;
845 new->n = n;
846 new->o = o;
847 new->prev = f.u;
848 new->next = NULL;
849 f.u->next = new;
850 f.u = f.u->next;
851 }
852 void undo_pop (struct undo* u) {
853 if (u == &undo_sentinel) return;
854
855 #ifdef KLONDIKE
856 if (u->f == FOUNDATION) {
857 /* foundation -> tableu */
858 int top_f = find_top(f.f[u->n]);
859 int top_t = find_top(f.t[u->t]);
860 f.f[u->n][top_f+1] = f.t[u->t][top_t];
861 f.t[u->t][top_t] = NO_CARD;
862 } else if (u->f == WASTE && u->t == FOUNDATION) {
863 /* waste -> foundation */
864 /* split u->n into wst and fnd: */
865 int wst = u->n & 0xffff;
866 int fnd = u->n >> 16;
867 /* move stock cards one position up to make room: */
868 for (int i = f.z; i >= wst; i--) f.s[i+1] = f.s[i];
869 /* move one card from foundation to waste: */
870 int top = find_top(f.f[fnd]);
871 f.s[wst] = f.f[fnd][top];
872 f.f[fnd][top] = NO_CARD;
873 f.z++;
874 f.w++;
875 } else if (u->f == WASTE) {
876 /* waste -> tableu */
877 /* move stock cards one position up to make room: */
878 for (int i = f.z; i >= u->n; i--) f.s[i+1] = f.s[i];
879 /* move one card from tableu to waste: */
880 int top = find_top(f.t[u->t]);
881 f.s[u->n] = f.t[u->t][top];
882 f.t[u->t][top] = NO_CARD;
883 f.z++;
884 f.w++;
885 } else if (u->t == FOUNDATION) {
886 /* tableu -> foundation */
887 int top_f = find_top(f.t[u->f]);
888 int top_t = find_top(f.f[u->n]);
889 /* close topcard if previous action caused turn_over(): */
890 if (u->o) f.t[u->f][top_f] *= -1;
891 /* move one card from foundation to tableu: */
892 f.t[u->f][top_f+1] = f.f[u->n][top_t];
893 f.f[u->n][top_t] = NO_CARD;
894 } else {
895 /* tableu -> tableu */
896 int top_f = find_top(f.t[u->f]);
897 int top_t = find_top(f.t[u->t]);
898 /* close topcard if previous action caused turn_over(): */
899 if (u->o) f.t[u->f][top_f] *= -1;
900 /* move n cards from tableu[f] to tableu[t]: */
901 for (int i = 0; i < u->n; i++) {
902 f.t[u->f][top_f+u->n-i] = f.t[u->t][top_t-i];
903 f.t[u->t][top_t-i] = NO_CARD;
904 }
905 }
906 #elif defined SPIDER
907 if (u->f == STOCK) {
908 /* stock -> tableu */
909 /*remove a card from each pile and put it back onto the stock:*/
910 for (int pile = NUM_PILES-1; pile >= 0; pile--) {
911 int top = find_top(f.t[pile]);
912 f.s[f.z++] = f.t[pile][top];
913 f.t[pile][top] = NO_CARD;
914 }
915 } else if (u->t == FOUNDATION) {
916 /* tableu -> foundation */
917 int top = find_top(f.t[u->f]);
918 /* close topcard if previous action caused turn_over(): */
919 if (u->o) f.t[u->f][top] *= -1;
920 /* append cards from foundation to tableu */
921 for (int i = RANK_K; i >= RANK_A; i--) {
922 f.t[u->f][++top] = f.f[u->n][i];
923 f.f[u->n][i] = NO_CARD;
924 }
925 f.w--; /* decrement complete-foundation-counter */
926
927 } else {
928 /* tableu -> tableu */
929 int top_f = find_top(f.t[u->f]);
930 int top_t = find_top(f.t[u->t]);
931 /* close topcard if previous action caused turn_over(): */
932 if (u->o) f.t[u->f][top_f] *= -1;
933 /* move n cards from tableu[f] to tableu[t]: */
934 for (int i = 0; i < u->n; i++) {
935 f.t[u->f][top_f+u->n-i] = f.t[u->t][top_t-i];
936 f.t[u->t][top_t-i] = NO_CARD;
937 }
938 }
939 #endif
940
941 void* old = f.u;
942 f.u = f.u->prev;
943 free(old);
944 }
945 void free_undo (struct undo* u) {
946 while (u && u != &undo_sentinel) {
947 void* old = u;
948 u = u->prev;
949 free (old);
950 }
951 }
952 //}}}
953
954 // initialization stuff {{{
955 void screen_setup (int enable) {
956 if (enable) {
957 raw_mode(1);
958 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
959 printf ("\033[H\033[J"); /* reset cursor, clear screen */
960 //TODO//printf ("\033[?1000h\033[?25l"); /* enable mouse, hide cursor */
961 } else {
962 //TODO//printf ("\033[?9l\033[?25h"); /* disable mouse, show cursor */
963 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
964 raw_mode(0);
965 }
966 }
967
968 void raw_mode(int enable) {
969 static struct termios saved_term_mode;
970 struct termios raw_term_mode;
971
972 if (enable) {
973 if (saved_term_mode.c_lflag == 0)/*don't overwrite stored mode*/
974 tcgetattr(STDIN_FILENO, &saved_term_mode);
975 raw_term_mode = saved_term_mode;
976 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
977 raw_term_mode.c_cc[VMIN] = 1 ;
978 raw_term_mode.c_cc[VTIME] = 0;
979 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
980 } else {
981 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
982 }
983 }
984
985 void signal_handler (int signum) {
986 struct winsize w;
987 switch (signum) {
988 case SIGCONT:
989 screen_setup(0);
990 screen_setup(1);
991 print_table(NO_HI, NO_HI);
992 break;
993 case SIGINT: //TODO: don't exit; just warn like vim does
994 exit(128+SIGINT);
995 case SIGWINCH:
996 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
997 op.w[0] = w.ws_row;
998 op.w[1] = w.ws_col;
999 break;
1000 }
1001 }
1002 void signal_setup(void) {
1003 struct sigaction saction;
1004
1005 saction.sa_handler = signal_handler;
1006 sigemptyset(&saction.sa_mask);
1007 saction.sa_flags = 0;
1008 if (sigaction(SIGCONT, &saction, NULL) < 0) {
1009 perror ("SIGCONT");
1010 exit (1);
1011 }
1012 if (sigaction(SIGINT, &saction, NULL) < 0) {
1013 perror ("SIGINT");
1014 exit (1);
1015 }
1016 if (sigaction(SIGWINCH, &saction, NULL) < 0) {
1017 perror ("SIGWINCH");
1018 exit (1);
1019 }
1020 }
1021 //}}}
1022
1023 //vim: foldmethod=marker
Imprint / Impressum