]> git.gir.st - solVItaire.git/blob - sol.c
implement 'M' keybinding
[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 <time.h>
8 #include <termios.h>
9 #include <unistd.h>
10
11 #include "sol.h"
12 #include "schemes.h"
13
14 struct playfield f;
15 struct opts op;
16
17 // action table {{{
18 /* stores a function pointer for every takeable action; called by game loop */
19 int (*action[NUM_PLACES][10])(int,int,int) = {
20 #ifdef KLONDIKE
21 /* 1 2 3 4 5 6 7 stk wst fnd*/
22 /* 1 */ { t2f, t2t, t2t, t2t, t2t, t2t, t2t, nop, nop, t2f },
23 /* 2 */ { t2t, t2f, t2t, t2t, t2t, t2t, t2t, nop, nop, t2f },
24 /* 3 */ { t2t, t2t, t2f, t2t, t2t, t2t, t2t, nop, nop, t2f },
25 /* 4 */ { t2t, t2t, t2t, t2f, t2t, t2t, t2t, nop, nop, t2f },
26 /* 5 */ { t2t, t2t, t2t, t2t, t2f, t2t, t2t, nop, nop, t2f },
27 /* 6 */ { t2t, t2t, t2t, t2t, t2t, t2f, t2t, nop, nop, t2f },
28 /* 7 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2f, nop, nop, t2f },
29 /*stk*/ { nop, nop, nop, nop, nop, nop, nop, nop, s2w, nop },
30 /*wst*/ { w2t, w2t, w2t, w2t, w2t, w2t, w2t, w2s, w2f, w2f },
31 /*fnd*/ { f2t, f2t, f2t, f2t, f2t, f2t, f2t, nop, nop, nop },
32 #elif defined SPIDER
33 /* 1 2 3 4 5 6 7 8 9 10*/
34 /* 1 */ { t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t },
35 /* 2 */ { t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t },
36 /* 3 */ { t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2t },
37 /* 4 */ { t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2t },
38 /* 5 */ { t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2t },
39 /* 6 */ { t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2t },
40 /* 7 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2t },
41 /* 8 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2t },
42 /* 9 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2t },
43 /*10 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2f },
44 /*stk*/ { s2t, s2t, s2t, s2t, s2t, s2t, s2t, s2t, s2t, s2t },
45 #endif
46 };
47 // }}}
48
49 // argv parsing, game loops, cleanup {{{
50 int main(int argc, char** argv) {
51 /* opinionated defaults: */
52 op.s = &unicode_large_color;
53 #ifdef SPIDER
54 op.m = MEDIUM;
55 #endif
56 op.v = 0;
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 'v': op.v = 1; break; /* conserve vertical space */
72 case 'b': op.s = &unicode_large_mono; break;
73 case 'c': op.s = &unicode_large_color; break;
74 case 'm': op.s = &unicode_small_mono; break; /* "mini" */
75 case 'h': default: goto error;
76 error:
77 fprintf (stderr, SHORTHELP LONGHELP KEYHELP, argv[0]);
78 return optget != 'h';
79 }
80 }
81
82 signal_setup();
83 atexit (*quit);
84
85 newgame:
86 screen_setup(1);
87
88 switch(sol()) {
89 case GAME_NEW: goto newgame;
90 case GAME_WON:
91 print_table(NO_HI, NO_HI);
92 win_anim();
93 if (getchar()=='q') return 0;
94 goto newgame;
95 case GAME_QUIT: return 0;
96 }
97 }
98
99 int sol(void) {
100 /* clean undo (from previous game): */
101 free_undo(f.u);
102
103 deal();
104
105 int from, to, opt;
106 for(;;) {
107 switch (get_cmd(&from, &to, &opt)) {
108 case CMD_MOVE:
109 switch (action[from][to](from,to,opt)) {
110 case OK: break;
111 case ERR: visbell(); break;
112 case WON: return GAME_WON;
113 }
114 break;
115 case CMD_HINT: break;//TODO: show a possible (and sensible) move
116 case CMD_JOIN: break;//TODO: join any pile to here (longest if possible)
117 case CMD_UNDO: undo_pop(f.u); break;
118 case CMD_INVAL: visbell(); break;
119 case CMD_NEW: return GAME_NEW;
120 case CMD_AGAIN: //TODO: restart with same seed
121 case CMD_QUIT: return GAME_QUIT;
122 }
123 }
124 }
125
126 void quit(void) {
127 screen_setup(0);
128 /* free undo data structures: */
129 free_undo(f.u);
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 undo_push(from, FOUNDATION, to,
224 turn_over(f.t[from]));
225 if (check_won()) return WON;
226 return OK;
227 } else return ERR;
228 }
229 int w2f(int from, int to, int opt) { /* waste to foundation */
230 (void) from; (void) to; (void) opt; /* don't need */
231 if (f.w < 0) return ERR;
232 to = get_suit(f.s[f.w]);
233 int top_to = find_top(f.f[to]);
234 if ((top_to < 0 && get_rank(f.s[f.w]) == RANK_A)
235 || (top_to >= 0 && rank_next(f.f[to][top_to], f.s[f.w]))) {
236 undo_push(WASTE, FOUNDATION, f.w | to<<16, 0);//ugly encoding :|
237 f.f[to][top_to+1] = stack_take();
238 if (check_won()) return WON;
239 return OK;
240 } else return ERR;
241
242 }
243 int s2w(int from, int to, int opt) { /* stock to waste */
244 (void) from; (void) to; (void) opt; /* don't need */
245 if (f.z == 0) return ERR;
246 f.w++;
247 if (f.w == f.z) f.w = -1;
248 return OK;
249 }
250 int w2s(int from, int to, int opt) { /* waste to stock (undo stock to waste) */
251 (void) from; (void) to; (void) opt; /* don't need */
252 if (f.z == 0) return ERR;
253 f.w--;
254 if (f.w < -1) f.w = f.z-1;
255 return OK;
256 }
257 int f2t(int from, int to, int opt) { /* foundation to tableu */
258 (void) from; /* don't need */
259 int top_to = find_top(f.t[to]);
260 from = opt;
261 int top_from = find_top(f.f[from]);
262
263 if ((get_color(f.t[to][top_to]) != get_color(f.f[from][top_from]))
264 && (rank_next(f.f[from][top_from], f.t[to][top_to]))) {
265 f.t[to][top_to+1] = f.f[from][top_from];
266 f.f[from][top_from] = NO_CARD;
267 undo_push(FOUNDATION, to, from, 0);
268 return OK;
269 } else return ERR;
270 }
271 int w2t(int from, int to, int opt) { /* waste to tableu */
272 (void) from; (void) opt; /* don't need */
273 int top_to = find_top(f.t[to]);
274 if (((get_color(f.t[to][top_to]) != get_color(f.s[f.w]))
275 && (rank_next(f.s[f.w], f.t[to][top_to])))
276 || (top_to < 0 && get_rank(f.s[f.w]) == RANK_K)) {
277 undo_push(WASTE, to, f.w, 0);
278 f.t[to][top_to+1] = stack_take();
279 return OK;
280 } else return ERR;
281 }
282 int t2t(int from, int to, int opt) { /* tableu to tableu */
283 (void) opt; /* don't need */
284 int top_to = find_top(f.t[to]);
285 int top_from = find_top(f.t[from]);
286 int count = 0; //NOTE: could probably be factored out
287 for (int i = top_from; i >=0; i--) {
288 if (((get_color(f.t[to][top_to]) != get_color(f.t[from][i]))
289 && (rank_next(f.t[from][i], f.t[to][top_to]))
290 && f.t[from][i] > NO_CARD) /* card face up? */
291 || (top_to < 0 && get_rank(f.t[from][i]) == RANK_K)) {
292 /* move cards [i..top_from] to their destination */
293 for (;i <= top_from; i++) {
294 top_to++;
295 f.t[to][top_to] = f.t[from][i];
296 f.t[from][i] = NO_CARD;
297 count++;
298 }
299 undo_push(from, to, count,
300 turn_over(f.t[from]));
301 return OK;
302 }
303 }
304 return ERR; /* no such move possible */
305 }
306 #elif defined SPIDER
307 int remove_if_complete (int pileno) { //cleanup!
308 card_t* pile = f.t[pileno];
309 /* test if K...A complete; move to foundation if so */
310 int top_from = find_top(pile);
311 if (get_rank(pile[top_from]) != RANK_A) return 0;
312 for (int i = top_from; i>=0; i--) {
313 if (!is_consecutive (pile, i)) return 0;
314 if (i+RANK_K == top_from /* if ace to king: remove it */
315 && get_rank(pile[top_from-RANK_K]) == RANK_K) {
316 for(int i=top_from, j=0; i>top_from-NUM_RANKS; i--,j++){
317 f.f[f.w][j] = pile[i];
318 pile[i] = NO_CARD;
319 }
320 undo_push(pileno, FOUNDATION, f.w,
321 turn_over(pile));
322 f.w++;
323 return 1;
324 }
325 }
326
327 return 0;
328 }
329 int t2t(int from, int to, int opt) { //in dire need of cleanup
330 int top_from = find_top(f.t[from]);
331 int top_to = find_top(f.t[to]);
332 int empty_to = (top_to < 0)? opt: -1; /* empty pile? */
333 int count = 0; //NOTE: could probably be factored out
334
335 for (int i = top_from; i >= 0; i--) {
336 if (!is_consecutive(f.t[from], i)) break;
337
338 /* is consecutive OR to empty pile and rank ok? */
339 if (rank_next(f.t[from][i], f.t[to][top_to])
340 || (empty_to >= RANK_A && get_rank(f.t[from][i]) == empty_to)) {
341 for (;i <= top_from; i++) {
342 top_to++;
343 f.t[to][top_to] = f.t[from][i];
344 f.t[from][i] = NO_CARD;
345 count++;
346 }
347 undo_push(from, to, count,
348 turn_over(f.t[from]));
349 remove_if_complete(to);
350 if (check_won()) return WON;
351 return OK;
352 }
353 }
354
355 return ERR; /* no such move possible */
356 }
357 int s2t(int from, int to, int opt) {
358 (void) from; (void) to; (void) opt; /* don't need */
359 if (f.z <= 0) return ERR; /* stack out of cards */
360 for (int pile = 0; pile < NUM_PILES; pile++)
361 if (f.t[pile][0]==NO_CARD) return ERR; /*no piles may be empty*/
362 for (int pile = 0; pile < NUM_PILES; pile++) {
363 f.t[pile][find_top(f.t[pile])+1] = f.s[--f.z];
364 remove_if_complete(pile);
365 if (check_won()) return WON;
366 }
367 undo_push(STOCK, TABLEU, 1, 0); /*NOTE: puts 1 card on each tableu pile*/
368 return OK;
369 }
370 int t2f(int from, int to, int opt) {
371 (void) to; (void) opt; /* don't need */
372 /* manually retrigger remove_if_complete() (e.g. after undo_pop) */
373 return remove_if_complete(from)?OK:ERR;
374 }
375 #endif
376 int nop(int from, int to, int opt) { (void)from;(void)to;(void)opt;return ERR; }
377 // }}}
378
379 // keyboard input handling {{{
380 // cursor functions{{{
381 #pragma GCC diagnostic ignored "-Wswitch" //not ideal :|
382 #ifdef KLONDIKE
383 void cursor_left (struct cursor* cursor) {
384 if (is_tableu(cursor->pile)) {
385 if (cursor->pile > 0) cursor->pile--;
386 cursor->opt = 0;
387 } else { /* stock/waste/foundation*/
388 switch (cursor->pile) {
389 case WASTE: cursor->pile = STOCK; cursor->opt = 0; break;
390 case FOUNDATION:
391 if (cursor->opt <= 0)
392 cursor->pile = WASTE;
393 else
394 cursor->opt--;
395 }
396 }
397 }
398 void cursor_down (struct cursor* cursor) {
399 if (!is_tableu(cursor->pile)) {
400 switch (cursor->pile) {
401 case STOCK: cursor->pile = TAB_1; break;
402 case WASTE: cursor->pile = TAB_2; break;
403 case FOUNDATION:
404 cursor->pile = TAB_4 + cursor->opt;
405 }
406 cursor->opt = 0;
407 }
408 }
409 void cursor_up (struct cursor* cursor) {
410 if (is_tableu(cursor->pile)) {
411 switch (cursor->pile) { //ugly :|
412 case TAB_1: cursor->pile = STOCK; break;
413 case TAB_2: cursor->pile = WASTE; break;
414 case TAB_3: cursor->pile = WASTE; break;
415 case TAB_4: case TAB_5: case TAB_6: case TAB_7:
416 cursor->opt=cursor->pile-TAB_4;
417 cursor->pile = FOUNDATION;
418 break;
419 }
420 }
421 }
422 void cursor_right (struct cursor* cursor) {
423 if (is_tableu(cursor->pile)) {
424 if (cursor->pile < TAB_MAX) cursor->pile++;
425 } else {
426 switch (cursor->pile) {
427 case STOCK: cursor->pile = WASTE; break;
428 case WASTE: cursor->pile = FOUNDATION;cursor->opt = 0; break;
429 case FOUNDATION:
430 if (cursor->opt < NUM_DECKS*NUM_SUITS)
431 cursor->opt++;
432 }
433 }
434 }
435 #elif defined SPIDER
436 /*NOTE: one can't highlight the stock due to me being too lazy to implement it*/
437 void cursor_left (struct cursor* cursor) {
438 if (cursor->pile > 0) cursor->pile--;
439 cursor->opt = 0;
440 }
441 void cursor_down (struct cursor* cursor) {
442 int first = first_movable(f.t[cursor->pile]);
443 int top = find_top(f.t[cursor->pile]);
444 if (first + cursor->opt < top)
445 cursor->opt++;
446 }
447 void cursor_up (struct cursor* cursor) {
448 if (cursor->opt > 0) cursor->opt--;
449 }
450 void cursor_right (struct cursor* cursor) {
451 if (cursor->pile < TAB_MAX) cursor->pile++;
452 cursor->opt = 0;
453 }
454 #endif
455 void cursor_to (struct cursor* cursor, int pile) {
456 cursor->pile = pile;
457 cursor->opt = 0;
458 }
459 #pragma GCC diagnostic pop
460 //}}}
461 int get_cmd (int* from, int* to, int* opt) {
462 //TODO: escape sequences (mouse, cursor keys)
463 int _f, t;
464 struct cursor inactive = {-1,-1};
465 static struct cursor active = {0,0};
466 active.opt = 0; /* always reset offset, but keep pile */
467
468 /***/
469 from_l: print_table(&active, &inactive);
470 _f = getchar();
471
472 switch (_f) {
473 /* direct addressing: */
474 case '1': *from = TAB_1; break;
475 case '2': *from = TAB_2; break;
476 case '3': *from = TAB_3; break;
477 case '4': *from = TAB_4; break;
478 case '5': *from = TAB_5; break;
479 case '6': *from = TAB_6; break;
480 case '7': *from = TAB_7; break;
481 #ifdef SPIDER
482 case '8': *from = TAB_8; break;
483 case '9': *from = TAB_9; break;
484 case '0': *from = TAB_10;break;
485 #elif defined KLONDIKE
486 case '9': *from = WASTE; break;
487 case '0': *from = FOUNDATION; break;
488 case '8': /* fallthrough */
489 #endif
490 case '\n': /* shortcut for dealing from stock */
491 *from = STOCK;
492 *to = WASTE;
493 return CMD_MOVE;
494 /* cursor keys addressing: */
495 case 'h': cursor_left (&active); goto from_l;
496 case 'j': cursor_down (&active); goto from_l;
497 case 'k': cursor_up (&active); goto from_l;
498 case 'l': cursor_right(&active); goto from_l;
499 case 'H': cursor_to(&active,TAB_1); goto from_l; /* leftmost tableu */
500 case 'L': cursor_to(&active,TAB_MAX);goto from_l; /* rigthmost tableu */
501 case 'M': cursor_to(&active,TAB_MAX/2); goto from_l; /* center tableu */
502 //TODO: real cursor keys, home/end
503 case ' ': /* continue with second cursor */
504 *from = active.pile;
505 if (*from == STOCK) {
506 *to = WASTE;
507 return CMD_MOVE;
508 }
509 #ifdef KLONDIKE
510 *opt = active.opt; /* when FOUNDATION */
511 #endif
512 inactive = active;
513 break;
514 /* misc keys: */
515 case ':':
516 {char buf[256];
517 fprintf (stderr, ":");
518 raw_mode(0); /* turn on echo */
519 fgets (buf, 256, stdin);
520 raw_mode(1);
521 switch(buf[0]) {
522 case 'q': return CMD_QUIT;
523 case 'n': return CMD_NEW;
524 case 'r': return CMD_AGAIN;
525 default: return CMD_INVAL;
526 }}
527 case 'J': return CMD_JOIN;
528 case 'K': /* fallthrough */
529 case '?': return CMD_HINT;
530 case 'u': return CMD_UNDO;
531 case EOF: return CMD_NONE; /* sent by SIGCONT */
532 default: return CMD_INVAL;
533 }
534 inactive.pile = *from; /* for direct addressing highlighting */
535 if (is_tableu(*from) && f.t[*from][0] == NO_CARD) return CMD_INVAL;
536
537 /***/
538 to_l: print_table(&active, &inactive);
539 t = getchar();
540
541 switch (t) {
542 case 'h': cursor_left (&active); goto to_l;
543 case 'j': cursor_down (&active); goto to_l;
544 case 'k': cursor_up (&active); goto to_l;
545 case 'l': cursor_right(&active); goto to_l;
546 case 'H': cursor_to(&active,TAB_1); goto to_l;
547 case 'L': cursor_to(&active,TAB_MAX); goto to_l;
548 case 'M': cursor_to(&active,TAB_MAX/2); 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 #ifdef KLONDIKE
665 f.w = -1; /* @start: nothing on waste */
666 #elif defined SPIDER
667 f.w = 0; /* number of used foundations */
668 #endif
669
670 f.u = &undo_sentinel;
671 }
672 //}}}
673
674 // screen drawing routines {{{
675 void print_hi(int invert, int grey_bg, int bold, char* str) {
676 if (bold && op.s == &unicode_large_color){//ARGH! awful hack for bold with faint
677 int offset = str[3]==017?16:str[4]==017?17:0;
678 printf ("%s%s%s""%.*s%s%s""%s%s%s",
679 bold?"\033[1m":"", invert?"\033[7m":"", grey_bg?"\033[100m":"",
680 offset, str, bold?"\033[1m":"", str+offset,
681 grey_bg?"\033[49m":"", invert?"\033[27m":"",bold?"\033[22m":"");
682 return;
683 }
684 printf ("%s%s%s%s%s%s%s",
685 bold?"\033[1m":"", invert?"\033[7m":"", grey_bg?"\033[100m":"",
686 str,
687 grey_bg?"\033[49m":"", invert?"\033[27m":"",bold?"\033[22m":"");
688 }
689 void print_table(const struct cursor* active, const struct cursor* inactive) {
690 printf("\033[2J\033[H"); /* clear screen, reset cursor */
691 #ifdef KLONDIKE
692 /* print stock, waste and foundation: */
693 for (int line = 0; line < op.s->height; line++) {
694 /* stock: */
695 print_hi (active->pile == STOCK, inactive->pile == STOCK, 1, (
696 (f.w < f.z-1)?op.s->facedown
697 :op.s->placeholder)[line]);
698 /* waste: */
699 print_hi (active->pile == WASTE, inactive->pile == WASTE, 1, (
700 /* NOTE: cast, because f.w sometimes is (short)-1 !? */
701 ((short)f.w >= 0)?op.s->card[f.s[f.w]]
702 :op.s->placeholder)[line]);
703 printf ("%s", op.s->card[NO_CARD][line]); /* spacer */
704 /* foundation: */
705 for (int pile = 0; pile < NUM_SUITS; pile++) {
706 int card = find_top(f.f[pile]);
707 print_hi (active->pile==FOUNDATION && active->opt==pile,
708 inactive->pile==FOUNDATION && (
709 /* cursor addr. || direct addr. */
710 inactive->opt==pile || inactive->opt < 0
711 ), 1,
712 (card < 0)?op.s->placeholder[line]
713 :op.s->card[f.f[pile][card]][line]);
714 }
715 printf("\n");
716 }
717 printf("\n");
718 #elif defined SPIDER
719 int fdone; for (fdone = NUM_DECKS*NUM_SUITS; fdone; fdone--)
720 if (f.f[fdone-1][RANK_K]) break; /*number of completed stacks*/
721 int spacer_from = f.z?(f.z/10-1) * op.s->halfwidth[0] + op.s->width:0;
722 int spacer_to = NUM_PILES*op.s->width -
723 ((fdone?(fdone-1) * op.s->halfwidth[1]:0)+op.s->width);
724 for (int line = 0; line < op.s->height; line++) {
725 /* available stock: */
726 for (int i = f.z/10; i; i--) {
727 if (i==1) printf ("%s", op.s->facedown[line]);
728 else printf ("%s", op.s->halfstack[line]);
729 }
730 /* spacer: */
731 for (int i = spacer_from; i < spacer_to; i++) printf (" ");
732 /* foundation (overlapping): */
733 for (int i = 0; i < NUM_DECKS*NUM_SUITS; i++) { //TODO: print in revrse order (otherwise new piles get put 'below' older ones)
734 int overlap = i? op.s->halfcard[line]: 0;
735 if (f.f[i][RANK_K]) printf ("%.*s", op.s->halfwidth[2],
736 op.s->card[f.f[i][RANK_K]][line]+overlap);
737 }
738 printf("\n");
739 }
740 printf("\n");
741 #endif
742 #ifdef KLONDIKE
743 #define DO_HI(cursor) (cursor->pile == pile && (movable || empty))
744 #define TOP_HI(c) 1 /* can't select partial stacks in KLONDIKE */
745 #define INC_OFFSET
746 #elif defined SPIDER
747 int offset[NUM_PILES]={1,1,1,1,1,1,1,1,1,1}; // :|
748 #define DO_HI(cursor) (cursor->pile == pile && (movable || empty) \
749 && offset[pile] > cursor->opt)
750 #define TOP_HI(cursor) (cursor->pile == pile && movable \
751 && offset[pile]-1 == cursor->opt)
752 #define INC_OFFSET if (movable) offset[pile]++
753 #endif
754 /* print tableu piles: */
755 int row[NUM_PILES] = {0};
756 int line[NUM_PILES]= {0};
757 int label[NUM_PILES]={0};
758 int line_had_card;
759 int did_placeholders = 0;
760 do {
761 line_had_card = 0;
762 for (int pile = 0; pile < NUM_PILES; pile++) {
763 card_t card = f.t[pile][row[pile]];
764 card_t next = f.t[pile][row[pile]+1];
765 int movable = is_movable(f.t[pile], row[pile]);
766 int empty = !card && row[pile] == 0;
767
768 print_hi (DO_HI(active), DO_HI(inactive), movable, (
769 (!card && row[pile] == 0)?op.s->placeholder
770 :(card<0)?op.s->facedown
771 :op.s->card[card]
772 )[line[pile]]);
773
774 int extreme_overlap = op.v && find_top(f.t[pile])>10;
775 /* normal overlap: */
776 if (++line[pile] >= (next?op.s->overlap:op.s->height)
777 /* extreme overlap on closed cards: */
778 || (extreme_overlap &&
779 line[pile] >= 1 &&
780 f.t[pile][row[pile]] < 0 &&
781 f.t[pile][row[pile]+1] <0)
782 /* extreme overlap on sequences: */
783 || (extreme_overlap &&
784 !TOP_HI(active) && /*always show top selected card*/
785 line[pile] >= 1 && row[pile] > 0 &&
786 f.t[pile][row[pile]-1] > NO_CARD &&
787 is_consecutive (f.t[pile], row[pile]) &&
788 is_consecutive (f.t[pile], row[pile]-1) &&
789 f.t[pile][row[pile]+1] != NO_CARD)
790 ) {
791 line[pile]=0;
792 row[pile]++;
793 INC_OFFSET;
794 }
795 /* tableu labels: */
796 if(!card && !label[pile] && row[pile]>0&&line[pile]>0) {
797 label[pile] = 1;
798 printf ("\b\b%d ", (pile+1) % 10); //XXX: hack
799 }
800 line_had_card |= !!card;
801 did_placeholders |= row[pile] > 0;
802 }
803 printf ("\n");
804 } while (line_had_card || !did_placeholders);
805 }
806
807 void visbell (void) {
808 printf ("\033[?5h"); fflush (stdout);
809 usleep (100000);
810 printf ("\033[?5l"); fflush (stdout);
811 }
812 void win_anim(void) {
813 printf ("\033[?25l"); /* hide cursor */
814 for (;;) {
815 /* set cursor to random location */
816 int row = 1+random()%(24-op.s->width);
817 int col = 1+random()%(80-op.s->height);
818
819 /* draw random card */
820 int face = 1 + random() % 52;
821 for (int l = 0; l < op.s->height; l++) {
822 printf ("\033[%d;%dH", row+l, col);
823 printf ("%s", op.s->card[face][l]);
824 }
825 fflush (stdout);
826
827 /* exit on keypress */
828 struct pollfd p = {STDIN_FILENO, POLLIN, 0};
829 if (poll (&p, 1, 80)) goto fin;
830 }
831 fin:
832 printf ("\033[?25h"); /* show cursor */
833 return;
834 }
835 //}}}
836
837 // undo logic {{{
838 void undo_push (int _f, int t, int n, int o) {
839 struct undo* new = malloc(sizeof(struct undo));
840 new->f = _f;
841 new->t = t;
842 new->n = n;
843 new->o = o;
844 new->prev = f.u;
845 new->next = NULL;
846 f.u->next = new;
847 f.u = f.u->next;
848 }
849 void undo_pop (struct undo* u) {
850 if (u == &undo_sentinel) return;
851
852 #ifdef KLONDIKE
853 if (u->f == FOUNDATION) {
854 /* foundation -> tableu */
855 int top_f = find_top(f.f[u->n]);
856 int top_t = find_top(f.t[u->t]);
857 f.f[u->n][top_f+1] = f.t[u->t][top_t];
858 f.t[u->t][top_t] = NO_CARD;
859 } else if (u->f == WASTE && u->t == FOUNDATION) {
860 /* waste -> foundation */
861 /* split u->n into wst and fnd: */
862 int wst = u->n & 0xffff;
863 int fnd = u->n >> 16;
864 /* move stock cards one position up to make room: */
865 for (int i = f.z; i >= wst; i--) f.s[i+1] = f.s[i];
866 /* move one card from foundation to waste: */
867 int top = find_top(f.f[fnd]);
868 f.s[wst] = f.f[fnd][top];
869 f.f[fnd][top] = NO_CARD;
870 f.z++;
871 f.w++;
872 } else if (u->f == WASTE) {
873 /* waste -> tableu */
874 /* move stock cards one position up to make room: */
875 for (int i = f.z; i >= u->n; i--) f.s[i+1] = f.s[i];
876 /* move one card from tableu to waste: */
877 int top = find_top(f.t[u->t]);
878 f.s[u->n] = f.t[u->t][top];
879 f.t[u->t][top] = NO_CARD;
880 f.z++;
881 f.w++;
882 } else if (u->t == FOUNDATION) {
883 /* tableu -> foundation */
884 int top_f = find_top(f.t[u->f]);
885 int top_t = find_top(f.f[u->n]);
886 /* close topcard if previous action caused turn_over(): */
887 if (u->o) f.t[u->f][top_f] *= -1;
888 /* move one card from foundation to tableu: */
889 f.t[u->f][top_f+1] = f.f[u->n][top_t];
890 f.f[u->n][top_t] = NO_CARD;
891 } else {
892 /* tableu -> tableu */
893 int top_f = find_top(f.t[u->f]);
894 int top_t = find_top(f.t[u->t]);
895 /* close topcard if previous action caused turn_over(): */
896 if (u->o) f.t[u->f][top_f] *= -1;
897 /* move n cards from tableu[f] to tableu[t]: */
898 for (int i = 0; i < u->n; i++) {
899 f.t[u->f][top_f+u->n-i] = f.t[u->t][top_t-i];
900 f.t[u->t][top_t-i] = NO_CARD;
901 }
902 }
903 #elif defined SPIDER
904 if (u->f == STOCK) {
905 /* stock -> tableu */
906 /*remove a card from each pile and put it back onto the stock:*/
907 for (int pile = NUM_PILES-1; pile >= 0; pile--) {
908 int top = find_top(f.t[pile]);
909 f.s[f.z++] = f.t[pile][top];
910 f.t[pile][top] = NO_CARD;
911 }
912 } else if (u->t == FOUNDATION) {
913 /* tableu -> foundation */
914 int top = find_top(f.t[u->f]);
915 /* close topcard if previous action caused turn_over(): */
916 if (u->o) f.t[u->f][top] *= -1;
917 /* append cards from foundation to tableu */
918 for (int i = RANK_K; i >= RANK_A; i--) {
919 f.t[u->f][++top] = f.f[u->n][i];
920 f.f[u->n][i] = NO_CARD;
921 }
922 f.w--; /* decrement complete-foundation-counter */
923
924 } else {
925 /* tableu -> tableu */
926 int top_f = find_top(f.t[u->f]);
927 int top_t = find_top(f.t[u->t]);
928 /* close topcard if previous action caused turn_over(): */
929 if (u->o) f.t[u->f][top_f] *= -1;
930 /* move n cards from tableu[f] to tableu[t]: */
931 for (int i = 0; i < u->n; i++) {
932 f.t[u->f][top_f+u->n-i] = f.t[u->t][top_t-i];
933 f.t[u->t][top_t-i] = NO_CARD;
934 }
935 }
936 #endif
937
938 void* old = f.u;
939 f.u = f.u->prev;
940 free(old);
941 }
942 void free_undo (struct undo* u) {
943 while (u && u != &undo_sentinel) {
944 void* old = u;
945 u = u->prev;
946 free (old);
947 }
948 }
949 //}}}
950
951 // initialization stuff {{{
952 void screen_setup (int enable) {
953 if (enable) {
954 raw_mode(1);
955 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
956 printf ("\033[H\033[J"); /* reset cursor, clear screen */
957 //TODO//printf ("\033[?1000h\033[?25l"); /* enable mouse, hide cursor */
958 } else {
959 //TODO//printf ("\033[?9l\033[?25h"); /* disable mouse, show cursor */
960 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
961 raw_mode(0);
962 }
963 }
964
965 void raw_mode(int enable) {
966 static struct termios saved_term_mode;
967 struct termios raw_term_mode;
968
969 if (enable) {
970 if (saved_term_mode.c_lflag == 0)/*don't overwrite stored mode*/
971 tcgetattr(STDIN_FILENO, &saved_term_mode);
972 raw_term_mode = saved_term_mode;
973 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
974 raw_term_mode.c_cc[VMIN] = 1 ;
975 raw_term_mode.c_cc[VTIME] = 0;
976 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
977 } else {
978 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
979 }
980 }
981
982 void signal_handler (int signum) {
983 switch (signum) {
984 case SIGCONT:
985 screen_setup(0);
986 screen_setup(1);
987 print_table(NO_HI, NO_HI);
988 break;
989 case SIGINT:
990 exit(128+SIGINT);
991 }
992 }
993 void signal_setup(void) {
994 struct sigaction saction;
995
996 saction.sa_handler = signal_handler;
997 sigemptyset(&saction.sa_mask);
998 saction.sa_flags = 0;
999 if (sigaction(SIGCONT, &saction, NULL) < 0) {
1000 perror ("SIGCONT");
1001 exit (1);
1002 }
1003 if (sigaction(SIGINT, &saction, NULL) < 0) {
1004 perror ("SIGINT");
1005 exit (1);
1006 }
1007 }
1008 //}}}
1009
1010 //vim: foldmethod=marker
Imprint / Impressum