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