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