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