]> git.gir.st - solVItaire.git/blob - sol.c
first version of join() -- to be replaced
[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
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: in spider, prefer same-suit cards if there is a tie
386 //TODO: in spider, prefer piles with less cards above our card. right
387 // now, this will often take from piles we've just constructed.
388 // also prefer to take from a pile if it results in an empty pile
389 // or a turn_over
390 //TODO: which pile to take from should form the basis of CMD_HINT
391
392 int top_to = find_top(f.t[to]); //TODO: handle empty
393 int from = -1;
394 int count = -1;
395
396 /* 1. find pile with largest number of useful movable cards: */
397 for (int pile = 0; pile < NUM_PILES; pile++) {
398 int tmp_count = 0;
399 int tmp_top = find_top(f.t[pile]);
400 /* backtrack until we find a compatible-to-'to'-pile card: */
401 while (tmp_top >= 0 && is_movable(f.t[pile], tmp_top)) {
402 int rankdiff = get_rank(f.t[pile][tmp_top]) - get_rank(f.t[to][top_to]);
403 tmp_count++;
404 if (rankdiff >= 0) break; /* past our card */
405 if (rankdiff == -1 //NOTE: could use rank_next()
406 #ifdef KLONDIKE
407 && get_color(f.t[pile][tmp_top]) != get_color(f.t[to][top_to])
408 #endif
409 && tmp_count > count) {
410 count = tmp_count;
411 from = pile;
412 }
413 tmp_top--;
414 }
415 }
416
417 if (from < 0) { /* nothing found */
418 #ifdef KLONDIKE /* check if we can take from waste before giving up */
419 return w2t(WASTE, to, 0);
420 #elif defined SPIDER
421 return ERR;
422 #endif
423 }
424
425 if (from == -1) return ERR; /* nothing found */
426
427 /* 2. move cards over and return: */
428 #ifdef KLONDIKE
429 return t2t(from, to, 0);
430 #elif defined SPIDER
431 int bottom = first_movable(f.t[from]);
432 return t2t(from, to, get_rank(f.t[from][bottom]));
433 #endif
434 }
435 int nop(int from, int to, int opt) { (void)from;(void)to;(void)opt;return ERR; }
436 // }}}
437
438 // keyboard input handling {{{
439 // cursor functions{{{
440 #pragma GCC diagnostic ignored "-Wswitch" //not ideal :|
441 #ifdef KLONDIKE
442 void cursor_left (struct cursor* cursor) {
443 if (is_tableu(cursor->pile)) {
444 if (cursor->pile > 0) cursor->pile--;
445 cursor->opt = 0;
446 } else { /* stock/waste/foundation*/
447 switch (cursor->pile) {
448 case WASTE: cursor->pile = STOCK; cursor->opt = 0; break;
449 case FOUNDATION:
450 if (cursor->opt <= 0)
451 cursor->pile = WASTE;
452 else
453 cursor->opt--;
454 }
455 }
456 }
457 void cursor_down (struct cursor* cursor) {
458 if (!is_tableu(cursor->pile)) {
459 switch (cursor->pile) {
460 case STOCK: cursor->pile = TAB_1; break;
461 case WASTE: cursor->pile = TAB_2; break;
462 case FOUNDATION:
463 cursor->pile = TAB_4 + cursor->opt;
464 }
465 cursor->opt = 0;
466 }
467 }
468 void cursor_up (struct cursor* cursor) {
469 if (is_tableu(cursor->pile)) {
470 switch (cursor->pile) { //ugly :|
471 case TAB_1: cursor->pile = STOCK; break;
472 case TAB_2: cursor->pile = WASTE; break;
473 case TAB_3: cursor->pile = WASTE; break;
474 case TAB_4: case TAB_5: case TAB_6: case TAB_7:
475 cursor->opt=cursor->pile-TAB_4;
476 cursor->pile = FOUNDATION;
477 break;
478 }
479 }
480 }
481 void cursor_right (struct cursor* cursor) {
482 if (is_tableu(cursor->pile)) {
483 if (cursor->pile < TAB_MAX) cursor->pile++;
484 } else {
485 switch (cursor->pile) {
486 case STOCK: cursor->pile = WASTE; break;
487 case WASTE: cursor->pile = FOUNDATION;cursor->opt = 0; break;
488 case FOUNDATION:
489 if (cursor->opt < NUM_DECKS*NUM_SUITS)
490 cursor->opt++;
491 }
492 }
493 }
494 #elif defined SPIDER
495 /*NOTE: one can't highlight the stock due to me being too lazy to implement it*/
496 void cursor_left (struct cursor* cursor) {
497 if (cursor->pile > 0) cursor->pile--;
498 cursor->opt = 0;
499 }
500 void cursor_down (struct cursor* cursor) {
501 int first = first_movable(f.t[cursor->pile]);
502 int top = find_top(f.t[cursor->pile]);
503 if (first + cursor->opt < top)
504 cursor->opt++;
505 }
506 void cursor_up (struct cursor* cursor) {
507 if (cursor->opt > 0) cursor->opt--;
508 }
509 void cursor_right (struct cursor* cursor) {
510 if (cursor->pile < TAB_MAX) cursor->pile++;
511 cursor->opt = 0;
512 }
513 #endif
514 void cursor_to (struct cursor* cursor, int pile) {
515 cursor->pile = pile;
516 cursor->opt = 0;
517 }
518 #pragma GCC diagnostic pop
519 //}}}
520 int get_cmd (int* from, int* to, int* opt) {
521 //TODO: escape sequences (mouse, cursor keys)
522 int _f, t;
523 struct cursor inactive = {-1,-1};
524 static struct cursor active = {0,0};
525 active.opt = 0; /* always reset offset, but keep pile */
526
527 /***/
528 from_l: print_table(&active, &inactive);
529 _f = getchar();
530
531 switch (_f) {
532 /* direct addressing: */
533 case '1': *from = TAB_1; break;
534 case '2': *from = TAB_2; break;
535 case '3': *from = TAB_3; break;
536 case '4': *from = TAB_4; break;
537 case '5': *from = TAB_5; break;
538 case '6': *from = TAB_6; break;
539 case '7': *from = TAB_7; break;
540 #ifdef SPIDER
541 case '8': *from = TAB_8; break;
542 case '9': *from = TAB_9; break;
543 case '0': *from = TAB_10;break;
544 #elif defined KLONDIKE
545 case '9': *from = WASTE; break;
546 case '0': *from = FOUNDATION; break;
547 case '8': /* fallthrough */
548 #endif
549 case '\n': /* shortcut for dealing from stock */
550 *from = STOCK;
551 *to = WASTE;
552 return CMD_MOVE;
553 /* cursor keys addressing: */
554 case 'h': cursor_left (&active); goto from_l;
555 case 'j': cursor_down (&active); goto from_l;
556 case 'k': cursor_up (&active); goto from_l;
557 case 'l': cursor_right(&active); goto from_l;
558 case 'H': cursor_to(&active,TAB_1); goto from_l; /* leftmost tableu */
559 case 'L': cursor_to(&active,TAB_MAX);goto from_l; /* rigthmost tableu */
560 case 'M': cursor_to(&active,TAB_MAX/2); goto from_l; /* center tableu */
561 //TODO: real cursor keys, home/end
562 case ' ': /* continue with second cursor */
563 *from = active.pile;
564 if (*from == STOCK) {
565 *to = WASTE;
566 return CMD_MOVE;
567 }
568 #ifdef KLONDIKE
569 *opt = active.opt; /* when FOUNDATION */
570 #endif
571 inactive = active;
572 break;
573 /* misc keys: */
574 case ':':
575 {char buf[256];
576 fprintf (stderr, ":");
577 raw_mode(0); /* turn on echo */
578 fgets (buf, 256, stdin);
579 raw_mode(1);
580 switch(buf[0]) {
581 case 'q': return CMD_QUIT;
582 case 'n': return CMD_NEW;
583 case 'r': return CMD_AGAIN;
584 default: return CMD_INVAL;
585 }}
586 case 'J':
587 *to = active.pile;
588 if (*to > TAB_MAX) return CMD_INVAL;
589 return CMD_JOIN;
590 case 'K': /* fallthrough */
591 case '?': return CMD_HINT;
592 case 'u': return CMD_UNDO;
593 case EOF: return CMD_NONE; /* sent by SIGCONT */
594 default: return CMD_INVAL;
595 }
596 inactive.pile = *from; /* for direct addressing highlighting */
597 if (is_tableu(*from) && f.t[*from][0] == NO_CARD) return CMD_INVAL;
598
599 /***/
600 to_l: print_table(&active, &inactive);
601 t = getchar();
602
603 switch (t) {
604 case 'h': cursor_left (&active); goto to_l;
605 case 'j': cursor_down (&active); goto to_l;
606 case 'k': cursor_up (&active); goto to_l;
607 case 'l': cursor_right(&active); goto to_l;
608 case 'H': cursor_to(&active,TAB_1); goto to_l;
609 case 'L': cursor_to(&active,TAB_MAX); goto to_l;
610 case 'M': cursor_to(&active,TAB_MAX/2); goto to_l;
611 case 'J': /* fallthrough; just join selected pile */
612 case ' ':
613 *to = active.pile;
614 break; /* continues with the foundation/empty tableu check */
615 case 'K': /* fallthrough */
616 case '?': return CMD_HINT;
617 case 'u': return CMD_NONE; /* cancel selection */
618 case EOF: return CMD_NONE; /* sent by SIGCONT */
619 default:
620 if (t < '0' || t > '9') return CMD_INVAL;
621 if (t == '0')
622 #ifdef KLONDIKE
623 *to = FOUNDATION;
624 #elif defined SPIDER
625 *to = TAB_10;
626 #endif
627 else
628 *to = t-'1';
629 }
630
631 /***/
632 #ifdef KLONDIKE
633 if (*from == FOUNDATION) {
634 int top = find_top(f.t[*to]);
635 if (top < 0) return CMD_INVAL;
636 int color = get_color(f.t[*to][top]);
637 int choice_1 = 1-color; /* selects piles of */
638 int choice_2 = 2+color; /* the opposite color */
639 int top_c1 = find_top(f.f[choice_1]);
640 int top_c2 = find_top(f.f[choice_2]);
641
642 switch ((rank_next(f.f[choice_1][top_c1], f.t[*to][top])
643 && top_c1 >= 0 ) << 0
644 |(rank_next(f.f[choice_2][top_c2], f.t[*to][top])
645 && top_c2 >= 0 ) << 1) {
646 case ( 1<<0): *opt = choice_1; break; /* choice_1 only */
647 case (1<<1 ): *opt = choice_2; break; /* choice_2 only */
648 case (1<<1 | 1<<0): /* both, ask user which to pick from */
649 printf ("take from (1-4): "); fflush (stdout);
650 *opt = getchar() - '1';
651 if (*opt < 0 || *opt > 3) return CMD_INVAL;
652 break;
653 default: return CMD_INVAL; /* none matched */
654 }
655 /* `opt` is the foundation index (0..3) */
656 }
657 #elif defined SPIDER
658 /* moving to empty tableu? */
659 if (is_tableu(*to) && f.t[*to][0] == NO_CARD) {
660 int bottom = first_movable(f.t[*from]);
661 if (inactive.opt >= 0) { /*if from was cursor addressed: */
662 *opt = get_rank(f.t[*from][bottom + inactive.opt]);
663 return CMD_MOVE;
664 }
665 int top = find_top(f.t[*from]);
666 if (top < 0) return CMD_INVAL;
667 if (top >= 0 && !is_movable(f.t[*from], top-1)) {
668 *opt = get_rank(f.t[*from][top]);
669 } else { /* only ask the user if it's unclear: */
670 printf ("\rup to ([a23456789xjqk] or space/return): ");
671 *opt = getchar();
672 switch (*opt) {
673 case ' ': *opt = get_rank(f.t[*from][top]); break;
674 case'\n': *opt = get_rank(f.t[*from][bottom]); break;
675 case 'a': case 'A': *opt = RANK_A; break;
676 case '0': /* fallthrough */
677 case 'x': case 'X': *opt = RANK_X; break;
678 case 'j': case 'J': *opt = RANK_J; break;
679 case 'q': case 'Q': *opt = RANK_Q; break;
680 case 'k': case 'K': *opt = RANK_K; break;
681 default: *opt -= '1';
682 }
683 if (*opt < RANK_A || *opt > RANK_K) return ERR;
684 }
685 /* `opt` is the rank of the highest card to move */
686 }
687 #endif
688 return CMD_MOVE;
689 }
690 // }}}
691
692 // shuffling and dealing {{{
693 void deal(void) {
694 f = (const struct playfield){0}; /* clear playfield */
695 card_t deck[DECK_SIZE*NUM_DECKS];
696 int avail = DECK_SIZE*NUM_DECKS;
697 for (int i = 0; i < DECK_SIZE*NUM_DECKS; i++) deck[i] = (i%DECK_SIZE)+1;
698 #ifdef SPIDER
699 if (op.m != NORMAL) for (int i = 0; i < DECK_SIZE*NUM_DECKS; i++) {
700 if (op.m == MEDIUM) deck[i] = 1+((deck[i]-1) | 2);
701 if (op.m == EASY) deck[i] = 1+((deck[i]-1) | 2 | 1);
702 /* the 1+ -1 dance gets rid of the offset created by NO_CARD */
703 }
704 #endif
705 srandom (time(NULL));
706 long seed = time(NULL);
707 srandom (seed);
708 for (int i = DECK_SIZE*NUM_DECKS-1; i > 0; i--) { /* fisher-yates */
709 int j = random() % (i+1);
710 if (j-i) deck[i]^=deck[j],deck[j]^=deck[i],deck[i]^=deck[j];
711 }
712
713 /* deal cards: */
714 for (int i = 0; i < NUM_PILES; i++) {
715 #ifdef KLONDIKE
716 int closed = i; /* pile n has n closed cards, then 1 open */
717 #elif defined SPIDER
718 int closed = i<4?5:4; /* pile 1-4 have 5, 5-10 have 4 closed */
719 #endif
720 /* face down cards are negated: */
721 for (int j = 0; j < closed; j++) f.t[i][j] = -deck[--avail];
722 f.t[i][closed] = deck[--avail]; /* the face-up card */
723 }
724 /* rest of the cards to the stock; NOTE: assert(avail==50) for spider */
725 for (f.z = 0; avail; f.z++) f.s[f.z] = deck[--avail];
726 #ifdef KLONDIKE
727 f.w = -1; /* @start: nothing on waste */
728 #elif defined SPIDER
729 f.w = 0; /* number of used foundations */
730 #endif
731
732 f.u = &undo_sentinel;
733 }
734 //}}}
735
736 // screen drawing routines {{{
737 void print_hi(int invert, int grey_bg, int bold, char* str) {
738 if (bold && op.s == &unicode_large_color){//ARGH! awful hack for bold with faint
739 int offset = str[3]==017?16:str[4]==017?17:0;
740 printf ("%s%s%s""%.*s%s%s""%s%s%s",
741 bold?"\033[1m":"", invert?"\033[7m":"", grey_bg?"\033[100m":"",
742 offset, str, bold?"\033[1m":"", str+offset,
743 grey_bg?"\033[49m":"", invert?"\033[27m":"",bold?"\033[22m":"");
744 return;
745 }
746 printf ("%s%s%s%s%s%s%s",
747 bold?"\033[1m":"", invert?"\033[7m":"", grey_bg?"\033[100m":"",
748 str,
749 grey_bg?"\033[49m":"", invert?"\033[27m":"",bold?"\033[22m":"");
750 }
751 void print_table(const struct cursor* active, const struct cursor* inactive) {
752 printf("\033[2J\033[H"); /* clear screen, reset cursor */
753 #ifdef KLONDIKE
754 /* print stock, waste and foundation: */
755 for (int line = 0; line < op.s->height; line++) {
756 /* stock: */
757 print_hi (active->pile == STOCK, inactive->pile == STOCK, 1, (
758 (f.w < f.z-1)?op.s->facedown
759 :op.s->placeholder)[line]);
760 /* waste: */
761 print_hi (active->pile == WASTE, inactive->pile == WASTE, 1, (
762 /* NOTE: cast, because f.w sometimes is (short)-1 !? */
763 ((short)f.w >= 0)?op.s->card[f.s[f.w]]
764 :op.s->placeholder)[line]);
765 printf ("%s", op.s->card[NO_CARD][line]); /* spacer */
766 /* foundation: */
767 for (int pile = 0; pile < NUM_SUITS; pile++) {
768 int card = find_top(f.f[pile]);
769 print_hi (active->pile==FOUNDATION && active->opt==pile,
770 inactive->pile==FOUNDATION && (
771 /* cursor addr. || direct addr. */
772 inactive->opt==pile || inactive->opt < 0
773 ), 1,
774 (card < 0)?op.s->placeholder[line]
775 :op.s->card[f.f[pile][card]][line]);
776 }
777 printf("\n");
778 }
779 printf("\n");
780 #elif defined SPIDER
781 int fdone; for (fdone = NUM_DECKS*NUM_SUITS; fdone; fdone--)
782 if (f.f[fdone-1][RANK_K]) break; /*number of completed stacks*/
783 int spacer_from = f.z?(f.z/10-1) * op.s->halfwidth[0] + op.s->width:0;
784 int spacer_to = NUM_PILES*op.s->width -
785 ((fdone?(fdone-1) * op.s->halfwidth[1]:0)+op.s->width);
786 for (int line = 0; line < op.s->height; line++) {
787 /* available stock: */
788 for (int i = f.z/10; i; i--) {
789 if (i==1) printf ("%s", op.s->facedown[line]);
790 else printf ("%s", op.s->halfstack[line]);
791 }
792 /* spacer: */
793 for (int i = spacer_from; i < spacer_to; i++) printf (" ");
794 /* foundation (overlapping): */
795 for (int i = 0; i < NUM_DECKS*NUM_SUITS; i++) { //TODO: print in revrse order (otherwise new piles get put 'below' older ones)
796 int overlap = i? op.s->halfcard[line]: 0;
797 if (f.f[i][RANK_K]) printf ("%.*s", op.s->halfwidth[2],
798 op.s->card[f.f[i][RANK_K]][line]+overlap);
799 }
800 printf("\n");
801 }
802 printf("\n");
803 #endif
804 #ifdef KLONDIKE
805 #define DO_HI(cursor) (cursor->pile == pile && (movable || empty))
806 #define TOP_HI(c) 1 /* can't select partial stacks in KLONDIKE */
807 #define INC_OFFSET
808 #elif defined SPIDER
809 int offset[NUM_PILES]={1,1,1,1,1,1,1,1,1,1}; // :|
810 #define DO_HI(cursor) (cursor->pile == pile && (movable || empty) \
811 && offset[pile] > cursor->opt)
812 #define TOP_HI(cursor) (cursor->pile == pile && movable \
813 && offset[pile]-1 == cursor->opt)
814 #define INC_OFFSET if (movable) offset[pile]++
815 #endif
816 /* print tableu piles: */
817 int row[NUM_PILES] = {0};
818 int line[NUM_PILES]= {0};
819 int label[NUM_PILES]={0};
820 int line_had_card;
821 int did_placeholders = 0;
822 do {
823 line_had_card = 0;
824 for (int pile = 0; pile < NUM_PILES; pile++) {
825 card_t card = f.t[pile][row[pile]];
826 card_t next = f.t[pile][row[pile]+1];
827 int movable = is_movable(f.t[pile], row[pile]);
828 int empty = !card && row[pile] == 0;
829
830 print_hi (DO_HI(active), DO_HI(inactive), movable, (
831 (!card && row[pile] == 0)?op.s->placeholder
832 :(card<0)?op.s->facedown
833 :op.s->card[card]
834 )[line[pile]]);
835
836 int extreme_overlap = ( 3 /* spacer, labels, status */
837 + 2 * op.s->height /* stock, top tableu card */
838 + find_top(f.t[pile]) * op.s->overlap) >op.w[0];
839 /* normal overlap: */
840 if (++line[pile] >= (next?op.s->overlap:op.s->height)
841 /* extreme overlap on closed cards: */
842 || (extreme_overlap &&
843 line[pile] >= 1 &&
844 f.t[pile][row[pile]] < 0 &&
845 f.t[pile][row[pile]+1] <0)
846 /* extreme overlap on sequences: */
847 || (extreme_overlap &&
848 !TOP_HI(active) && /*always show top selected card*/
849 line[pile] >= 1 && row[pile] > 0 &&
850 f.t[pile][row[pile]-1] > NO_CARD &&
851 is_consecutive (f.t[pile], row[pile]) &&
852 is_consecutive (f.t[pile], row[pile]-1) &&
853 f.t[pile][row[pile]+1] != NO_CARD)
854 ) {
855 line[pile]=0;
856 row[pile]++;
857 INC_OFFSET;
858 }
859 /* tableu labels: */
860 if(!card && !label[pile] && row[pile]>0&&line[pile]>0) {
861 label[pile] = 1;
862 printf ("\b\b%d ", (pile+1) % 10); //XXX: hack
863 }
864 line_had_card |= !!card;
865 did_placeholders |= row[pile] > 0;
866 }
867 printf ("\n");
868 } while (line_had_card || !did_placeholders);
869 }
870
871 void visbell (void) {
872 printf ("\033[?5h"); fflush (stdout);
873 usleep (100000);
874 printf ("\033[?5l"); fflush (stdout);
875 }
876 void win_anim(void) {
877 printf ("\033[?25l"); /* hide cursor */
878 for (;;) {
879 /* set cursor to random location */
880 int row = 1+random()%(24-op.s->width);
881 int col = 1+random()%(80-op.s->height);
882
883 /* draw random card */
884 int face = 1 + random() % 52;
885 for (int l = 0; l < op.s->height; l++) {
886 printf ("\033[%d;%dH", row+l, col);
887 printf ("%s", op.s->card[face][l]);
888 }
889 fflush (stdout);
890
891 /* exit on keypress */
892 struct pollfd p = {STDIN_FILENO, POLLIN, 0};
893 if (poll (&p, 1, 80)) goto fin;
894 }
895 fin:
896 printf ("\033[?25h"); /* show cursor */
897 return;
898 }
899 //}}}
900
901 // undo logic {{{
902 void undo_push (int _f, int t, int n, int o) {
903 struct undo* new = malloc(sizeof(struct undo));
904 new->f = _f;
905 new->t = t;
906 new->n = n;
907 new->o = o;
908 new->prev = f.u;
909 new->next = NULL;
910 f.u->next = new;
911 f.u = f.u->next;
912 }
913 void undo_pop (struct undo* u) {
914 if (u == &undo_sentinel) return;
915
916 #ifdef KLONDIKE
917 if (u->f == FOUNDATION) {
918 /* foundation -> tableu */
919 int top_f = find_top(f.f[u->n]);
920 int top_t = find_top(f.t[u->t]);
921 f.f[u->n][top_f+1] = f.t[u->t][top_t];
922 f.t[u->t][top_t] = NO_CARD;
923 } else if (u->f == WASTE && u->t == FOUNDATION) {
924 /* waste -> foundation */
925 /* split u->n into wst and fnd: */
926 int wst = u->n & 0xffff;
927 int fnd = u->n >> 16;
928 /* move stock cards one position up to make room: */
929 for (int i = f.z; i >= wst; i--) f.s[i+1] = f.s[i];
930 /* move one card from foundation to waste: */
931 int top = find_top(f.f[fnd]);
932 f.s[wst] = f.f[fnd][top];
933 f.f[fnd][top] = NO_CARD;
934 f.z++;
935 f.w++;
936 } else if (u->f == WASTE) {
937 /* waste -> tableu */
938 /* move stock cards one position up to make room: */
939 for (int i = f.z; i >= u->n; i--) f.s[i+1] = f.s[i];
940 /* move one card from tableu to waste: */
941 int top = find_top(f.t[u->t]);
942 f.s[u->n] = f.t[u->t][top];
943 f.t[u->t][top] = NO_CARD;
944 f.z++;
945 f.w++;
946 } else if (u->t == FOUNDATION) {
947 /* tableu -> foundation */
948 int top_f = find_top(f.t[u->f]);
949 int top_t = find_top(f.f[u->n]);
950 /* close topcard if previous action caused turn_over(): */
951 if (u->o) f.t[u->f][top_f] *= -1;
952 /* move one card from foundation to tableu: */
953 f.t[u->f][top_f+1] = f.f[u->n][top_t];
954 f.f[u->n][top_t] = NO_CARD;
955 } else {
956 /* tableu -> tableu */
957 int top_f = find_top(f.t[u->f]);
958 int top_t = find_top(f.t[u->t]);
959 /* close topcard if previous action caused turn_over(): */
960 if (u->o) f.t[u->f][top_f] *= -1;
961 /* move n cards from tableu[f] to tableu[t]: */
962 for (int i = 0; i < u->n; i++) {
963 f.t[u->f][top_f+u->n-i] = f.t[u->t][top_t-i];
964 f.t[u->t][top_t-i] = NO_CARD;
965 }
966 }
967 #elif defined SPIDER
968 if (u->f == STOCK) {
969 /* stock -> tableu */
970 /*remove a card from each pile and put it back onto the stock:*/
971 for (int pile = NUM_PILES-1; pile >= 0; pile--) {
972 int top = find_top(f.t[pile]);
973 f.s[f.z++] = f.t[pile][top];
974 f.t[pile][top] = NO_CARD;
975 }
976 } else if (u->t == FOUNDATION) {
977 /* tableu -> foundation */
978 int top = find_top(f.t[u->f]);
979 /* close topcard if previous action caused turn_over(): */
980 if (u->o) f.t[u->f][top] *= -1;
981 /* append cards from foundation to tableu */
982 for (int i = RANK_K; i >= RANK_A; i--) {
983 f.t[u->f][++top] = f.f[u->n][i];
984 f.f[u->n][i] = NO_CARD;
985 }
986 f.w--; /* decrement complete-foundation-counter */
987
988 } else {
989 /* tableu -> tableu */
990 int top_f = find_top(f.t[u->f]);
991 int top_t = find_top(f.t[u->t]);
992 /* close topcard if previous action caused turn_over(): */
993 if (u->o) f.t[u->f][top_f] *= -1;
994 /* move n cards from tableu[f] to tableu[t]: */
995 for (int i = 0; i < u->n; i++) {
996 f.t[u->f][top_f+u->n-i] = f.t[u->t][top_t-i];
997 f.t[u->t][top_t-i] = NO_CARD;
998 }
999 }
1000 #endif
1001
1002 void* old = f.u;
1003 f.u = f.u->prev;
1004 free(old);
1005 }
1006 void free_undo (struct undo* u) {
1007 while (u && u != &undo_sentinel) {
1008 void* old = u;
1009 u = u->prev;
1010 free (old);
1011 }
1012 }
1013 //}}}
1014
1015 // initialization stuff {{{
1016 void screen_setup (int enable) {
1017 if (enable) {
1018 raw_mode(1);
1019 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
1020 printf ("\033[H\033[J"); /* reset cursor, clear screen */
1021 //TODO//printf ("\033[?1000h\033[?25l"); /* enable mouse, hide cursor */
1022 } else {
1023 //TODO//printf ("\033[?9l\033[?25h"); /* disable mouse, show cursor */
1024 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
1025 raw_mode(0);
1026 }
1027 }
1028
1029 void raw_mode(int enable) {
1030 static struct termios saved_term_mode;
1031 struct termios raw_term_mode;
1032
1033 if (enable) {
1034 if (saved_term_mode.c_lflag == 0)/*don't overwrite stored mode*/
1035 tcgetattr(STDIN_FILENO, &saved_term_mode);
1036 raw_term_mode = saved_term_mode;
1037 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
1038 raw_term_mode.c_cc[VMIN] = 1 ;
1039 raw_term_mode.c_cc[VTIME] = 0;
1040 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
1041 } else {
1042 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
1043 }
1044 }
1045
1046 void signal_handler (int signum) {
1047 struct winsize w;
1048 switch (signum) {
1049 case SIGCONT:
1050 screen_setup(0);
1051 screen_setup(1);
1052 print_table(NO_HI, NO_HI);
1053 break;
1054 case SIGINT: //TODO: don't exit; just warn like vim does
1055 exit(128+SIGINT);
1056 case SIGWINCH:
1057 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
1058 op.w[0] = w.ws_row;
1059 op.w[1] = w.ws_col;
1060 break;
1061 }
1062 }
1063 void signal_setup(void) {
1064 struct sigaction saction;
1065
1066 saction.sa_handler = signal_handler;
1067 sigemptyset(&saction.sa_mask);
1068 saction.sa_flags = 0;
1069 if (sigaction(SIGCONT, &saction, NULL) < 0) {
1070 perror ("SIGCONT");
1071 exit (1);
1072 }
1073 if (sigaction(SIGINT, &saction, NULL) < 0) {
1074 perror ("SIGINT");
1075 exit (1);
1076 }
1077 if (sigaction(SIGWINCH, &saction, NULL) < 0) {
1078 perror ("SIGWINCH");
1079 exit (1);
1080 }
1081 }
1082 //}}}
1083
1084 //vim: foldmethod=marker
Imprint / Impressum