]> git.gir.st - solVItaire.git/blob - sol.c
fix off-by-one
[solVItaire.git] / sol.c
1 #define _DEFAULT_SOURCE
2 #define _POSIX_C_SOURCE /* for sigaction */
3 #include <poll.h>
4 #include <signal.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <sys/ioctl.h>
8 #include <time.h>
9 #include <termios.h>
10 #include <unistd.h>
11
12 #include "sol.h"
13 #include "schemes.h"
14
15 struct playfield f;
16 struct opts op;
17
18 // action table {{{
19 /* stores a function pointer for every takeable action; called by game loop */
20 int (*action[NUM_PLACES][10])(int,int,int) = {
21 #ifdef KLONDIKE
22 /* 1 2 3 4 5 6 7 stk wst fnd*/
23 /* 1 */ { t2f, t2t, t2t, t2t, t2t, t2t, t2t, nop, nop, t2f },
24 /* 2 */ { t2t, t2f, t2t, t2t, t2t, t2t, t2t, nop, nop, t2f },
25 /* 3 */ { t2t, t2t, t2f, t2t, t2t, t2t, t2t, nop, nop, t2f },
26 /* 4 */ { t2t, t2t, t2t, t2f, t2t, t2t, t2t, nop, nop, t2f },
27 /* 5 */ { t2t, t2t, t2t, t2t, t2f, t2t, t2t, nop, nop, t2f },
28 /* 6 */ { t2t, t2t, t2t, t2t, t2t, t2f, t2t, nop, nop, t2f },
29 /* 7 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2f, nop, nop, t2f },
30 /*stk*/ { nop, nop, nop, nop, nop, nop, nop, nop, s2w, nop },
31 /*wst*/ { w2t, w2t, w2t, w2t, w2t, w2t, w2t, w2s, w2f, w2f },
32 /*fnd*/ { f2t, f2t, f2t, f2t, f2t, f2t, f2t, nop, nop, nop },
33 #elif defined SPIDER
34 /* 1 2 3 4 5 6 7 8 9 10*/
35 /* 1 */ { t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t },
36 /* 2 */ { t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t },
37 /* 3 */ { t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2t, t2t },
38 /* 4 */ { t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2t, t2t },
39 /* 5 */ { t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2t, t2t },
40 /* 6 */ { t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2t, t2t },
41 /* 7 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2t, t2t },
42 /* 8 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2t, t2t },
43 /* 9 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2f, t2t },
44 /*10 */ { t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2t, t2f },
45 /*stk*/ { s2t, s2t, s2t, s2t, s2t, s2t, s2t, s2t, s2t, s2t },
46 #endif
47 };
48 // }}}
49
50 // argv parsing, game loops, cleanup {{{
51 int main(int argc, char** argv) {
52 /* opinionated defaults: */
53 op.s = &unicode_large_color;
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:vbcm")) != -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 'h': default: goto error;
75 error:
76 fprintf (stderr, SHORTHELP LONGHELP KEYHELP, argv[0]);
77 return optget != 'h';
78 }
79 }
80
81 signal_setup();
82 atexit (*quit);
83
84 signal_handler(SIGWINCH); /* initialize window size */
85
86 newgame:
87 screen_setup(1);
88
89 switch(sol()) {
90 case GAME_NEW: goto newgame;
91 case GAME_WON:
92 print_table(NO_HI, NO_HI);
93 win_anim();
94 if (getchar()=='q') return 0;
95 goto newgame;
96 case GAME_QUIT: return 0;
97 }
98 }
99
100 int sol(void) {
101 /* clean undo (from previous game): */
102 free_undo(f.u);
103
104 deal();
105
106 int from, to, opt;
107 for(;;) {
108 switch (get_cmd(&from, &to, &opt)) {
109 case CMD_MOVE:
110 switch (action[from][to](from,to,opt)) {
111 case OK: break;
112 case ERR: visbell(); break;
113 case WON: return GAME_WON;
114 }
115 break;
116 case CMD_HINT: break;//TODO: show a possible (and sensible) move. if possible, involve active cursor
117 case CMD_JOIN:
118 switch (join(to)) {
119 case OK: break;
120 case ERR: visbell(); break;
121 case WON: return GAME_WON;
122 }
123 break;
124 case CMD_UNDO: undo_pop(f.u); break;
125 case CMD_INVAL: visbell(); break;
126 case CMD_NEW: return GAME_NEW;
127 case CMD_AGAIN: //TODO: restart with same seed
128 case CMD_QUIT: return GAME_QUIT;
129 }
130 }
131 }
132
133 void quit(void) {
134 screen_setup(0);
135 /* free undo data structures: */
136 free_undo(f.u);
137 }
138 //}}}
139
140 // card games helper functions {{{
141 #define get_suit(card) \
142 ((card-1) % NUM_SUITS)
143 #define get_rank(card) \
144 ((card-1) / NUM_SUITS)
145 #define get_color(card) \
146 ((get_suit(card) ^ get_suit(card)>>1) & 1)
147
148 #define is_tableu(where) (where <= TAB_MAX)
149
150 int find_top(card_t* pile) {
151 int i;
152 for(i=PILE_SIZE-1; i>=0 && !pile[i]; i--);
153 return i;
154 }
155 int first_movable(card_t* pile) {
156 int i = 0;
157 for (;pile[i] && !is_movable(pile, i); i++);
158 return i;
159 }
160 int turn_over(card_t* pile) {
161 int top = find_top(pile);
162 if (pile[top] < 0) {
163 pile[top] *= -1;
164 return 1;
165 } else return 0;
166 }
167 int check_won(void) {
168 for (int pile = 0; pile < NUM_DECKS*NUM_SUITS; pile++)
169 if (f.f[pile][NUM_RANKS-1] == NO_CARD) return 0;
170
171 return 1;
172 }
173 int rank_next (card_t a, card_t b) {
174 return get_rank(a) == get_rank(b)-1;
175 }
176 int is_consecutive (card_t* pile, int pos) {
177 if (pos+1 >= PILE_SIZE) return 1; /* card is last */
178 if (pile[pos+1] == NO_CARD) return 1; /* card is first */
179
180 #ifdef KLONDIKE
181 /* ranks consecutive? */
182 if (!rank_next(pile[pos+1], pile[pos])) return 0;
183 /* color opposite? */
184 if (get_color(pile[pos+1]) == get_color(pile[pos])) return 0;
185 #elif defined SPIDER
186 /* ranks consecutive? */
187 if (!rank_next(pile[pos+1], pile[pos])) return 0;
188 /* same suit? */
189 if (get_suit(pile[pos+1]) != get_suit(pile[pos])) return 0;
190 #endif
191
192 return 1;
193 }
194
195 int is_movable(card_t* pile, int n) {
196 #ifdef KLONDIKE
197 return(pile[n] > NO_CARD); /*non-movable cards don't exist in klondike*/
198 #elif defined SPIDER
199 int top = find_top(pile);
200 for (int i = top; i >= 0; i--) {
201 if (pile[i] <= NO_CARD) return 0; /*no card or card face down?*/
202 if (!is_consecutive(pile, i)) return 0;
203 if (i == n) return 1; /* card reached, must be movable */
204 }
205 return 0;
206 #endif
207 }
208 //}}}
209
210 // takeable actions {{{
211 #ifdef KLONDIKE
212 card_t stack_take(void) { /*NOTE: assert(f.w >= 0) */
213 card_t card = f.s[f.w];
214 /* move stack one over, so there are no gaps in it: */
215 for (int i = f.w; i < f.z-1; i++)
216 f.s[i] = f.s[i+1];
217 f.z--;
218 f.w--; /* make previous card visible again */
219 return card;
220 }
221 int t2f(int from, int to, int opt) { /* tableu to foundation */
222 (void) to; (void) opt; /* don't need */
223 int top_from = find_top(f.t[from]);
224 to = get_suit(f.t[from][top_from]);
225 int top_to = find_top(f.f[to]);
226 if ((top_to < 0 && get_rank(f.t[from][top_from]) == RANK_A)
227 || (top_to >= 0 && rank_next(f.f[to][top_to],f.t[from][top_from]))) {
228 f.f[to][top_to+1] = f.t[from][top_from];
229 f.t[from][top_from] = NO_CARD;
230 undo_push(from, FOUNDATION, to,
231 turn_over(f.t[from]));
232 if (check_won()) return WON;
233 return OK;
234 } else return ERR;
235 }
236 int w2f(int from, int to, int opt) { /* waste to foundation */
237 (void) from; (void) to; (void) opt; /* don't need */
238 if (f.w < 0) return ERR;
239 to = get_suit(f.s[f.w]);
240 int top_to = find_top(f.f[to]);
241 if ((top_to < 0 && get_rank(f.s[f.w]) == RANK_A)
242 || (top_to >= 0 && rank_next(f.f[to][top_to], f.s[f.w]))) {
243 undo_push(WASTE, FOUNDATION, f.w | to<<16, 0);//ugly encoding :|
244 f.f[to][top_to+1] = stack_take();
245 if (check_won()) return WON;
246 return OK;
247 } else return ERR;
248
249 }
250 int s2w(int from, int to, int opt) { /* stock to waste */
251 (void) from; (void) to; (void) opt; /* don't need */
252 if (f.z == 0) return ERR;
253 f.w++;
254 if (f.w == f.z) f.w = -1;
255 return OK;
256 }
257 int w2s(int from, int to, int opt) { /* waste to stock (undo stock to waste) */
258 (void) from; (void) to; (void) opt; /* don't need */
259 if (f.z == 0) return ERR;
260 f.w--;
261 if (f.w < -1) f.w = f.z-1;
262 return OK;
263 }
264 int f2t(int from, int to, int opt) { /* foundation to tableu */
265 (void) from; /* don't need */
266 int top_to = find_top(f.t[to]);
267 from = opt;
268 int top_from = find_top(f.f[from]);
269
270 if ((get_color(f.t[to][top_to]) != get_color(f.f[from][top_from]))
271 && (rank_next(f.f[from][top_from], f.t[to][top_to]))) {
272 f.t[to][top_to+1] = f.f[from][top_from];
273 f.f[from][top_from] = NO_CARD;
274 undo_push(FOUNDATION, to, from, 0);
275 return OK;
276 } else return ERR;
277 }
278 int w2t(int from, int to, int opt) { /* waste to tableu */
279 (void) from; (void) opt; /* don't need */
280 int top_to = find_top(f.t[to]);
281 if (((get_color(f.t[to][top_to]) != get_color(f.s[f.w]))
282 && (rank_next(f.s[f.w], f.t[to][top_to])))
283 || (top_to < 0 && get_rank(f.s[f.w]) == RANK_K)) {
284 undo_push(WASTE, to, f.w, 0);
285 f.t[to][top_to+1] = stack_take();
286 return OK;
287 } else return ERR;
288 }
289 int t2t(int from, int to, int opt) { /* tableu to tableu */
290 (void) opt; /* don't need */
291 int top_to = find_top(f.t[to]);
292 int top_from = find_top(f.t[from]);
293 int count = 0; //NOTE: could probably be factored out
294 for (int i = top_from; i >=0; i--) {
295 if (((get_color(f.t[to][top_to]) != get_color(f.t[from][i]))
296 && (rank_next(f.t[from][i], f.t[to][top_to]))
297 && f.t[from][i] > NO_CARD) /* card face up? */
298 || (top_to < 0 && get_rank(f.t[from][i]) == RANK_K)) {
299 /* move cards [i..top_from] to their destination */
300 for (;i <= top_from; i++) {
301 top_to++;
302 f.t[to][top_to] = f.t[from][i];
303 f.t[from][i] = NO_CARD;
304 count++;
305 }
306 undo_push(from, to, count,
307 turn_over(f.t[from]));
308 return OK;
309 }
310 }
311 return ERR; /* no such move possible */
312 }
313 #elif defined SPIDER
314 int remove_if_complete (int pileno) { //cleanup!
315 card_t* pile = f.t[pileno];
316 /* test if K...A complete; move to foundation if so */
317 int top_from = find_top(pile);
318 if (get_rank(pile[top_from]) != RANK_A) return 0;
319 for (int i = top_from; i>=0; i--) {
320 if (!is_consecutive (pile, i)) return 0;
321 if (i+RANK_K == top_from /* if ace to king: remove it */
322 && get_rank(pile[top_from-RANK_K]) == RANK_K) {
323 for(int i=top_from, j=0; i>top_from-NUM_RANKS; i--,j++){
324 f.f[f.w][j] = pile[i];
325 pile[i] = NO_CARD;
326 }
327 undo_push(pileno, FOUNDATION, f.w,
328 turn_over(pile));
329 f.w++;
330 return 1;
331 }
332 }
333
334 return 0;
335 }
336 int t2t(int from, int to, int opt) { //in dire need of cleanup
337 int top_from = find_top(f.t[from]);
338 int top_to = find_top(f.t[to]);
339 int empty_to = (top_to < 0)? opt: -1; /* empty pile? */
340 int count = 0; //NOTE: could probably be factored out
341
342 for (int i = top_from; i >= 0; i--) {
343 if (!is_consecutive(f.t[from], i)) break;
344
345 /* is consecutive OR to empty pile and rank ok? */
346 if (rank_next(f.t[from][i], f.t[to][top_to])
347 || (empty_to >= RANK_A && get_rank(f.t[from][i]) == empty_to)) {
348 for (;i <= top_from; i++) {
349 top_to++;
350 f.t[to][top_to] = f.t[from][i];
351 f.t[from][i] = NO_CARD;
352 count++;
353 }
354 undo_push(from, to, count,
355 turn_over(f.t[from]));
356 remove_if_complete(to);
357 if (check_won()) return WON;
358 return OK;
359 }
360 }
361
362 return ERR; /* no such move possible */
363 }
364 int s2t(int from, int to, int opt) {
365 (void) from; (void) to; (void) opt; /* don't need */
366 if (f.z <= 0) return ERR; /* stack out of cards */
367 for (int pile = 0; pile < NUM_PILES; pile++)
368 if (f.t[pile][0]==NO_CARD) return ERR; /*no piles may be empty*/
369 for (int pile = 0; pile < NUM_PILES; pile++) {
370 f.t[pile][find_top(f.t[pile])+1] = f.s[--f.z];
371 remove_if_complete(pile);
372 if (check_won()) return WON;
373 }
374 undo_push(STOCK, TABLEU, 1, 0); /*NOTE: puts 1 card on each tableu pile*/
375 return OK;
376 }
377 int t2f(int from, int to, int opt) {
378 (void) to; (void) opt; /* don't need */
379 /* manually retrigger remove_if_complete() (e.g. after undo_pop) */
380 return remove_if_complete(from)?OK:ERR;
381 }
382 #endif
383 int join(int to) {
384 //TODO: allow joining to foundation in klondike
385 //TODO: which pile to take from should form the basis of CMD_HINT
386
387 int top_to = find_top(f.t[to]); //TODO: handle empty
388 int from = -1;
389
390 struct rating {
391 int ok:1; /* card to move in pile? */
392 int above; /* number of movable cards above */
393 int below; /* number of cards below ours */
394 int pos; /* where the card to move is in the pile */
395 } r[NUM_PILES] = {{0}};
396
397 /* 1. rate each pile: */
398 for (int pile = 0; pile < NUM_PILES; pile++) {
399 r[pile].pos = find_top(f.t[pile]);
400 /* backtrack until we find a compatible-to-'to'-pile card: */
401 while (r[pile].pos >= 0 && is_movable(f.t[pile], r[pile].pos)) {
402 int rankdiff = get_rank(f.t[pile][r[pile].pos])
403 - get_rank(f.t[to][top_to]);
404 if (rankdiff >= 0) break; /* past our card */
405 if (rankdiff == -1 /* rank matches */
406 #ifdef KLONDIKE
407 && get_color(f.t[pile][r[pile].pos]) /* color OK */
408 != get_color(f.t[to][top_to])
409 #elif defined SPIDER
410 && get_suit(f.t[pile][r[pile].pos]) /* color OK */
411 == get_suit(f.t[to][top_to])
412 #endif
413 ) {
414 r[pile].ok++;
415 for (int i = r[pile].pos; i >= 0; i--)
416 if (is_movable(f.t[pile], i-1))
417 r[pile].above++;
418 else break;
419 break;
420 }
421 r[pile].pos--;
422 r[pile].below++;
423 }
424 }
425
426 /* 2. find optimal pile: (optimized for spider) */
427 for (int pile = 0, above = 99, turn = 0, empty = 0, below = 99, e=0,t=0;
428 pile < NUM_PILES; pile++) {
429 if (!r[pile].ok) continue;
430
431 if ((e=(r[pile].pos == 0)) /* will become empty */
432 || ((t=(f.t[pile][r[pile].pos-1] < 0)) && !empty) /* will turn_over */
433 || (r[pile].above < above && !empty) /* less cards above */
434 || (r[pile].above ==above && r[pile].below < below && !empty && !turn)) { /* if tied, use shorter pile */
435 from = pile;
436 above = r[pile].above;
437 below = r[pile].below;
438 empty |= e;
439 turn |= t;
440 }
441 }
442
443 /* 3a. give up if nothing found: */
444 if (from < 0) {
445 #ifdef KLONDIKE /* check if we can take from waste before giving up */
446 return w2t(WASTE, to, 0);
447 #elif defined SPIDER
448 return ERR;
449 #endif
450 }
451
452 /* 3b. move cards over and return: */
453 #ifdef KLONDIKE
454 return t2t(from, to, 0);
455 #elif defined SPIDER
456 int bottom = first_movable(f.t[from]);
457 return t2t(from, to, get_rank(f.t[from][bottom]));
458 #endif
459 }
460 int nop(int from, int to, int opt) { (void)from;(void)to;(void)opt;return ERR; }
461 // }}}
462
463 // keyboard input handling {{{
464 // cursor functions{{{
465 #pragma GCC diagnostic ignored "-Wswitch" //not ideal :|
466 #ifdef KLONDIKE
467 void cursor_left (struct cursor* cursor) {
468 if (is_tableu(cursor->pile)) {
469 if (cursor->pile > 0) cursor->pile--;
470 cursor->opt = 0;
471 } else { /* stock/waste/foundation*/
472 switch (cursor->pile) {
473 case WASTE: cursor->pile = STOCK; cursor->opt = 0; break;
474 case FOUNDATION:
475 if (cursor->opt <= 0)
476 cursor->pile = WASTE;
477 else
478 cursor->opt--;
479 }
480 }
481 }
482 void cursor_down (struct cursor* cursor) {
483 if (!is_tableu(cursor->pile)) {
484 switch (cursor->pile) {
485 case STOCK: cursor->pile = TAB_1; break;
486 case WASTE: cursor->pile = TAB_2; break;
487 case FOUNDATION:
488 cursor->pile = TAB_4 + cursor->opt;
489 }
490 cursor->opt = 0;
491 }
492 }
493 void cursor_up (struct cursor* cursor) {
494 if (is_tableu(cursor->pile)) {
495 switch (cursor->pile) { //ugly :|
496 case TAB_1: cursor->pile = STOCK; break;
497 case TAB_2: cursor->pile = WASTE; break;
498 case TAB_3: cursor->pile = WASTE; break;
499 case TAB_4: case TAB_5: case TAB_6: case TAB_7:
500 cursor->opt=cursor->pile-TAB_4;
501 cursor->pile = FOUNDATION;
502 break;
503 }
504 }
505 }
506 void cursor_right (struct cursor* cursor) {
507 if (is_tableu(cursor->pile)) {
508 if (cursor->pile < TAB_MAX) cursor->pile++;
509 } else {
510 switch (cursor->pile) {
511 case STOCK: cursor->pile = WASTE; break;
512 case WASTE: cursor->pile = FOUNDATION;cursor->opt = 0; break;
513 case FOUNDATION:
514 if (cursor->opt < NUM_SUITS-1)
515 cursor->opt++;
516 }
517 }
518 }
519 #elif defined SPIDER
520 /*NOTE: one can't highlight the stock due to me being too lazy to implement it*/
521 void cursor_left (struct cursor* cursor) {
522 if (cursor->pile > 0) cursor->pile--;
523 cursor->opt = 0;
524 }
525 void cursor_down (struct cursor* cursor) {
526 int first = first_movable(f.t[cursor->pile]);
527 int top = find_top(f.t[cursor->pile]);
528 if (first + cursor->opt < top)
529 cursor->opt++;
530 }
531 void cursor_up (struct cursor* cursor) {
532 if (cursor->opt > 0) cursor->opt--;
533 }
534 void cursor_right (struct cursor* cursor) {
535 if (cursor->pile < TAB_MAX) cursor->pile++;
536 cursor->opt = 0;
537 }
538 #endif
539 void cursor_to (struct cursor* cursor, int pile) {
540 cursor->pile = pile;
541 cursor->opt = 0;
542 }
543 #pragma GCC diagnostic pop
544 //}}}
545 int get_cmd (int* from, int* to, int* opt) {
546 //TODO: escape sequences (mouse, cursor keys)
547 int _f, t;
548 struct cursor inactive = {-1,-1};
549 static struct cursor active = {0,0};
550 active.opt = 0; /* always reset offset, but keep pile */
551
552 /***/
553 from_l: print_table(&active, &inactive);
554 _f = getchar();
555
556 switch (_f) {
557 /* direct addressing: */
558 case '1': *from = TAB_1; break;
559 case '2': *from = TAB_2; break;
560 case '3': *from = TAB_3; break;
561 case '4': *from = TAB_4; break;
562 case '5': *from = TAB_5; break;
563 case '6': *from = TAB_6; break;
564 case '7': *from = TAB_7; break;
565 #ifdef SPIDER
566 case '8': *from = TAB_8; break;
567 case '9': *from = TAB_9; break;
568 case '0': *from = TAB_10;break;
569 #elif defined KLONDIKE
570 case '9': *from = WASTE; break;
571 case '0': *from = FOUNDATION; break;
572 case '8': /* fallthrough */
573 #endif
574 case '\n': /* shortcut for dealing from stock */
575 *from = STOCK;
576 *to = WASTE;
577 return CMD_MOVE;
578 /* cursor keys addressing: */
579 case 'h': cursor_left (&active); goto from_l;
580 case 'j': cursor_down (&active); goto from_l;
581 case 'k': cursor_up (&active); goto from_l;
582 case 'l': cursor_right(&active); goto from_l;
583 case 'H': cursor_to(&active,TAB_1); goto from_l; /* leftmost tableu */
584 case 'L': cursor_to(&active,TAB_MAX);goto from_l; /* rigthmost tableu */
585 case 'M': cursor_to(&active,TAB_MAX/2); goto from_l; /* center tableu */
586 //TODO: real cursor keys, home/end
587 case ' ': /* continue with second cursor */
588 *from = active.pile;
589 if (*from == STOCK) {
590 *to = WASTE;
591 return CMD_MOVE;
592 }
593 #ifdef KLONDIKE
594 *opt = active.opt; /* when FOUNDATION */
595 #endif
596 inactive = active;
597 break;
598 /* misc keys: */
599 case ':':
600 {char buf[256];
601 fprintf (stderr, ":");
602 raw_mode(0); /* turn on echo */
603 fgets (buf, 256, stdin);
604 raw_mode(1);
605 switch(buf[0]) {
606 case 'q': return CMD_QUIT;
607 case 'n': return CMD_NEW;
608 case 'r': return CMD_AGAIN;
609 default: return CMD_INVAL;
610 }}
611 case 'J':
612 *to = active.pile;
613 if (*to > TAB_MAX) return CMD_INVAL;
614 return CMD_JOIN;
615 case 'K': /* fallthrough */
616 case '?': return CMD_HINT;
617 case 'u': return CMD_UNDO;
618 case EOF: return CMD_NONE; /* sent by SIGCONT */
619 default: return CMD_INVAL;
620 }
621 inactive.pile = *from; /* for direct addressing highlighting */
622 if (is_tableu(*from) && f.t[*from][0] == NO_CARD) return CMD_INVAL;
623
624 /***/
625 to_l: print_table(&active, &inactive);
626 t = getchar();
627
628 switch (t) {
629 case 'h': cursor_left (&active); goto to_l;
630 case 'j': cursor_down (&active); goto to_l;
631 case 'k': cursor_up (&active); goto to_l;
632 case 'l': cursor_right(&active); goto to_l;
633 case 'H': cursor_to(&active,TAB_1); goto to_l;
634 case 'L': cursor_to(&active,TAB_MAX); goto to_l;
635 case 'M': cursor_to(&active,TAB_MAX/2); goto to_l;
636 case 'J': /* fallthrough; just join selected pile */
637 case ' ':
638 *to = active.pile;
639 break; /* continues with the foundation/empty tableu check */
640 case 'K': /* fallthrough */
641 case '?': return CMD_HINT;
642 case 'u': return CMD_NONE; /* cancel selection */
643 case EOF: return CMD_NONE; /* sent by SIGCONT */
644 default:
645 if (t < '0' || t > '9') return CMD_INVAL;
646 if (t == '0')
647 #ifdef KLONDIKE
648 *to = FOUNDATION;
649 #elif defined SPIDER
650 *to = TAB_10;
651 #endif
652 else
653 *to = t-'1';
654 }
655
656 /***/
657 #ifdef KLONDIKE
658 if (*from == FOUNDATION) {
659 int top = find_top(f.t[*to]);
660 if (top < 0) return CMD_INVAL;
661 int color = get_color(f.t[*to][top]);
662 int choice_1 = 1-color; /* selects piles of */
663 int choice_2 = 2+color; /* the opposite color */
664 int top_c1 = find_top(f.f[choice_1]);
665 int top_c2 = find_top(f.f[choice_2]);
666
667 switch ((rank_next(f.f[choice_1][top_c1], f.t[*to][top])
668 && top_c1 >= 0 ) << 0
669 |(rank_next(f.f[choice_2][top_c2], f.t[*to][top])
670 && top_c2 >= 0 ) << 1) {
671 case ( 1<<0): *opt = choice_1; break; /* choice_1 only */
672 case (1<<1 ): *opt = choice_2; break; /* choice_2 only */
673 case (1<<1 | 1<<0): /* both, ask user which to pick from */
674 printf ("take from (1-4): "); fflush (stdout);
675 *opt = getchar() - '1';
676 if (*opt < 0 || *opt > 3) return CMD_INVAL;
677 break;
678 default: return CMD_INVAL; /* none matched */
679 }
680 /* `opt` is the foundation index (0..3) */
681 }
682 #elif defined SPIDER
683 /* moving to empty tableu? */
684 if (is_tableu(*to) && f.t[*to][0] == NO_CARD) {
685 int bottom = first_movable(f.t[*from]);
686 if (inactive.opt >= 0) { /*if from was cursor addressed: */
687 *opt = get_rank(f.t[*from][bottom + inactive.opt]);
688 return CMD_MOVE;
689 }
690 int top = find_top(f.t[*from]);
691 if (top < 0) return CMD_INVAL;
692 if (top >= 0 && !is_movable(f.t[*from], top-1)) {
693 *opt = get_rank(f.t[*from][top]);
694 } else { /* only ask the user if it's unclear: */
695 printf ("\rup to ([a23456789xjqk] or space/return): ");
696 *opt = getchar();
697 switch (*opt) {
698 case ' ': *opt = get_rank(f.t[*from][top]); break;
699 case'\n': *opt = get_rank(f.t[*from][bottom]); break;
700 case 'a': case 'A': *opt = RANK_A; break;
701 case '0': /* fallthrough */
702 case 'x': case 'X': *opt = RANK_X; break;
703 case 'j': case 'J': *opt = RANK_J; break;
704 case 'q': case 'Q': *opt = RANK_Q; break;
705 case 'k': case 'K': *opt = RANK_K; break;
706 default: *opt -= '1';
707 }
708 if (*opt < RANK_A || *opt > RANK_K) return ERR;
709 }
710 /* `opt` is the rank of the highest card to move */
711 }
712 #endif
713 return CMD_MOVE;
714 }
715 // }}}
716
717 // shuffling and dealing {{{
718 void deal(void) {
719 f = (const struct playfield){0}; /* clear playfield */
720 card_t deck[DECK_SIZE*NUM_DECKS];
721 int avail = DECK_SIZE*NUM_DECKS;
722 for (int i = 0; i < DECK_SIZE*NUM_DECKS; i++) deck[i] = (i%DECK_SIZE)+1;
723 #ifdef SPIDER
724 if (op.m != NORMAL) for (int i = 0; i < DECK_SIZE*NUM_DECKS; i++) {
725 if (op.m == MEDIUM) deck[i] = 1+((deck[i]-1) | 2);
726 if (op.m == EASY) deck[i] = 1+((deck[i]-1) | 2 | 1);
727 /* the 1+ -1 dance gets rid of the offset created by NO_CARD */
728 }
729 #endif
730 srandom (time(NULL));
731 long seed = time(NULL);
732 srandom (seed);
733 for (int i = DECK_SIZE*NUM_DECKS-1; i > 0; i--) { /* fisher-yates */
734 int j = random() % (i+1);
735 if (j-i) deck[i]^=deck[j],deck[j]^=deck[i],deck[i]^=deck[j];
736 }
737
738 /* deal cards: */
739 for (int i = 0; i < NUM_PILES; i++) {
740 #ifdef KLONDIKE
741 int closed = i; /* pile n has n closed cards, then 1 open */
742 #elif defined SPIDER
743 int closed = i<4?5:4; /* pile 1-4 have 5, 5-10 have 4 closed */
744 #endif
745 /* face down cards are negated: */
746 for (int j = 0; j < closed; j++) f.t[i][j] = -deck[--avail];
747 f.t[i][closed] = deck[--avail]; /* the face-up card */
748 }
749 /* rest of the cards to the stock; NOTE: assert(avail==50) for spider */
750 for (f.z = 0; avail; f.z++) f.s[f.z] = deck[--avail];
751 #ifdef KLONDIKE
752 f.w = -1; /* @start: nothing on waste */
753 #elif defined SPIDER
754 f.w = 0; /* number of used foundations */
755 #endif
756
757 f.u = &undo_sentinel;
758 }
759 //}}}
760
761 // screen drawing routines {{{
762 void print_hi(int invert, int grey_bg, int bold, char* str) {
763 if (bold && op.s == &unicode_large_color){//ARGH! awful hack for bold with faint
764 int offset = str[3]==017?16:str[4]==017?17:0;
765 printf ("%s%s%s""%.*s%s%s""%s%s%s",
766 bold?"\033[1m":"", invert?"\033[7m":"", grey_bg?"\033[100m":"",
767 offset, str, bold?"\033[1m":"", str+offset,
768 grey_bg?"\033[49m":"", invert?"\033[27m":"",bold?"\033[22m":"");
769 return;
770 }
771 printf ("%s%s%s%s%s%s%s",
772 bold?"\033[1m":"", invert?"\033[7m":"", grey_bg?"\033[100m":"",
773 str,
774 grey_bg?"\033[49m":"", invert?"\033[27m":"",bold?"\033[22m":"");
775 }
776 void print_table(const struct cursor* active, const struct cursor* inactive) {
777 printf("\033[2J\033[H"); /* clear screen, reset cursor */
778 #ifdef KLONDIKE
779 /* print stock, waste and foundation: */
780 for (int line = 0; line < op.s->height; line++) {
781 /* stock: */
782 print_hi (active->pile == STOCK, inactive->pile == STOCK, 1, (
783 (f.w < f.z-1)?op.s->facedown
784 :op.s->placeholder)[line]);
785 /* waste: */
786 print_hi (active->pile == WASTE, inactive->pile == WASTE, 1, (
787 /* NOTE: cast, because f.w sometimes is (short)-1 !? */
788 ((short)f.w >= 0)?op.s->card[f.s[f.w]]
789 :op.s->placeholder)[line]);
790 printf ("%s", op.s->card[NO_CARD][line]); /* spacer */
791 /* foundation: */
792 for (int pile = 0; pile < NUM_SUITS; pile++) {
793 int card = find_top(f.f[pile]);
794 print_hi (active->pile==FOUNDATION && active->opt==pile,
795 inactive->pile==FOUNDATION && (
796 /* cursor addr. || direct addr. */
797 inactive->opt==pile || inactive->opt < 0
798 ), 1,
799 (card < 0)?op.s->placeholder[line]
800 :op.s->card[f.f[pile][card]][line]);
801 }
802 printf("\n");
803 }
804 printf("\n");
805 #elif defined SPIDER
806 int fdone; for (fdone = NUM_DECKS*NUM_SUITS; fdone; fdone--)
807 if (f.f[fdone-1][RANK_K]) break; /*number of completed stacks*/
808 int spacer_from = f.z?(f.z/10-1) * op.s->halfwidth[0] + op.s->width:0;
809 int spacer_to = NUM_PILES*op.s->width -
810 ((fdone?(fdone-1) * op.s->halfwidth[1]:0)+op.s->width);
811 for (int line = 0; line < op.s->height; line++) {
812 /* available stock: */
813 for (int i = f.z/10; i; i--) {
814 if (i==1) printf ("%s", op.s->facedown[line]);
815 else printf ("%s", op.s->halfstack[line]);
816 }
817 /* spacer: */
818 for (int i = spacer_from; i < spacer_to; i++) printf (" ");
819 /* foundation (overlapping): */
820 for (int i = 0; i < NUM_DECKS*NUM_SUITS; i++) { //TODO: print in revrse order (otherwise new piles get put 'below' older ones)
821 int overlap = i? op.s->halfcard[line]: 0;
822 if (f.f[i][RANK_K]) printf ("%.*s", op.s->halfwidth[2],
823 op.s->card[f.f[i][RANK_K]][line]+overlap);
824 }
825 printf("\n");
826 }
827 printf("\n");
828 #endif
829 #ifdef KLONDIKE
830 #define DO_HI(cursor) (cursor->pile == pile && (movable || empty))
831 #define TOP_HI(c) 1 /* can't select partial stacks in KLONDIKE */
832 #define INC_OFFSET
833 #elif defined SPIDER
834 int offset[NUM_PILES]={1,1,1,1,1,1,1,1,1,1}; // :|
835 #define DO_HI(cursor) (cursor->pile == pile && (movable || empty) \
836 && offset[pile] > cursor->opt)
837 #define TOP_HI(cursor) (cursor->pile == pile && movable \
838 && offset[pile]-1 == cursor->opt)
839 #define INC_OFFSET if (movable) offset[pile]++
840 #endif
841 /* print tableu piles: */
842 int row[NUM_PILES] = {0};
843 int line[NUM_PILES]= {0};
844 int label[NUM_PILES]={0};
845 int line_had_card;
846 int did_placeholders = 0;
847 do {
848 line_had_card = 0;
849 for (int pile = 0; pile < NUM_PILES; pile++) {
850 card_t card = f.t[pile][row[pile]];
851 card_t next = f.t[pile][row[pile]+1];
852 int movable = is_movable(f.t[pile], row[pile]);
853 int empty = !card && row[pile] == 0;
854
855 print_hi (DO_HI(active), DO_HI(inactive), movable, (
856 (!card && row[pile] == 0)?op.s->placeholder
857 :(card<0)?op.s->facedown
858 :op.s->card[card]
859 )[line[pile]]);
860
861 int extreme_overlap = ( 3 /* spacer, labels, status */
862 + 2 * op.s->height /* stock, top tableu card */
863 + find_top(f.t[pile]) * op.s->overlap) >op.w[0];
864 /* normal overlap: */
865 if (++line[pile] >= (next?op.s->overlap:op.s->height)
866 /* extreme overlap on closed cards: */
867 || (extreme_overlap &&
868 line[pile] >= 1 &&
869 f.t[pile][row[pile]] < 0 &&
870 f.t[pile][row[pile]+1] <0)
871 /* extreme overlap on sequences: */
872 || (extreme_overlap &&
873 !TOP_HI(active) && /*always show top selected card*/
874 line[pile] >= 1 && row[pile] > 0 &&
875 f.t[pile][row[pile]-1] > NO_CARD &&
876 is_consecutive (f.t[pile], row[pile]) &&
877 is_consecutive (f.t[pile], row[pile]-1) &&
878 f.t[pile][row[pile]+1] != NO_CARD)
879 ) {
880 line[pile]=0;
881 row[pile]++;
882 INC_OFFSET;
883 }
884 /* tableu labels: */
885 if(!card && !label[pile] && row[pile]>0&&line[pile]>0) {
886 label[pile] = 1;
887 printf ("\b\b%d ", (pile+1) % 10); //XXX: hack
888 }
889 line_had_card |= !!card;
890 did_placeholders |= row[pile] > 0;
891 }
892 printf ("\n");
893 } while (line_had_card || !did_placeholders);
894 }
895
896 void visbell (void) {
897 printf ("\033[?5h"); fflush (stdout);
898 usleep (100000);
899 printf ("\033[?5l"); fflush (stdout);
900 }
901 void win_anim(void) {
902 printf ("\033[?25l"); /* hide cursor */
903 for (;;) {
904 /* set cursor to random location */
905 int row = 1+random()%(24-op.s->width);
906 int col = 1+random()%(80-op.s->height);
907
908 /* draw random card */
909 int face = 1 + random() % 52;
910 for (int l = 0; l < op.s->height; l++) {
911 printf ("\033[%d;%dH", row+l, col);
912 printf ("%s", op.s->card[face][l]);
913 }
914 fflush (stdout);
915
916 /* exit on keypress */
917 struct pollfd p = {STDIN_FILENO, POLLIN, 0};
918 if (poll (&p, 1, 80)) goto fin;
919 }
920 fin:
921 printf ("\033[?25h"); /* show cursor */
922 return;
923 }
924 //}}}
925
926 // undo logic {{{
927 void undo_push (int _f, int t, int n, int o) {
928 struct undo* new = malloc(sizeof(struct undo));
929 new->f = _f;
930 new->t = t;
931 new->n = n;
932 new->o = o;
933 new->prev = f.u;
934 new->next = NULL;
935 f.u->next = new;
936 f.u = f.u->next;
937 }
938 void undo_pop (struct undo* u) {
939 if (u == &undo_sentinel) return;
940
941 #ifdef KLONDIKE
942 if (u->f == FOUNDATION) {
943 /* foundation -> tableu */
944 int top_f = find_top(f.f[u->n]);
945 int top_t = find_top(f.t[u->t]);
946 f.f[u->n][top_f+1] = f.t[u->t][top_t];
947 f.t[u->t][top_t] = NO_CARD;
948 } else if (u->f == WASTE && u->t == FOUNDATION) {
949 /* waste -> foundation */
950 /* split u->n into wst and fnd: */
951 int wst = u->n & 0xffff;
952 int fnd = u->n >> 16;
953 /* move stock cards one position up to make room: */
954 for (int i = f.z; i >= wst; i--) f.s[i+1] = f.s[i];
955 /* move one card from foundation to waste: */
956 int top = find_top(f.f[fnd]);
957 f.s[wst] = f.f[fnd][top];
958 f.f[fnd][top] = NO_CARD;
959 f.z++;
960 f.w++;
961 } else if (u->f == WASTE) {
962 /* waste -> tableu */
963 /* move stock cards one position up to make room: */
964 for (int i = f.z; i >= u->n; i--) f.s[i+1] = f.s[i];
965 /* move one card from tableu to waste: */
966 int top = find_top(f.t[u->t]);
967 f.s[u->n] = f.t[u->t][top];
968 f.t[u->t][top] = NO_CARD;
969 f.z++;
970 f.w++;
971 } else if (u->t == FOUNDATION) {
972 /* tableu -> foundation */
973 int top_f = find_top(f.t[u->f]);
974 int top_t = find_top(f.f[u->n]);
975 /* close topcard if previous action caused turn_over(): */
976 if (u->o) f.t[u->f][top_f] *= -1;
977 /* move one card from foundation to tableu: */
978 f.t[u->f][top_f+1] = f.f[u->n][top_t];
979 f.f[u->n][top_t] = NO_CARD;
980 } else {
981 /* tableu -> tableu */
982 int top_f = find_top(f.t[u->f]);
983 int top_t = find_top(f.t[u->t]);
984 /* close topcard if previous action caused turn_over(): */
985 if (u->o) f.t[u->f][top_f] *= -1;
986 /* move n cards from tableu[f] to tableu[t]: */
987 for (int i = 0; i < u->n; i++) {
988 f.t[u->f][top_f+u->n-i] = f.t[u->t][top_t-i];
989 f.t[u->t][top_t-i] = NO_CARD;
990 }
991 }
992 #elif defined SPIDER
993 if (u->f == STOCK) {
994 /* stock -> tableu */
995 /*remove a card from each pile and put it back onto the stock:*/
996 for (int pile = NUM_PILES-1; pile >= 0; pile--) {
997 int top = find_top(f.t[pile]);
998 f.s[f.z++] = f.t[pile][top];
999 f.t[pile][top] = NO_CARD;
1000 }
1001 } else if (u->t == FOUNDATION) {
1002 /* tableu -> foundation */
1003 int top = find_top(f.t[u->f]);
1004 /* close topcard if previous action caused turn_over(): */
1005 if (u->o) f.t[u->f][top] *= -1;
1006 /* append cards from foundation to tableu */
1007 for (int i = RANK_K; i >= RANK_A; i--) {
1008 f.t[u->f][++top] = f.f[u->n][i];
1009 f.f[u->n][i] = NO_CARD;
1010 }
1011 f.w--; /* decrement complete-foundation-counter */
1012
1013 } else {
1014 /* tableu -> tableu */
1015 int top_f = find_top(f.t[u->f]);
1016 int top_t = find_top(f.t[u->t]);
1017 /* close topcard if previous action caused turn_over(): */
1018 if (u->o) f.t[u->f][top_f] *= -1;
1019 /* move n cards from tableu[f] to tableu[t]: */
1020 for (int i = 0; i < u->n; i++) {
1021 f.t[u->f][top_f+u->n-i] = f.t[u->t][top_t-i];
1022 f.t[u->t][top_t-i] = NO_CARD;
1023 }
1024 }
1025 #endif
1026
1027 void* old = f.u;
1028 f.u = f.u->prev;
1029 free(old);
1030 }
1031 void free_undo (struct undo* u) {
1032 while (u && u != &undo_sentinel) {
1033 void* old = u;
1034 u = u->prev;
1035 free (old);
1036 }
1037 }
1038 //}}}
1039
1040 // initialization stuff {{{
1041 void screen_setup (int enable) {
1042 if (enable) {
1043 raw_mode(1);
1044 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
1045 printf ("\033[H\033[J"); /* reset cursor, clear screen */
1046 //TODO//printf ("\033[?1000h\033[?25l"); /* enable mouse, hide cursor */
1047 } else {
1048 //TODO//printf ("\033[?9l\033[?25h"); /* disable mouse, show cursor */
1049 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
1050 raw_mode(0);
1051 }
1052 }
1053
1054 void raw_mode(int enable) {
1055 static struct termios saved_term_mode;
1056 struct termios raw_term_mode;
1057
1058 if (enable) {
1059 if (saved_term_mode.c_lflag == 0)/*don't overwrite stored mode*/
1060 tcgetattr(STDIN_FILENO, &saved_term_mode);
1061 raw_term_mode = saved_term_mode;
1062 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
1063 raw_term_mode.c_cc[VMIN] = 1 ;
1064 raw_term_mode.c_cc[VTIME] = 0;
1065 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
1066 } else {
1067 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
1068 }
1069 }
1070
1071 void signal_handler (int signum) {
1072 struct winsize w;
1073 switch (signum) {
1074 case SIGCONT:
1075 screen_setup(0);
1076 screen_setup(1);
1077 print_table(NO_HI, NO_HI);
1078 break;
1079 case SIGINT: //TODO: don't exit; just warn like vim does
1080 exit(128+SIGINT);
1081 case SIGWINCH:
1082 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
1083 op.w[0] = w.ws_row;
1084 op.w[1] = w.ws_col;
1085 break;
1086 }
1087 }
1088 void signal_setup(void) {
1089 struct sigaction saction;
1090
1091 saction.sa_handler = signal_handler;
1092 sigemptyset(&saction.sa_mask);
1093 saction.sa_flags = 0;
1094 if (sigaction(SIGCONT, &saction, NULL) < 0) {
1095 perror ("SIGCONT");
1096 exit (1);
1097 }
1098 if (sigaction(SIGINT, &saction, NULL) < 0) {
1099 perror ("SIGINT");
1100 exit (1);
1101 }
1102 if (sigaction(SIGWINCH, &saction, NULL) < 0) {
1103 perror ("SIGWINCH");
1104 exit (1);
1105 }
1106 }
1107 //}}}
1108
1109 //vim: foldmethod=marker
Imprint / Impressum