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