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