]> git.gir.st - solVItaire.git/blob - sol.c
freecell: smart card selector, part 2
[solVItaire.git] / sol.c
1 #define _DEFAULT_SOURCE /* for getopt, sigaction, usleep */
2 #include <poll.h>
3 #include <signal.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <sys/ioctl.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 #elif defined FREECELL
46 /* 1 2 3 4 5 6 7 8 cll fnd*/
47 /* 1 */ { t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2c, t2f },
48 /* 2 */ { t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2c, t2f },
49 /* 3 */ { t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2c, t2f },
50 /* 4 */ { t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2c, t2f },
51 /* 5 */ { t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2c, t2f },
52 /* 6 */ { t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2c, t2f },
53 /* 7 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2c, t2f },
54 /* 8 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2c, t2f },
55 /*cll*/ { c2t, c2t, c2t, c2t, c2t, c2t, c2t, c2t, c2f, c2f },
56 /*fnd*/ { f2t, f2t, f2t, f2t, f2t, f2t, f2t, f2t, f2c, nop },
57 #endif
58 };
59 // }}}
60
61 // argv parsing, game loops, cleanup {{{
62 int main(int argc, char** argv) {
63 /* opinionated defaults: */
64 op.s = &unicode_large_color;
65 op.v = 1; /* enable fake visbell by default */
66 #ifdef SPIDER
67 op.m = MEDIUM;
68 #endif
69
70 int optget;
71 opterr = 0; /* don't print message on unrecognized option */
72 while ((optget = getopt (argc, argv, "+:hs:vbcmMV")) != -1) {
73 switch (optget) {
74 #ifdef SPIDER
75 case 's': /* number of suits */
76 switch (optarg[0]) {
77 case '1': op.m = EASY; break;
78 case '2': op.m = MEDIUM; break;
79 case '4': op.m = NORMAL; break;
80 default: goto error;
81 } break;
82 #endif
83 case 'b': op.s = &unicode_large_mono; break;
84 case 'c': op.s = &unicode_large_color; break;
85 case 'm': op.s = &unicode_small_mono; break; /* "mini, monochrome" */
86 case 'M': op.s = &unicode_small_color; break; /* "mini, colorful" */
87 case 'V': op.v = 0; break; /* WARN: experimental; might change */
88 case 'h': default: goto error;
89 error:
90 fprintf (stderr, SHORTHELP LONGHELP KEYHELP, argv[0]);
91 return optget != 'h';
92 }
93 }
94
95 signal_setup();
96 atexit (*quit);
97
98 signal_handler(SIGWINCH); /* initialize window size */
99
100 newgame:
101 screen_setup(1);
102
103 switch(sol()) {
104 case GAME_NEW: goto newgame;
105 case GAME_WON:
106 print_table(NO_HI, NO_HI);
107 win_anim();
108 if (getch(NULL)=='q') return 0;
109 goto newgame;
110 case GAME_QUIT: return 0;
111 }
112 }
113
114 #define is_tableu(where) (where <= TAB_MAX) // "card games helper functions"
115
116 int sol(void) {
117 int ret;
118 long seed = time(NULL);
119 restart:
120 free_undo(f.u);
121 deal(seed);
122
123 int from, to, opt;
124 for(;;) {
125 switch (get_cmd(&from, &to, &opt)) {
126 case CMD_MOVE:
127 ret = action[from][to](from,to,opt);
128 #ifdef FREECELL
129 if (ret == ERR && is_tableu(from) && to == from)
130 /* t2f failed? try t2c! */
131 ret = t2c(from, STOCK, 0);
132 else
133 #endif
134 if (ret == ERR && is_tableu(from) && is_tableu(to))
135 /* try again with from/to swapped: */
136 ret = action[to][from](to,from,opt);
137 switch (ret) {
138 case OK: break;
139 case ERR: visbell(); break;
140 case WON: return GAME_WON;
141 }
142 break;
143 case CMD_JOIN:
144 switch (join(to)) {
145 case OK: break;
146 case ERR: visbell(); break;
147 case WON: return GAME_WON;
148 }
149 break;
150 case CMD_HINT: break;//TODO: show a possible (and sensible) move. if possible, involve active cursor
151 case CMD_UNDO: undo_pop(f.u); break;
152 case CMD_INVAL: visbell(); break;
153 case CMD_NEW: return GAME_NEW;
154 case CMD_AGAIN: goto restart;
155 case CMD_QUIT: return GAME_QUIT;
156 case CMD_HELP:
157 printf (KEYHELP "\nPress any key to continue.");
158 getch(NULL);
159 break;
160 }
161 }
162 }
163
164 void quit(void) {
165 screen_setup(0);
166 free_undo(f.u);
167 }
168 //}}}
169
170 // card games helper functions {{{
171 #define get_suit(card) \
172 ((card-1) % NUM_SUITS)
173 #define get_rank(card) \
174 ((card-1) / NUM_SUITS)
175 #define get_color(card) \
176 ((get_suit(card) ^ get_suit(card)>>1) & 1)
177
178 int find_top(card_t* pile) {
179 int i;
180 for(i=PILE_SIZE-1; i>=0 && !pile[i]; i--);
181 return i;
182 }
183 int first_movable(card_t* pile) {
184 /* NOTE: in FREECELL this does not take max_move into account! */
185 int i = 0;
186 for (;pile[i] && !is_movable(pile, i); i++);
187 return i;
188 }
189 int turn_over(card_t* pile) {
190 int top = find_top(pile);
191 if (pile[top] < 0) {
192 pile[top] *= -1;
193 return 1;
194 } else return 0;
195 }
196 int check_won(void) {
197 for (int pile = 0; pile < NUM_DECKS*NUM_SUITS; pile++)
198 if (f.f[pile][NUM_RANKS-1] == NO_CARD) return 0;
199
200 return 1;
201 }
202 int rank_next (card_t a, card_t b) {
203 return get_rank(a) == get_rank(b)-1;
204 }
205 int is_consecutive (card_t* pile, int pos) {
206 if (pos+1 >= PILE_SIZE) return 1; /* card is last */
207 if (pile[pos+1] == NO_CARD) return 1; /* card is first */
208
209 #if defined KLONDIKE || defined FREECELL
210 /* ranks consecutive? */
211 if (!rank_next(pile[pos+1], pile[pos])) return 0;
212 /* color opposite? */
213 if (get_color(pile[pos+1]) == get_color(pile[pos])) return 0;
214 #elif defined SPIDER
215 /* ranks consecutive? */
216 if (!rank_next(pile[pos+1], pile[pos])) return 0;
217 /* same suit? */
218 if (get_suit(pile[pos+1]) != get_suit(pile[pos])) return 0;
219 #endif
220
221 return 1;
222 }
223
224 int is_movable(card_t* pile, int n) {
225 #ifdef KLONDIKE
226 return(pile[n] > NO_CARD); /*non-movable cards don't exist in klondike*/
227 #elif defined SPIDER || defined FREECELL
228 int top = find_top(pile);
229 for (int i = top; i >= 0; i--) {
230 if (pile[i] <= NO_CARD) return 0; /*no card or card face down?*/
231 if (!is_consecutive(pile, i)) return 0;
232 if (i == n) return 1; /* card reached, must be movable */
233 }
234 return 0;
235 #endif
236 }
237 //}}}
238
239 // takeable actions {{{
240 #ifdef KLONDIKE
241 card_t stack_take(void) { /*NOTE: assert(f.w >= 0) */
242 card_t card = f.s[f.w];
243 /* move stack one over, so there are no gaps in it: */
244 for (int i = f.w; i < f.z-1; i++)
245 f.s[i] = f.s[i+1];
246 f.z--;
247 f.w--; /* make previous card visible again */
248 return card;
249 }
250 int t2f(int from, int to, int opt) { /* tableu to foundation */
251 (void) to; (void) opt; /* don't need */
252 int top_from = find_top(f.t[from]);
253 to = get_suit(f.t[from][top_from]);
254 int top_to = find_top(f.f[to]);
255 if ((top_to < 0 && get_rank(f.t[from][top_from]) == RANK_A)
256 || (top_to >= 0 && rank_next(f.f[to][top_to],f.t[from][top_from]))) {
257 f.f[to][top_to+1] = f.t[from][top_from];
258 f.t[from][top_from] = NO_CARD;
259 undo_push(from, FOUNDATION, to,
260 turn_over(f.t[from]));
261 if (check_won()) return WON;
262 return OK;
263 } else return ERR;
264 }
265 int w2f(int from, int to, int opt) { /* waste to foundation */
266 (void) from; (void) to; (void) opt; /* don't need */
267 if (f.w < 0) return ERR;
268 to = get_suit(f.s[f.w]);
269 int top_to = find_top(f.f[to]);
270 if ((top_to < 0 && get_rank(f.s[f.w]) == RANK_A)
271 || (top_to >= 0 && rank_next(f.f[to][top_to], f.s[f.w]))) {
272 undo_push(WASTE, FOUNDATION, f.w | to<<16, 0);//ugly encoding :|
273 f.f[to][top_to+1] = stack_take();
274 if (check_won()) return WON;
275 return OK;
276 } else return ERR;
277
278 }
279 int s2w(int from, int to, int opt) { /* stock to waste */
280 (void) from; (void) to; (void) opt; /* don't need */
281 if (f.z == 0) return ERR;
282 f.w++;
283 if (f.w == f.z) f.w = -1;
284 return OK;
285 }
286 int w2s(int from, int to, int opt) { /* waste to stock (undo stock to waste) */
287 (void) from; (void) to; (void) opt; /* don't need */
288 if (f.z == 0) return ERR;
289 f.w--;
290 if (f.w < -1) f.w = f.z-1;
291 return OK;
292 }
293 int f2t(int from, int to, int opt) { /* foundation to tableu */
294 (void) from; /* don't need */
295 int top_to = find_top(f.t[to]);
296 from = opt;
297 int top_from = find_top(f.f[from]);
298
299 if ((get_color(f.t[to][top_to]) != get_color(f.f[from][top_from]))
300 && (rank_next(f.f[from][top_from], f.t[to][top_to]))) {
301 f.t[to][top_to+1] = f.f[from][top_from];
302 f.f[from][top_from] = NO_CARD;
303 undo_push(FOUNDATION, to, from, 0);
304 return OK;
305 } else return ERR;
306 }
307 int w2t(int from, int to, int opt) { /* waste to tableu */
308 (void) from; (void) opt; /* don't need */
309 if (f.w < 0) return ERR;
310 int top_to = find_top(f.t[to]);
311 if (((get_color(f.t[to][top_to]) != get_color(f.s[f.w]))
312 && (rank_next(f.s[f.w], f.t[to][top_to])))
313 || (top_to < 0 && get_rank(f.s[f.w]) == RANK_K)) {
314 undo_push(WASTE, to, f.w, 0);
315 f.t[to][top_to+1] = stack_take();
316 return OK;
317 } else return ERR;
318 }
319 int t2t(int from, int to, int opt) { /* tableu to tableu */
320 (void) opt; /* don't need */
321 int top_to = find_top(f.t[to]);
322 int top_from = find_top(f.t[from]);
323 int count = 0; //NOTE: could probably be factored out
324 for (int i = top_from; i >=0; i--) {
325 if (((get_color(f.t[to][top_to]) != get_color(f.t[from][i]))
326 && (rank_next(f.t[from][i], f.t[to][top_to]))
327 && f.t[from][i] > NO_CARD) /* card face up? */
328 || (top_to < 0 && get_rank(f.t[from][i]) == RANK_K)) {
329 /* move cards [i..top_from] to their destination */
330 for (;i <= top_from; i++) {
331 top_to++;
332 f.t[to][top_to] = f.t[from][i];
333 f.t[from][i] = NO_CARD;
334 count++;
335 }
336 undo_push(from, to, count,
337 turn_over(f.t[from]));
338 return OK;
339 }
340 }
341 return ERR; /* no such move possible */
342 }
343 #elif defined SPIDER
344 int remove_if_complete (int pileno) { //cleanup!
345 card_t* pile = f.t[pileno];
346 /* test if K...A complete; move to foundation if so */
347 int top_from = find_top(pile);
348 if (get_rank(pile[top_from]) != RANK_A) return 0;
349 for (int i = top_from; i>=0; i--) {
350 if (!is_consecutive (pile, i)) return 0;
351 if (i+RANK_K == top_from /* if ace to king: remove it */
352 && get_rank(pile[top_from-RANK_K]) == RANK_K) {
353 for(int i=top_from, j=0; i>top_from-NUM_RANKS; i--,j++){
354 f.f[f.w][j] = pile[i];
355 pile[i] = NO_CARD;
356 }
357 undo_push(pileno, FOUNDATION, f.w,
358 turn_over(pile));
359 f.w++;
360 return 1;
361 }
362 }
363
364 return 0;
365 }
366 int t2t(int from, int to, int opt) { //in dire need of cleanup
367 int top_from = find_top(f.t[from]);
368 int top_to = find_top(f.t[to]);
369 int empty_to = (top_to < 0)? opt: -1; /* empty pile? */
370 int count = 0; //NOTE: could probably be factored out
371
372 for (int i = top_from; i >= 0; i--) {
373 if (!is_consecutive(f.t[from], i)) break;
374
375 /* is consecutive OR to empty pile and rank ok? */
376 if (rank_next(f.t[from][i], f.t[to][top_to])
377 || (empty_to >= RANK_A && get_rank(f.t[from][i]) == empty_to)) {
378 for (;i <= top_from; i++) {
379 top_to++;
380 f.t[to][top_to] = f.t[from][i];
381 f.t[from][i] = NO_CARD;
382 count++;
383 }
384 undo_push(from, to, count,
385 turn_over(f.t[from]));
386 remove_if_complete(to);
387 if (check_won()) return WON;
388 return OK;
389 }
390 }
391
392 return ERR; /* no such move possible */
393 }
394 int s2t(int from, int to, int opt) {
395 (void) from; (void) to; (void) opt; /* don't need */
396 if (f.z <= 0) return ERR; /* stack out of cards */
397 for (int pile = 0; pile < NUM_PILES; pile++)
398 if (f.t[pile][0]==NO_CARD) return ERR; /*no piles may be empty*/
399 for (int pile = 0; pile < NUM_PILES; pile++) {
400 f.t[pile][find_top(f.t[pile])+1] = f.s[--f.z];
401 remove_if_complete(pile);
402 if (check_won()) return WON;
403 }
404 undo_push(STOCK, TABLEU, 1, 0);/*NOTE: puts 1 card on each tableu pile*/
405 return OK;
406 }
407 int t2f(int from, int to, int opt) {
408 (void) to; (void) opt; /* don't need */
409 /* manually retrigger remove_if_complete() (e.g. after undo_pop) */
410 return remove_if_complete(from)?OK:ERR;
411 }
412 #elif defined FREECELL
413 int max_move(int from, int to) {
414 /* returns the maximum number of cards that can be moved */
415 /* see also: https://boardgames.stackexchange.com/a/45157/26498 */
416 int free_tabs = 0, free_cells = 0;
417 for (int i = 0; i < NUM_PILES; i++) free_tabs += f.t[i][0] == NO_CARD;
418 for (int i = 0; i < NUM_CELLS; i++) free_cells += f.s[i] == NO_CARD;
419
420 /* don't count the tableau we are moving to: */
421 if (to >= 0 && f.t[to][0] == NO_CARD) free_tabs--;
422
423 /* theoretic maximum is limited by the number of cards on the pile */
424 int max_theory = (1<<free_tabs) * (free_cells + 1);
425 int max_effective = 1 + find_top(f.t[from]) - first_movable(f.t[from]);
426 return max_effective < max_theory? max_effective : max_theory;
427 }
428 //TODO FREECELL: auto move to tableu after each move (not all cards possible, only when it is the smallest rank still on the board)
429 int t2t(int from, int to, int opt) {
430 int top_to = find_top(f.t[to]);
431 int top_from = find_top(f.t[from]);
432 int count = 0; //NOTE: could probably be factored out
433 int cards = max_move(from, to);
434 if (top_to < 0) { /* moving to empty pile? */
435 if (opt > cards)
436 return ERR; /* cannot execute move */
437 cards = opt; /* user wants to move n cards*/
438 }
439
440 for (int i = top_from; i >=0; i--) {
441 if (cards-->0/*enough space and not more attempted than wanted*/
442 && ((top_to >= 0 /* if destn. not empty: check rank/color */
443 && ((get_color(f.t[to][top_to]) != get_color(f.t[from][i]))
444 && (rank_next(f.t[from][i], f.t[to][top_to]))))
445 || (top_to < 0 && !cards))) {/*if dest empty and right # cards*/
446 /* move cards [i..top_from] to their destination */
447 for (;i <= top_from; i++) {
448 top_to++;
449 f.t[to][top_to] = f.t[from][i];
450 f.t[from][i] = NO_CARD;
451 count++;
452 }
453 undo_push(from, to, count, 0);
454 return OK;
455 }
456 }
457 return ERR; /* no such move possible */
458 }
459 int t2f(int from, int to, int opt) { /* 1:1 copy from KLONDIKE */
460 (void) to; (void) opt; /* don't need */
461 int top_from = find_top(f.t[from]);
462 to = get_suit(f.t[from][top_from]);
463 int top_to = find_top(f.f[to]);
464 if ((top_to < 0 && get_rank(f.t[from][top_from]) == RANK_A)
465 || (top_to >= 0 && rank_next(f.f[to][top_to],f.t[from][top_from]))) {
466 f.f[to][top_to+1] = f.t[from][top_from];
467 f.t[from][top_from] = NO_CARD;
468 undo_push(from, FOUNDATION, to, 0);
469 if (check_won()) return WON;
470 return OK;
471 } else return ERR;
472 }
473 int f2t(int from, int to, int opt) {
474 (void) from; /* don't need */
475 int top_to = find_top(f.t[to]);
476 from = opt;
477 int top_from = find_top(f.f[from]);
478
479 if (top_to < 0 /* empty tableu? */
480 ||((get_color(f.t[to][top_to]) != get_color(f.f[from][top_from]))
481 && (rank_next(f.f[from][top_from], f.t[to][top_to])))) {
482 f.t[to][top_to+1] = f.f[from][top_from];
483 f.f[from][top_from] = NO_CARD;
484 undo_push(FOUNDATION, to, from, 0);
485 return OK;
486 } else return ERR;
487 }
488 int t2c(int from, int to, int opt) {
489 (void) to; (void) opt; /* don't need */
490 /* is a cell free? */
491 if (f.w == (1<<NUM_CELLS)-1)
492 return ERR;
493 for (to = 0; to < NUM_CELLS; to++)
494 if (!(f.w>>to&1)) break;
495 /* move 1 card */
496 int top_from = find_top(f.t[from]);
497 f.s[to] = f.t[from][top_from];
498 f.t[from][top_from] = NO_CARD;
499 f.w |= 1<<to; /* mark cell as occupied */
500 undo_push(from, STOCK, to, 0);
501
502 return OK;
503 }
504 int c2t(int from, int to, int opt) {
505 (void) from; /* don't need */
506 int top_to = find_top(f.t[to]);
507 from = opt;
508
509 if (top_to < 0 /* empty tableu? */
510 ||((get_color(f.t[to][top_to]) != get_color(f.s[from]))
511 && (rank_next(f.s[from], f.t[to][top_to])))) {
512 f.t[to][top_to+1] = f.s[from];
513 f.s[from] = NO_CARD;
514 f.w &= ~(1<<from); /* mark cell as free */
515 undo_push(STOCK, to, from, 0);
516 return OK;
517 } else return ERR;
518 return ERR;
519 }
520 int c2f(int from, int to, int opt) {
521 (void) from; (void) to; /* don't need */
522 from = opt;
523 to = get_suit(f.s[from]);
524 int top_to = find_top(f.f[to]);
525 if ((top_to < 0 && get_rank(f.s[from]) == RANK_A)
526 || (top_to >= 0 && rank_next(f.f[to][top_to],f.s[from]))) {
527 f.f[to][top_to+1] = f.s[from];
528 f.s[from] = NO_CARD;
529 f.w &= ~(1<<from); /* mark cell as free */
530 undo_push(STOCK, FOUNDATION, from | to<<16, 0);
531 if (check_won()) return WON;
532 return OK;
533 } else return ERR;
534 }
535 int f2c(int from, int to, int opt) {
536 (void) from; (void) to; /* don't need */
537 /* is a cell free? */
538 if (f.w == (1<<NUM_CELLS)-1)
539 return ERR;
540 for (to = 0; to < NUM_CELLS; to++)
541 if (!(f.w>>to&1)) break;
542 /* move 1 card */
543 from = opt;
544 int top_from = find_top(f.f[from]);
545 f.s[to] = f.f[from][top_from];
546 f.f[from][top_from] = NO_CARD;
547 f.w |= 1<<to; /* mark cell as occupied */
548 undo_push(FOUNDATION, STOCK, from | to<<16, 0);
549
550 return OK;
551 }
552 #endif
553
554 //TODO: generalize prediction engine for CMD_HINT
555 #ifdef KLONDIKE
556 #define would_complete(pile) 0
557 #elif defined SPIDER
558 #define would_complete(pile) \
559 (get_rank(f.t[pile][r[pile].top]) == RANK_A \
560 && get_rank(f.t[to][bottom_to]) == RANK_K)
561 #elif defined FREECELL
562 #define would_complete(pile) 0
563 #endif
564 #define would_turn(pile) \
565 (f.t[pile][r[pile].pos-1] < 0)
566 #define would_empty(pile) \
567 (r[pile].pos == 0)
568
569 int join(int to) {
570 //TODO FREECELL: join to empty tableu (longest cascade?)
571 int top_to = find_top(f.t[to]);
572 #ifdef SPIDER
573 int bottom_to = first_movable(f.t[to]);
574 #endif
575
576 #ifdef KLONDIKE
577 if (to == WASTE || to == STOCK) return ERR; /*why would you do that!?*/
578
579 if (to == FOUNDATION) {
580 int status = ERR;
581 for (int i = 0; i <= TAB_MAX; i++)
582 switch ((i?t2f:w2f)(i-1, FOUNDATION, 0)) {
583 case WON: return WON;
584 case OK: status = OK;
585 case ERR: /* nop */;
586 }
587 return status;
588 }
589
590 if (top_to < 0) { /* move a king to empty pile: */
591 for (int i = 0; i < TAB_MAX; i++) {
592 if (f.t[i][0] < 0) /* i.e. would turn? */
593 if (t2t(i, to, 0) == OK) return OK;
594 }
595 return w2t(WASTE, to, 0);
596 }
597 #endif
598
599 struct rating {
600 int ok:1; /* card to move in pile? */
601 int above; /* number of movable cards above */
602 int below; /* number of cards below ours */
603 int pos; /* where the card to move is in the pile */
604 int top; /* find_top() */
605 } r[NUM_PILES] = {{0}};
606 int complete = 0;/* SPIDER: true if any pile would complete a stack */
607 int turn = 0; /* SPIDER: true if any pile would turn_over */
608 int empty = 0; /* true if any pile would become empty */
609
610 /* 1. rate each pile: */
611 #ifdef SPIDER
612 if (top_to < 0) {
613 for (int pile = 0; pile < NUM_PILES; pile++) {
614 if (pile == to) continue;
615 int top = find_top(f.t[pile]);
616 int bottom = first_movable(f.t[pile]);
617 r[pile].pos = bottom; /* need for would_empty */
618
619 if (top < 0) continue; /* no cards to move */
620 if (would_empty(pile)) continue; /* doesn't help */
621
622 r[pile].ok++;
623 r[pile].above = 0; /* always take as many as possible */
624 r[pile].below = top - bottom;
625 r[pile].top = top;
626 complete |= would_complete(pile); /* never happens */
627 turn |= would_turn(pile);
628 empty |= would_empty(pile);
629 }
630 } else
631 #endif
632 for (int pile = 0; pile < NUM_PILES; pile++) {
633 r[pile].top = r[pile].pos = find_top(f.t[pile]);
634 /* backtrack until we find a compatible-to-'to'-pile card: */
635 #ifdef FREECELL
636 int maxmove = max_move(pile, -1);
637 #endif
638 while (r[pile].pos >= 0 && is_movable(f.t[pile], r[pile].pos)) {
639 int rankdiff = get_rank(f.t[pile][r[pile].pos])
640 - get_rank(f.t[to][top_to]);
641 if (rankdiff >= 0) break; /* past our card */
642 #ifdef FREECELL
643 if (!maxmove--) break; /* can't move this many cards */
644 #endif
645 if (rankdiff == -1 /* rank matches */
646 #if defined KLONDIKE || defined FREECELL
647 && get_color(f.t[pile][r[pile].pos]) /* color OK */
648 != get_color(f.t[to][top_to])
649 #elif defined SPIDER
650 && get_suit(f.t[pile][r[pile].pos]) /* color OK */
651 == get_suit(f.t[to][top_to])
652 #endif
653 ) {
654 r[pile].ok++;
655 complete |= would_complete(pile);
656 turn |= would_turn(pile);
657 empty |= would_empty(pile);
658 for (int i = r[pile].pos; i >= 0; i--)
659 if (is_movable(f.t[pile], i-1))
660 r[pile].above++;
661 else break;
662 break;
663 }
664 r[pile].pos--;
665 r[pile].below++;
666 }
667 }
668
669 /* 2. find optimal pile: (optimized for spider) */
670 //todo: in spider, prefer longest piles if above==0 (faster completions)
671 int from = -1;
672 for (int pile = 0, above = 99, below = 99; pile < NUM_PILES; pile++) {
673 if (!r[pile].ok) continue;
674 /* don't bother if another pile would be better: prefer ... */
675 /* ... to complete a stack: */
676 if (!would_complete(pile) && complete) continue;
677 /* ... emptying piles: */
678 if (!would_empty(pile) && empty && !complete) continue;
679 /* ... to turn_over: */
680 if (!would_turn(pile) && turn && !complete && !empty) continue;
681 /* ... not to rip apart too many cards: */
682 if (r[pile].above > above) continue;
683 /* if tied, prefer ... */
684 if (r[pile].above == above
685 /* ... larger pile if destination is empty */
686 && (top_to < 0? r[pile].below < below
687 /* ... shorter pile otherwise */
688 : r[pile].below > below))
689 continue;
690
691 from = pile;
692 above = r[pile].above;
693 below = r[pile].below;
694 }
695
696 /* 3. move cards over and return: */
697 #ifdef KLONDIKE
698 /* prefer waste if it wouldn't turn_over: */
699 /* NOTE: does not attempt to take from froundation */
700 if (!empty && !turn && w2t(WASTE, to, 0) == OK)
701 return OK;
702 if (from < 0) /* nothing found */
703 return ERR;
704 return t2t(from, to, 0);
705 #elif defined SPIDER
706 if (from < 0) /* nothing found */
707 return ERR;
708 int bottom = first_movable(f.t[from]);
709 return t2t(from, to, get_rank(f.t[from][bottom]));
710 #elif defined FREECELL
711 if (from < 0) /* no tableu move found */ {
712 /* try all free cells before giving up: */
713 for (int i = 0; i < NUM_CELLS; i++)
714 if (c2t(STOCK, to, i) == OK) return OK;
715 return ERR;
716 }
717 return t2t(from, to, 0);
718 #endif
719 }
720 #undef would_empty
721 #undef would_turn
722 #undef would_complete
723 int nop(int from, int to, int opt) { (void)from;(void)to;(void)opt;return ERR; }
724 // }}}
725
726 // keyboard input handling {{{
727 // cursor functions{{{
728 #ifdef KLONDIKE
729 void cursor_left (struct cursor* cursor) {
730 op.h = 1;
731 if (is_tableu(cursor->pile)) {
732 if (cursor->pile > 0) cursor->pile--;
733 cursor->opt = 0;
734 } else { /* stock/waste/foundation*/
735 switch (cursor->pile) {
736 case WASTE: cursor->pile = STOCK; cursor->opt = 0; break;
737 case FOUNDATION:
738 if (cursor->opt <= 0)
739 cursor->pile = WASTE;
740 else
741 cursor->opt--;
742 }
743 }
744 }
745 void cursor_down (struct cursor* cursor) {
746 op.h = 1;
747 if (!is_tableu(cursor->pile)) {
748 switch (cursor->pile) {
749 case STOCK: cursor->pile = TAB_1; break;
750 case WASTE: cursor->pile = TAB_2; break;
751 case FOUNDATION:
752 cursor->pile = TAB_4 + cursor->opt;
753 }
754 cursor->opt = 0;
755 }
756 }
757 void cursor_up (struct cursor* cursor) {
758 op.h = 1;
759 if (is_tableu(cursor->pile)) {
760 switch (cursor->pile) { //ugly :|
761 case TAB_1: cursor->pile = STOCK; break;
762 case TAB_2: cursor->pile = WASTE; break;
763 case TAB_3: cursor->pile = WASTE; break;
764 case TAB_4: case TAB_5: case TAB_6: case TAB_7:
765 cursor->opt=cursor->pile-TAB_4;
766 cursor->pile = FOUNDATION;
767 break;
768 }
769 }
770 }
771 void cursor_right (struct cursor* cursor) {
772 op.h = 1;
773 if (is_tableu(cursor->pile)) {
774 if (cursor->pile < TAB_MAX) cursor->pile++;
775 cursor->opt = 0;
776 } else {
777 switch (cursor->pile) {
778 case STOCK: cursor->pile = WASTE; break;
779 case WASTE: cursor->pile = FOUNDATION;cursor->opt = 0; break;
780 case FOUNDATION:
781 if (cursor->opt < NUM_SUITS-1)
782 cursor->opt++;
783 }
784 }
785 }
786 #elif defined SPIDER
787 /*NOTE: one can't highlight the stock due to me being too lazy to implement it*/
788 void cursor_left (struct cursor* cursor) {
789 op.h = 1;
790 if (cursor->pile > 0) cursor->pile--;
791 cursor->opt = 0;
792 }
793 void cursor_down (struct cursor* cursor) {
794 op.h = 1;
795 int first = first_movable(f.t[cursor->pile]);
796 int top = find_top(f.t[cursor->pile]);
797 if (first + cursor->opt < top)
798 cursor->opt++;
799 }
800 void cursor_up (struct cursor* cursor) {
801 op.h = 1;
802 if (cursor->opt > 0) cursor->opt--;
803 }
804 void cursor_right (struct cursor* cursor) {
805 op.h = 1;
806 if (cursor->pile < TAB_MAX) cursor->pile++;
807 cursor->opt = 0;
808 }
809 #elif defined FREECELL
810 void cursor_left (struct cursor* cursor) {
811 op.h = 1;
812 if (is_tableu(cursor->pile)) {
813 if (cursor->pile > 0) cursor->pile--;
814 cursor->opt = 0;
815 } else { /* cells/foundation*/
816 switch (cursor->pile) {
817 case STOCK:
818 if (cursor->opt > 0)
819 cursor->opt--;
820 break;
821 case FOUNDATION:
822 if (cursor->opt <= 0) {
823 cursor->pile = STOCK;
824 cursor->opt = 3;
825 } else {
826 cursor->opt--;
827 }
828 }
829 }
830 }
831 void cursor_down (struct cursor* cursor) {
832 op.h = 1;
833 if (is_tableu(cursor->pile)) {
834 if (cursor->opt < max_move(cursor->pile, -1)-1)
835 cursor->opt++;
836 } else {
837 cursor->pile = cursor->opt+NUM_CELLS*(cursor->pile==FOUNDATION);
838 cursor->opt = 0;
839 }
840 }
841 void cursor_up (struct cursor* cursor) {
842 op.h = 1;
843 if (is_tableu(cursor->pile)) {
844 if (cursor->opt > 0) {
845 cursor->opt--;
846 } else {
847 switch (cursor->pile) {
848 case TAB_1: case TAB_2: case TAB_3: case TAB_4:
849 cursor->opt = cursor->pile; /*assumes TAB_1==0*/
850 cursor->pile = STOCK;
851 break;
852 case TAB_5: case TAB_6: case TAB_7: case TAB_8:
853 cursor->opt = cursor->pile - NUM_CELLS;
854 cursor->pile = FOUNDATION;
855 }
856 }
857 }
858 }
859 void cursor_right (struct cursor* cursor) {
860 op.h = 1;
861 if (is_tableu(cursor->pile)) {
862 if (cursor->pile < TAB_MAX) cursor->pile++;
863 cursor->opt = 0;
864 } else {
865 switch (cursor->pile) {
866 case STOCK:
867 if (cursor->opt < NUM_SUITS-1) {
868 cursor->opt++;
869 } else {
870 cursor->pile = FOUNDATION;
871 cursor->opt = 0;
872 } break;
873 case FOUNDATION:
874 if (cursor->opt < NUM_SUITS-1)
875 cursor->opt++;
876 }
877 }
878 }
879 #endif
880 void cursor_to (struct cursor* cursor, int pile) {
881 op.h = 1;
882 cursor->pile = pile;
883 cursor->opt = 0;
884 }
885 int set_mouse(int pile, int* main, int* opt) {
886 //TODO: this should set cursor.opt, so card selector choice dialog does not trigger!
887 op.h = 0;
888 if (pile < 0) return 1;
889 *main = pile;
890 #ifdef KLONDIKE
891 if (pile >= FOUNDATION)//TODO: check upper bound!
892 *main = FOUNDATION,
893 *opt = pile - FOUNDATION;
894 #elif defined SPIDER
895 (void)opt;
896 #elif defined FREECELL
897 if (pile > TAB_MAX) {
898 *main = pile-STOCK < NUM_CELLS? STOCK : FOUNDATION;
899 *opt = (pile-STOCK) % 4;
900 }
901 #endif
902 return 0;
903 }
904 //}}}
905 int get_cmd (int* from, int* to, int* opt) {
906 int _f, t;
907 unsigned char mouse[6] = {0}; /* must clear [3]! */
908 struct cursor inactive = {-1,-1};
909 static struct cursor active = {0,0};
910 if (is_tableu(active.pile))
911 active.opt = 0;
912
913 /***/
914 from_l: print_table(&active, &inactive);
915 _f = getch(mouse);
916
917 switch (_f) {
918 /* direct addressing: */
919 case '1': *from = TAB_1; break;
920 case '2': *from = TAB_2; break;
921 case '3': *from = TAB_3; break;
922 case '4': *from = TAB_4; break;
923 case '5': *from = TAB_5; break;
924 case '6': *from = TAB_6; break;
925 case '7': *from = TAB_7; break;
926 #ifdef SPIDER
927 case '8': *from = TAB_8; break;
928 case '9': *from = TAB_9; break;
929 case '0': *from = TAB_10;break;
930 #elif defined FREECELL
931 case '8': *from = TAB_8; break;
932 case '9': *from = STOCK; break;
933 case '0': *from = FOUNDATION; break;
934 #elif defined KLONDIKE
935 case '9': *from = WASTE; break;
936 case '0': *from = FOUNDATION; break;
937 case '8': /* fallthrough */
938 #endif
939 #ifndef FREECELL
940 case '\n': *from = STOCK; break;
941 #endif
942 /* cursor keys addressing: */
943 case KEY_LEFT:
944 case 'h': cursor_left (&active); goto from_l;
945 case KEY_DOWN:
946 case 'j': cursor_down (&active); goto from_l;
947 case KEY_UP:
948 case 'k': cursor_up (&active); goto from_l;
949 case KEY_RIGHT:
950 case 'l': cursor_right(&active); goto from_l;
951 case KEY_HOME:
952 case 'H': cursor_to(&active,TAB_1); goto from_l; /* leftmost tableu */
953 case KEY_END:
954 case 'L': cursor_to(&active,TAB_MAX);goto from_l; /* rigthmost tableu */
955 case KEY_INS:
956 case 'M': cursor_to(&active,TAB_MAX/2); goto from_l; /* center tableu */
957 case ' ': /* continue with second cursor */
958 *from = active.pile;
959 #ifdef KLONDIKE
960 *opt = active.opt; /* when FOUNDATION */
961 #endif
962 inactive = active;
963 break;
964 /* mouse addressing: */
965 case MOUSE_MIDDLE: return CMD_NONE;
966 case MOUSE_RIGHT:
967 if (set_mouse(term2pile(mouse), to, opt))
968 return CMD_INVAL;
969 goto join_l;
970 case MOUSE_LEFT:
971 if (set_mouse(term2pile(mouse), from, opt))
972 return CMD_INVAL;
973 if (!is_tableu(*from))
974 inactive.opt = *opt; /* prevents card selector dialog */
975 break;
976 /* misc keys: */
977 case ':':
978 {char buf[256];
979 fprintf (stderr, ":");
980 raw_mode(0); /* turn on echo */
981 fgets (buf, 256, stdin);
982 raw_mode(1);
983 switch(buf[0]) {
984 case 'q': return CMD_QUIT;
985 case 'n': return CMD_NEW;
986 case 'r': return CMD_AGAIN;
987 case 'h': return CMD_HELP;
988 default: return CMD_INVAL;
989 }}
990 case 'J':
991 *to = active.pile;
992 join_l:
993 #ifdef KLONDIKE
994 if (*to == FOUNDATION) return CMD_JOIN;
995 #endif
996 if (*to > TAB_MAX) return CMD_INVAL;
997 return CMD_JOIN;
998 case 'K': /* fallthrough */
999 case '?': return CMD_HINT;
1000 case 'u': return CMD_UNDO;
1001 case 002: return CMD_NONE; /* sent by SIGWINCH */
1002 case EOF: return CMD_NONE; /* sent by SIGCONT */
1003 default: return CMD_INVAL;
1004 }
1005 inactive.pile = *from; /* for direct addressing highlighting */
1006 if (is_tableu(*from) && f.t[*from][0] == NO_CARD) return CMD_INVAL;
1007
1008 #ifndef FREECELL
1009 if (*from == STOCK) {
1010 *to = WASTE;
1011 return CMD_MOVE;
1012 }
1013 #endif
1014
1015 /***/
1016 to_l: print_table(&active, &inactive);
1017 t = getch(mouse);
1018
1019 switch (t) {
1020 case KEY_LEFT:
1021 case 'h': cursor_left (&active); goto to_l;
1022 case KEY_DOWN:
1023 case 'j': cursor_down (&active); goto to_l;
1024 case KEY_UP:
1025 case 'k': cursor_up (&active); goto to_l;
1026 case KEY_RIGHT:
1027 case 'l': cursor_right(&active); goto to_l;
1028 case KEY_HOME:
1029 case 'H': cursor_to(&active,TAB_1); goto to_l;
1030 case KEY_END:
1031 case 'L': cursor_to(&active,TAB_MAX); goto to_l;
1032 case KEY_INS:
1033 case 'M': cursor_to(&active,TAB_MAX/2); goto to_l;
1034 case 'J': /* fallthrough; just join selected pile */
1035 case ' ':
1036 *to = active.pile;
1037 break; /* continues with the foundation/empty tableu check */
1038 case MOUSE_MIDDLE:
1039 case MOUSE_RIGHT: return CMD_NONE;
1040 case MOUSE_LEFT:
1041 if (set_mouse(term2pile(mouse), to, opt))
1042 return CMD_INVAL;
1043 /*#ifdef SPIDER
1044 //TODO: set opt if to field is empty; suppress "up do" dialog from below
1045 if (is_tableu(*to) && f.t[*to][0] == NO_CARD) {
1046 int top = find_top(f.t[*from]);
1047 if (top < 0) return CMD_INVAL;
1048 if (top >= 0 && !is_movable(f.t[*from], top-1)) {
1049 *opt = get_rank(f.t[*from][top]);
1050 } else {
1051 // ask user
1052 }
1053 }
1054 #endif*/
1055 break;
1056 case 'K': /* fallthrough */
1057 case '?': return CMD_HINT;
1058 case 'u': return CMD_NONE; /* cancel selection */
1059 case EOF: return CMD_NONE; /* sent by SIGCONT */
1060 default:
1061 if (t < '0' || t > '9') return CMD_INVAL;
1062 if (t == '0')
1063 #ifdef KLONDIKE
1064 *to = FOUNDATION;
1065 #elif defined SPIDER
1066 *to = TAB_10;
1067 #elif defined FREECELL
1068 *to = FOUNDATION;
1069 else if (t == '9')
1070 *to = STOCK;
1071 #endif
1072 else
1073 *to = t-'1';
1074 }
1075
1076 /***/
1077 #ifdef KLONDIKE
1078 if (*from == FOUNDATION) {
1079 if (inactive.opt >= 0) {
1080 *opt = inactive.opt;
1081 return CMD_MOVE;
1082 }
1083 int top = find_top(f.t[*to]);
1084 if (top < 0) return CMD_INVAL;
1085 int color = get_color(f.t[*to][top]);
1086 int choice_1 = 1-color; /* selects piles of */
1087 int choice_2 = 2+color; /* the opposite color */
1088 int top_c1 = find_top(f.f[choice_1]);
1089 int top_c2 = find_top(f.f[choice_2]);
1090
1091 switch ((rank_next(f.f[choice_1][top_c1], f.t[*to][top])
1092 && top_c1 >= 0 ) << 0
1093 |(rank_next(f.f[choice_2][top_c2], f.t[*to][top])
1094 && top_c2 >= 0 ) << 1) {
1095 case ( 1<<0): *opt = choice_1; break; /* choice_1 only */
1096 case (1<<1 ): *opt = choice_2; break; /* choice_2 only */
1097 case (1<<1 | 1<<0): /* both, ask user which to pick from */
1098 printf ("take from (1-4): "); fflush (stdout);
1099 *opt = getch(NULL) - '1';
1100 if (*opt < 0 || *opt > 3) return CMD_INVAL;
1101 break;
1102 default: return CMD_INVAL; /* none matched */
1103 }
1104 /* `opt` is the foundation index (0..3) */
1105 }
1106 #elif defined SPIDER
1107 /* moving to empty tableu? */
1108 if (is_tableu(*to) && f.t[*to][0] == NO_CARD) {
1109 int bottom = first_movable(f.t[*from]);
1110 if (inactive.opt >= 0) { /*if from was cursor addressed: */
1111 *opt = get_rank(f.t[*from][bottom + inactive.opt]);
1112 return CMD_MOVE;
1113 }
1114 int top = find_top(f.t[*from]);
1115 if (top < 0) return CMD_INVAL;
1116 if (top >= 0 && !is_movable(f.t[*from], top-1)) {
1117 *opt = get_rank(f.t[*from][top]);
1118 } else { /* only ask the user if it's unclear: */
1119 printf ("\rup to ([a23456789xjqk] or space/return): ");
1120 *opt = getch(NULL);
1121 switch (*opt) {
1122 case ' ': *opt = get_rank(f.t[*from][top]); break;
1123 case'\n': *opt = get_rank(f.t[*from][bottom]); break;
1124 case 'a': case 'A': *opt = RANK_A; break;
1125 case '0': /* fallthrough */
1126 case 'x': case 'X': *opt = RANK_X; break;
1127 case 'j': case 'J': *opt = RANK_J; break;
1128 case 'q': case 'Q': *opt = RANK_Q; break;
1129 case 'k': case 'K': *opt = RANK_K; break;
1130 default: *opt -= '1';
1131 }
1132 if (*opt < RANK_A || *opt > RANK_K) return CMD_INVAL;
1133 }
1134 /* `opt` is the rank of the highest card to move */
1135 }
1136 #elif defined FREECELL
1137 /* if it was selected with a cursor, it's obvious: */
1138 if (inactive.opt >= 0) {
1139 if (is_tableu(*from)) {
1140 /* NOTE: max_move same as in cursor_down() */
1141 *opt = max_move(*from, -1) - inactive.opt;
1142 } else {
1143 *opt = inactive.opt;
1144 }
1145 /* moving from tableu to empty tableu? */
1146 } else if(is_tableu(*from) && is_tableu(*to) && f.t[*to][0] == NO_CARD){
1147 int top = find_top(f.t[*from]);
1148 int max = max_move(*from, *to);
1149 int rank;
1150 if (top < 0) return CMD_INVAL;
1151 if (max == 1) { /* only 1 movable? */
1152 return *opt = 1, CMD_MOVE;
1153 } else { /* only ask the user if it's unclear: */
1154 int bottom = top - (max-1);
1155 printf ("\rup to ([a23456789xjqk] or space/return): ");
1156 rank = getch(NULL);
1157 switch (rank) {
1158 case ' ': rank = get_rank(f.t[*from][top]); break;
1159 case'\n': rank = get_rank(f.t[*from][bottom]); break;
1160 case 'a': case 'A': rank = RANK_A; break;
1161 case '0': /* fallthrough */
1162 case 'x': case 'X': rank = RANK_X; break;
1163 case 'j': case 'J': rank = RANK_J; break;
1164 case 'q': case 'Q': rank = RANK_Q; break;
1165 case 'k': case 'K': rank = RANK_K; break;
1166 default: rank -= '1';
1167 }
1168 if (rank < RANK_A || rank > RANK_K) return CMD_INVAL;
1169
1170 for (int i = 0; max--; i++)
1171 if (get_rank(f.t[*from][top-i]) == rank)
1172 return *opt = 1+i, CMD_MOVE;
1173
1174 return CMD_INVAL;
1175 }
1176 /* `opt` is the number of cards to move */
1177 /* moving between stock/foundation? */
1178 } else if (*from == FOUNDATION && *to == FOUNDATION) {
1179 return CMD_INVAL; /* nonsensical */
1180 } else if (*from == FOUNDATION && *to == STOCK) {
1181 //can take from all non-empty foundations
1182 if (f.w == (1<<NUM_CELLS)-1) return CMD_INVAL; /*no free cells*/
1183 int ok_foundation; /* find compatible foundations: */
1184 int used_fs=0; for (int i = 0; i < NUM_SUITS; i++)
1185 if (!!f.f[i][0]) ok_foundation = i, used_fs++;
1186
1187 if (used_fs == 0) return CMD_INVAL; /* nowhere to take from */
1188 if (used_fs == 1) { /* take from the only one */
1189 return *opt = ok_foundation, CMD_MOVE;
1190 } else { /* ask user */
1191 printf ("take from (1-4): "); fflush (stdout);
1192 *opt = getch(NULL) - '1';
1193 if (*opt < 0 || *opt > 3) return CMD_INVAL;
1194 }
1195 /* `opt` is the foundation index (0..3) */
1196 } else if (*from == STOCK && !is_tableu(*to)) { /* cell -> foundation */
1197 //check all non-empty cells
1198 if (!f.w) return CMD_INVAL; /* no cell to take from */
1199 int ok_cell; /* find compatible cells: */
1200 int used_cs=0; for (int i = 0; i < NUM_CELLS; i++) {
1201 int to = get_suit(f.s[i]);
1202 int top_to = find_top(f.f[to]);
1203 if ((top_to<0 && get_rank(f.s[i]) == RANK_A)
1204 || (top_to>=0 && rank_next(f.f[to][top_to], f.s[i])))
1205 ok_cell = i, used_cs++;
1206 }
1207
1208 if (used_cs == 0) return CMD_INVAL; /* nowhere to take from */
1209 if (used_cs == 1) { /* take from the only one */
1210 return *opt = ok_cell, CMD_MOVE;
1211 } else { /* ask user */
1212 printf ("take from (1-4): "); fflush (stdout);
1213 *opt = getch(NULL) - '1';
1214 if (*opt < 0 || *opt > 3) return CMD_INVAL;
1215 }
1216 /* `opt` is the cell index (0..3) */
1217 } else if (*from == FOUNDATION || *from == STOCK) { /* -> tableu */
1218 //foundation: 2 choices
1219 //stock: 4 choices
1220 //TODO FREECELL: foundation/freecells -> tableu card selector dialog
1221
1222 printf ("take from (1-4): "); fflush (stdout);
1223 *opt = getch(NULL) - '1';
1224 if (*opt < 0 || *opt > 3) return CMD_INVAL;
1225 }
1226 #endif
1227 return CMD_MOVE;
1228 }
1229
1230 int getctrlseq(unsigned char* buf) {
1231 int c;
1232 enum esc_states {
1233 START,
1234 ESC_SENT,
1235 CSI_SENT,
1236 MOUSE_EVENT,
1237 } state = START;
1238 int offset = 0x20; /* never sends control chars as data */
1239 while ((c = getchar()) != EOF) {
1240 switch (state) {
1241 case START:
1242 switch (c) {
1243 case '\033': state=ESC_SENT; break;
1244 default: return c;
1245 }
1246 break;
1247 case ESC_SENT:
1248 switch (c) {
1249 case '[': state=CSI_SENT; break;
1250 default: return KEY_INVAL;
1251 }
1252 break;
1253 case CSI_SENT:
1254 switch (c) {
1255 case 'A': return KEY_UP;
1256 case 'B': return KEY_DOWN;
1257 case 'C': return KEY_RIGHT;
1258 case 'D': return KEY_LEFT;
1259 /*NOTE: home/end send ^[[x~ . no support for modifiers*/
1260 case 'H': return KEY_HOME;
1261 case 'F': return KEY_END;
1262 case '2': getchar(); return KEY_INS;
1263 case '5': getchar(); return KEY_PGUP;
1264 case '6': getchar(); return KEY_PGDN;
1265 case 'M': state=MOUSE_EVENT; break;
1266 default: return KEY_INVAL;
1267 }
1268 break;
1269 case MOUSE_EVENT:
1270 if (buf == NULL) return KEY_INVAL;
1271 buf[0] = c - offset;
1272 buf[1] = getchar() - offset;
1273 buf[2] = getchar() - offset;
1274 return MOUSE_ANY;
1275 default:
1276 return KEY_INVAL;
1277 }
1278 }
1279 return 2;
1280 }
1281 int term2pile(unsigned char *mouse) {
1282 int line = (mouse[2]-1);
1283 int column = (mouse[1]-1) / op.s->width;
1284
1285 if (line < op.s->height) { /* first line */
1286 #ifdef KLONDIKE
1287 switch (column) {
1288 case 0: return STOCK;
1289 case 1: return WASTE;
1290 case 2: return -1; /* spacer */
1291 case 3: return FOUNDATION+0;
1292 case 4: return FOUNDATION+1;
1293 case 5: return FOUNDATION+2;
1294 case 6: return FOUNDATION+3;
1295 }
1296 #elif defined SPIDER
1297 if (column < 3) return STOCK;
1298 return -1;
1299 #elif defined FREECELL
1300 if (column < NUM_SUITS + NUM_CELLS) return STOCK+column;
1301 return -1;
1302 #endif
1303 } else if (line > op.s->height) { /* tableu */
1304 if (column <= TAB_MAX) return column;
1305 }
1306 return -1;
1307 }
1308 int wait_mouse_up(unsigned char* mouse) {
1309 //TODO: mouse drag: start gets inactive, hovering gets active cursors
1310 struct cursor cur = {-1,-1};
1311 int level = 1;
1312 /* note: if dragged [3]==1 and second position is in mouse[0,4,5] */
1313
1314 /* display a cursor while mouse button is pushed: */
1315 int pile = term2pile(mouse);
1316 cur.pile = pile;
1317 #ifdef KLONDIKE
1318 if (pile >= FOUNDATION) {
1319 cur.pile = FOUNDATION;
1320 cur.opt = pile-FOUNDATION;
1321 }
1322 #elif defined FREECELL
1323 if (pile > TAB_MAX) {
1324 cur.pile = pile-STOCK < NUM_CELLS? STOCK : FOUNDATION;
1325 cur.opt = (pile-STOCK) % 4;
1326 }
1327 #endif
1328 /* need to temporarily show the cursor, then revert to last state: */
1329 int old_show_cursor_hi = op.h; //TODO: ARGH! that's awful!
1330 op.h = 1;
1331 print_table(&cur, NO_HI); //TODO: should not overwrite inactive cursor!
1332 op.h = old_show_cursor_hi;
1333
1334 while (level > 0) {
1335 if (getctrlseq (mouse+3) == MOUSE_ANY) {
1336 /* ignore mouse wheel events: */
1337 if (mouse[3] & 0x40) continue;
1338
1339 else if((mouse[3]&3) == 3) level--; /* release event */
1340 else level++; /* another button pressed */
1341 }
1342 }
1343
1344 int success = mouse[1] == mouse[4] && mouse[2] == mouse[5];
1345 if (success) {
1346 mouse[3] = 0;
1347 }
1348 return success;
1349 }
1350
1351 int getch(unsigned char* buf) {
1352 //TODO: if buf==NULL disable mouse input
1353 /* returns a character, EOF, or constant for an escape/control sequence - NOT
1354 compatible with the ncurses implementation of same name */
1355 int action;
1356 if (buf && buf[3]) {
1357 /* mouse was dragged; return 'ungetted' previous destination */
1358 action = MOUSE_DRAG;
1359 /* keep original [0], as [3] only contains release event */
1360 buf[1] = buf[4];
1361 buf[2] = buf[5];
1362 buf[3] = 0;
1363 } else {
1364 action = getctrlseq(buf);
1365 }
1366
1367 switch (action) {
1368 case MOUSE_ANY:
1369 if (buf[0] > 3) break; /* ignore wheel events */
1370 wait_mouse_up(buf);
1371 /* fallthrough */
1372 case MOUSE_DRAG:
1373 switch (buf[0]) {
1374 case 0: return MOUSE_LEFT;
1375 case 1: return MOUSE_MIDDLE;
1376 case 2: return MOUSE_RIGHT;
1377 }
1378 }
1379
1380 return action;
1381 }
1382 // }}}
1383
1384 // shuffling and dealing {{{
1385 void deal(long seed) {
1386 f = (const struct playfield){0}; /* clear playfield */
1387 card_t deck[DECK_SIZE*NUM_DECKS];
1388 int avail = DECK_SIZE*NUM_DECKS;
1389 for (int i = 0; i < DECK_SIZE*NUM_DECKS; i++) deck[i] = (i%DECK_SIZE)+1;
1390 #ifdef SPIDER
1391 if (op.m != NORMAL) for (int i = 0; i < DECK_SIZE*NUM_DECKS; i++) {
1392 if (op.m == MEDIUM) deck[i] = 1+((deck[i]-1) | 2);
1393 if (op.m == EASY) deck[i] = 1+((deck[i]-1) | 2 | 1);
1394 /* the 1+ -1 dance gets rid of the offset created by NO_CARD */
1395 }
1396 #endif
1397 srand (seed);
1398 for (int i = DECK_SIZE*NUM_DECKS-1; i > 0; i--) { /* fisher-yates */
1399 int j = rand() % (i+1);
1400 if (j-i) deck[i]^=deck[j],deck[j]^=deck[i],deck[i]^=deck[j];
1401 }
1402
1403 /* deal cards: */
1404 for (int i = 0; i < NUM_PILES; i++) {
1405 #ifdef KLONDIKE
1406 #define SIGN -
1407 int count = i; /* pile n has n closed cards, then 1 open */
1408 #elif defined SPIDER
1409 #define SIGN -
1410 int count = i<4?5:4; /* pile 1-4 have 5, 5-10 have 4 closed */
1411 #elif defined FREECELL
1412 #define SIGN +
1413 int count = i<4?6:5;/*like spider, but cards are dealt face-up*/
1414 #endif
1415 /* "SIGN": face down cards are negated */
1416 for (int j = 0; j < count; j++) f.t[i][j] = SIGN deck[--avail];
1417 f.t[i][count] = deck[--avail]; /* the face-up card */
1418 #undef SIGN
1419 }
1420 /* rest of the cards to the stock: */
1421 /* NOTE: assert(avail==50) for spider, assert(avail==0) for freecell */
1422 for (f.z = 0; avail; f.z++) f.s[f.z] = deck[--avail];
1423 #ifdef KLONDIKE
1424 f.w = -1; /* @start: nothing on waste */
1425 #elif defined SPIDER
1426 f.w = 0; /* number of used foundations */
1427 #elif defined FREECELL
1428 f.w = 0; /* bitmask of used free cells */
1429 #endif
1430
1431 f.u = &undo_sentinel;
1432 }
1433 //}}}
1434
1435 // screen drawing routines {{{
1436 void print_hi(int invert, int grey_bg, int bold, char* str) {
1437 if (!op.h) invert = 0; /* don't show invert if we used the mouse last */
1438 if (bold && op.s == &unicode_large_color){ //awful hack for bold + faint
1439 int offset = str[3]==017?16:str[4]==017?17:0;
1440 printf ("%s%s%s""%.*s%s%s""%s%s%s",
1441 "\033[1m", invert?"\033[7m":"", grey_bg?"\033[100m":"",
1442 offset, str, bold?"\033[1m":"", str+offset,
1443 grey_bg?"\033[49m":"", invert?"\033[27m":"","\033[22m");
1444 return;
1445 }
1446 printf ("%s%s%s%s%s%s%s",
1447 bold?"\033[1m":"", invert?"\033[7m":"", grey_bg?"\033[100m":"",
1448 str,
1449 grey_bg?"\033[49m":"", invert?"\033[27m":"",bold?"\033[22m":"");
1450 }
1451 void print_table(const struct cursor* active, const struct cursor* inactive) {
1452 printf("\033[2J\033[H"); /* clear screen, reset cursor */
1453 #ifdef KLONDIKE
1454 /* print stock, waste and foundation: */
1455 for (int line = 0; line < op.s->height; line++) {
1456 /* stock: */
1457 print_hi (active->pile == STOCK, inactive->pile == STOCK, 1, (
1458 (f.w < f.z-1)?op.s->facedown
1459 :op.s->placeholder)[line]);
1460 /* waste: */
1461 print_hi (active->pile == WASTE, inactive->pile == WASTE, 1, (
1462 /* NOTE: cast, because f.w sometimes is (short)-1 !? */
1463 ((short)f.w >= 0)?op.s->card[f.s[f.w]]
1464 :op.s->placeholder)[line]);
1465 printf ("%s", op.s->card[NO_CARD][line]); /* spacer */
1466 /* foundation: */
1467 for (int pile = 0; pile < NUM_SUITS; pile++) {
1468 int card = find_top(f.f[pile]);
1469 print_hi (active->pile==FOUNDATION && active->opt==pile,
1470 inactive->pile==FOUNDATION && (
1471 /* cursor addr. || direct addr. */
1472 inactive->opt==pile || inactive->opt < 0
1473 ), 1,
1474 (card < 0)?op.s->foundation[line]
1475 :op.s->card[f.f[pile][card]][line]);
1476 }
1477 printf("\n");
1478 }
1479 printf("\n");
1480 #elif defined SPIDER
1481 int fdone; for (fdone = NUM_DECKS*NUM_SUITS; fdone; fdone--)
1482 if (f.f[fdone-1][RANK_K]) break; /*number of completed stacks*/
1483 int spacer_from = f.z?(f.z/10-1) * op.s->halfwidth[0] + op.s->width:0;
1484 int spacer_to = NUM_PILES*op.s->width -
1485 ((fdone?(fdone-1) * op.s->halfwidth[1]:0)+op.s->width);
1486 for (int line = 0; line < op.s->height; line++) {
1487 /* available stock: */
1488 for (int i = f.z/10; i; i--) {
1489 if (i==1) printf ("%s", op.s->facedown[line]);
1490 else printf ("%s", op.s->halfstack[line]);
1491 }
1492 /* spacer: */
1493 for (int i = spacer_from; i < spacer_to; i++) printf (" ");
1494 /* foundation (overlapping): */
1495 for (int i = NUM_DECKS*NUM_SUITS-1, half = 0; i >= 0; i--) {
1496 int overlap = half? op.s->halfcard[line]: 0;
1497 if (f.f[i][RANK_K]) printf ("%.*s", op.s->halfwidth[2],
1498 op.s->card[f.f[i][RANK_K]][line]+overlap),
1499 half++;
1500 }
1501 printf("\n");
1502 }
1503 printf("\n");
1504 #elif defined FREECELL
1505 /* print open cells, foundation: */
1506 for (int line = 0; line < op.s->height; line++) {
1507 for (int pile = 0; pile < NUM_CELLS; pile++)
1508 print_hi (active->pile==STOCK && active->opt==pile,
1509 inactive->pile==STOCK && (
1510 /* cursor addr. || direct addr. */
1511 inactive->opt==pile || inactive->opt < 0
1512 ), 1,
1513 ((f.s[pile])?op.s->card[f.s[pile]]
1514 :op.s->placeholder)[line]);
1515 for (int pile = 0; pile < NUM_SUITS; pile++) {
1516 int card = find_top(f.f[pile]);
1517 print_hi (active->pile==FOUNDATION && active->opt==pile,
1518 inactive->pile==FOUNDATION && (
1519 /* cursor addr. || direct addr. */
1520 inactive->opt==pile || inactive->opt < 0
1521 ), 1,
1522 (card < 0)?op.s->foundation[line]
1523 :op.s->card[f.f[pile][card]][line]);
1524 }
1525 printf("\n");
1526 }
1527 printf("\n");
1528 #endif
1529 #ifdef KLONDIKE
1530 #define DO_HI(cursor) (cursor->pile == pile && (movable || empty))
1531 #define TOP_HI(c) 1 /* can't select partial stacks in KLONDIKE */
1532 #elif defined SPIDER || defined FREECELL
1533 int offset[NUM_PILES]={0}; /* first card to highlight */
1534 # ifdef FREECELL
1535 int bottom[NUM_PILES]; /* first movable card */
1536 for (int i=0; i<NUM_PILES; i++)
1537 bottom[i] = find_top(f.t[i]) - max_move(i,-1);
1538 # endif
1539 #define DO_HI(cursor) (cursor->pile == pile && (movable || empty) \
1540 && offset[pile] >= cursor->opt)
1541 #define TOP_HI(cursor) (cursor->pile == pile && movable \
1542 && offset[pile] == cursor->opt)
1543 #endif
1544 /* print tableu piles: */
1545 int row[NUM_PILES] = {0};
1546 int line[NUM_PILES]= {0};
1547 int label[NUM_PILES]={0};
1548 int line_had_card;
1549 int did_placeholders = 0;
1550 do {
1551 line_had_card = 0;
1552 for (int pile = 0; pile < NUM_PILES; pile++) {
1553 card_t card = f.t[pile][row[pile]];
1554 card_t next = f.t[pile][row[pile]+1];
1555 int movable = is_movable(f.t[pile], row[pile]);
1556 #ifdef FREECELL
1557 if(row[pile] <= bottom[pile]) movable = 0;
1558 #endif
1559 int empty = !card && row[pile] == 0;
1560
1561 print_hi (DO_HI(active), DO_HI(inactive), movable, (
1562 (!card && row[pile] == 0)?op.s->placeholder
1563 :(card<0)?op.s->facedown
1564 :op.s->card[card]
1565 )[line[pile]]);
1566
1567 int extreme_overlap = ( 3 /* spacer, labels, status */
1568 + 2 * op.s->height /* stock, top tableu card */
1569 + find_top(f.t[pile]) * op.s->overlap) >op.w[0];
1570 /* normal overlap: */
1571 if (++line[pile] >= (next?op.s->overlap:op.s->height)
1572 /* extreme overlap on closed cards: */
1573 || (extreme_overlap &&
1574 line[pile] >= 1 &&
1575 f.t[pile][row[pile]] < 0 &&
1576 f.t[pile][row[pile]+1] <0)
1577 /* extreme overlap on sequences: */
1578 || (extreme_overlap &&
1579 !TOP_HI(active) && /*always show top selected card*/
1580 line[pile] >= 1 && row[pile] > 0 &&
1581 f.t[pile][row[pile]-1] > NO_CARD &&
1582 is_consecutive (f.t[pile], row[pile]) &&
1583 is_consecutive (f.t[pile], row[pile]-1) &&
1584 f.t[pile][row[pile]+1] != NO_CARD)
1585 ) {
1586 line[pile]=0;
1587 row[pile]++;
1588 #if defined SPIDER || defined FREECELL
1589 if (movable) offset[pile]++;
1590 #endif
1591 }
1592 /* tableu labels: */
1593 if(!card && !label[pile] && row[pile]>0&&line[pile]>0) {
1594 label[pile] = 1;
1595 printf ("\b\b%d ", (pile+1) % 10); //XXX: hack
1596 }
1597 line_had_card |= !!card;
1598 did_placeholders |= row[pile] > 0;
1599 }
1600 printf ("\n");
1601 } while (line_had_card || !did_placeholders);
1602 }
1603
1604 void visbell (void) {
1605 if (!op.v) return;
1606 printf ("\033[?5h"); fflush (stdout);
1607 usleep (100000);
1608 printf ("\033[?5l"); fflush (stdout);
1609 }
1610 void win_anim(void) {
1611 printf ("\033[?25l"); /* hide cursor */
1612 for (;;) {
1613 /* set cursor to random location */
1614 int row = 1+rand()%(1+op.w[0]-op.s->height);
1615 int col = 1+rand()%(1+op.w[1]-op.s->width);
1616
1617 /* draw random card */
1618 int face = 1 + rand() % 52;
1619 for (int l = 0; l < op.s->height; l++) {
1620 printf ("\033[%d;%dH", row+l, col);
1621 printf ("%s", op.s->card[face][l]);
1622 }
1623 fflush (stdout);
1624
1625 /* exit on keypress */
1626 struct pollfd p = {STDIN_FILENO, POLLIN, 0};
1627 if (poll (&p, 1, 80)) goto fin;
1628 }
1629 fin:
1630 printf ("\033[?25h"); /* show cursor */
1631 return;
1632 }
1633 //}}}
1634
1635 // undo logic {{{
1636 void undo_push (int _f, int t, int n, int o) {
1637 struct undo* new = malloc(sizeof(struct undo));
1638 new->f = _f;
1639 new->t = t;
1640 new->n = n;
1641 new->o = o;
1642 new->prev = f.u;
1643 new->next = NULL;
1644 f.u->next = new;
1645 f.u = f.u->next;
1646 }
1647 void undo_pop (struct undo* u) {
1648 if (u == &undo_sentinel) return;
1649
1650 #ifdef KLONDIKE
1651 if (u->f == FOUNDATION) {
1652 /* foundation -> tableu */
1653 int top_f = find_top(f.f[u->n]);
1654 int top_t = find_top(f.t[u->t]);
1655 f.f[u->n][top_f+1] = f.t[u->t][top_t];
1656 f.t[u->t][top_t] = NO_CARD;
1657 } else if (u->f == WASTE && u->t == FOUNDATION) {
1658 /* waste -> foundation */
1659 /* split u->n into wst and fnd: */
1660 int wst = u->n & 0xffff;
1661 int fnd = u->n >> 16;
1662 /* move stock cards one position up to make room: */
1663 for (int i = f.z; i >= wst; i--) f.s[i+1] = f.s[i];
1664 /* move one card from foundation to waste: */
1665 int top = find_top(f.f[fnd]);
1666 f.s[wst] = f.f[fnd][top];
1667 f.f[fnd][top] = NO_CARD;
1668 f.z++;
1669 f.w++;
1670 } else if (u->f == WASTE) {
1671 /* waste -> tableu */
1672 /* move stock cards one position up to make room: */
1673 for (int i = f.z-1; i >= u->n; i--) f.s[i+1] = f.s[i];
1674 /* move one card from tableu to waste: */
1675 int top = find_top(f.t[u->t]);
1676 f.s[u->n] = f.t[u->t][top];
1677 f.t[u->t][top] = NO_CARD;
1678 f.z++;
1679 f.w++;
1680 } else if (u->t == FOUNDATION) {
1681 /* tableu -> foundation */
1682 int top_f = find_top(f.t[u->f]);
1683 int top_t = find_top(f.f[u->n]);
1684 /* close topcard if previous action caused turn_over(): */
1685 if (u->o) f.t[u->f][top_f] *= -1;
1686 /* move one card from foundation to tableu: */
1687 f.t[u->f][top_f+1] = f.f[u->n][top_t];
1688 f.f[u->n][top_t] = NO_CARD;
1689 } else {
1690 /* tableu -> tableu */
1691 int top_f = find_top(f.t[u->f]);
1692 int top_t = find_top(f.t[u->t]);
1693 /* close topcard if previous action caused turn_over(): */
1694 if (u->o) f.t[u->f][top_f] *= -1;
1695 /* move n cards from tableu[f] to tableu[t]: */
1696 for (int i = 0; i < u->n; i++) {
1697 f.t[u->f][top_f+u->n-i] = f.t[u->t][top_t-i];
1698 f.t[u->t][top_t-i] = NO_CARD;
1699 }
1700 }
1701 #elif defined SPIDER
1702 if (u->f == STOCK) {
1703 /* stock -> tableu */
1704 /*remove a card from each pile and put it back onto the stock:*/
1705 for (int pile = NUM_PILES-1; pile >= 0; pile--) {
1706 int top = find_top(f.t[pile]);
1707 f.s[f.z++] = f.t[pile][top];
1708 f.t[pile][top] = NO_CARD;
1709 }
1710 } else if (u->t == FOUNDATION) {
1711 /* tableu -> foundation */
1712 int top = find_top(f.t[u->f]);
1713 /* close topcard if previous action caused turn_over(): */
1714 if (u->o) f.t[u->f][top] *= -1;
1715 /* append cards from foundation to tableu */
1716 for (int i = RANK_K; i >= RANK_A; i--) {
1717 f.t[u->f][++top] = f.f[u->n][i];
1718 f.f[u->n][i] = NO_CARD;
1719 }
1720 f.w--; /* decrement complete-foundation-counter */
1721
1722 } else {
1723 /* tableu -> tableu */
1724 int top_f = find_top(f.t[u->f]);
1725 int top_t = find_top(f.t[u->t]);
1726 /* close topcard if previous action caused turn_over(): */
1727 if (u->o) f.t[u->f][top_f] *= -1;
1728 /* move n cards from tableu[f] to tableu[t]: */
1729 for (int i = 0; i < u->n; i++) {
1730 f.t[u->f][top_f+u->n-i] = f.t[u->t][top_t-i];
1731 f.t[u->t][top_t-i] = NO_CARD;
1732 }
1733 }
1734 #elif defined FREECELL
1735 /*NOTE: if from and to are both stock/foundation, opt = from | to<<16 */
1736 if (u->f == STOCK && u->t == FOUNDATION) {
1737 /* free cells -> foundation */
1738 /* split u->n into cll and fnd: */
1739 int cll = u->n & 0xffff;
1740 int fnd = u->n >> 16;
1741 /* move one card from foundation to free cell: */
1742 int top = find_top(f.f[fnd]);
1743 f.s[cll] = f.f[fnd][top];
1744 f.f[fnd][top] = NO_CARD;
1745 f.w |= 1<<cll; /* mark cell as occupied */
1746 } else if (u->f == STOCK) {
1747 /* free cells -> cascade */
1748 int top_t = find_top(f.t[u->t]);
1749 f.s[u->n] = f.t[u->t][top_t];
1750 f.t[u->t][top_t] = NO_CARD;
1751 f.w |= 1<<u->n; /* mark cell as occupied */
1752 } else if (u->f == FOUNDATION && u->t == STOCK) {
1753 /* foundation -> free cells */
1754 /* split u->n into cll and fnd: */
1755 int cll = u->n >> 16;
1756 int fnd = u->n & 0xffff;
1757 /* move 1 card from free cell to foundation: */
1758 int top_f = find_top(f.f[fnd]);
1759 f.f[fnd][top_f+1] = f.s[cll];
1760 f.s[cll] = NO_CARD;
1761 f.w &= ~(1<<cll); /* mark cell as free */
1762 } else if (u->f == FOUNDATION) {
1763 /* foundation -> cascade */
1764 int top_f = find_top(f.f[u->n]);
1765 int top_t = find_top(f.t[u->t]);
1766 f.f[u->n][top_f+1] = f.t[u->t][top_t];
1767 f.t[u->t][top_t] = NO_CARD;
1768 } else if (u->t == STOCK) {
1769 /* cascade -> free cells */
1770 int top_f = find_top(f.t[u->f]);
1771 f.t[u->f][top_f+1] = f.s[u->n];
1772 f.s[u->n] = NO_CARD;
1773 f.w &= ~(1<<u->n); /* mark cell as free */
1774 } else if (u->t == FOUNDATION) {
1775 /* cascade -> foundation */
1776 int top_f = find_top(f.t[u->f]);
1777 int top_t = find_top(f.f[u->n]);
1778 /* move one card from foundation to cascade: */
1779 f.t[u->f][top_f+1] = f.f[u->n][top_t];
1780 f.f[u->n][top_t] = NO_CARD;
1781 } else {
1782 /* cascade -> cascade */
1783 int top_f = find_top(f.t[u->f]);
1784 int top_t = find_top(f.t[u->t]);
1785 /* move n cards from tableu[f] to tableu[t]: */
1786 for (int i = 0; i < u->n; i++) {
1787 f.t[u->f][top_f+u->n-i] = f.t[u->t][top_t-i];
1788 f.t[u->t][top_t-i] = NO_CARD;
1789 }
1790 }
1791 #endif
1792
1793 void* old = f.u;
1794 f.u = f.u->prev;
1795 free(old);
1796 }
1797 void free_undo (struct undo* u) {
1798 while (u && u != &undo_sentinel) {
1799 void* old = u;
1800 u = u->prev;
1801 free (old);
1802 }
1803 }
1804 //}}}
1805
1806 // initialization stuff {{{
1807 void screen_setup (int enable) {
1808 if (enable) {
1809 raw_mode(1);
1810 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
1811 printf ("\033[H\033[J"); /* reset cursor, clear screen */
1812 printf ("\033[?1000h"); /* enable mouse */
1813 } else {
1814 printf ("\033[?1000l"); /* disable mouse */
1815 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
1816 raw_mode(0);
1817 }
1818 }
1819
1820 void raw_mode(int enable) {
1821 static struct termios saved_term_mode;
1822 struct termios raw_term_mode;
1823
1824 if (enable) {
1825 if (saved_term_mode.c_lflag == 0)/*don't overwrite stored mode*/
1826 tcgetattr(STDIN_FILENO, &saved_term_mode);
1827 raw_term_mode = saved_term_mode;
1828 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
1829 raw_term_mode.c_cc[VMIN] = 1 ;
1830 raw_term_mode.c_cc[VTIME] = 0;
1831 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
1832 } else {
1833 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
1834 }
1835 }
1836
1837 void signal_handler (int signum) {
1838 struct winsize w;
1839 switch (signum) {
1840 case SIGTSTP:
1841 screen_setup(0);
1842 signal(SIGTSTP, SIG_DFL); /* NOTE: assumes SysV semantics! */
1843 raise(SIGTSTP);
1844 break;
1845 case SIGCONT:
1846 screen_setup(1);
1847 print_table(NO_HI, NO_HI);
1848 break;
1849 case SIGINT: //TODO: don't exit; just warn like vim does
1850 exit(128+SIGINT);
1851 case SIGWINCH:
1852 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
1853 op.w[0] = w.ws_row;
1854 op.w[1] = w.ws_col;
1855 break;
1856 }
1857 }
1858 void signal_setup(void) {
1859 struct sigaction saction;
1860
1861 saction.sa_handler = signal_handler;
1862 sigemptyset(&saction.sa_mask);
1863 saction.sa_flags = 0;
1864 if (sigaction(SIGTSTP, &saction, NULL) < 0) {
1865 perror ("SIGTSTP");
1866 exit (1);
1867 }
1868 if (sigaction(SIGCONT, &saction, NULL) < 0) {
1869 perror ("SIGCONT");
1870 exit (1);
1871 }
1872 if (sigaction(SIGINT, &saction, NULL) < 0) {
1873 perror ("SIGINT");
1874 exit (1);
1875 }
1876 if (sigaction(SIGWINCH, &saction, NULL) < 0) {
1877 perror ("SIGWINCH");
1878 exit (1);
1879 }
1880 }
1881 //}}}
1882
1883 //vim: foldmethod=marker
Imprint / Impressum