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