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