]> git.gir.st - minesVIiper.git/blob - mines.c
add compile time flag 'FLAGALL_ON_CHOORD'
[minesVIiper.git] / mines.c
1 /*******************************************************************************
2 minesviiper 0.5
3 By Tobias Girstmair, 2015 - 2018
4
5 ./minesviiper 16x16x40
6 (see ./minesviiper -h for full list of options)
7
8 MOUSE MODE: - left click to open and choord
9 - right click to flag/unflag
10 VI MODE: - hjkl to move cursor left/down/up/right
11 - o/space to open and choord
12 - i to flag/unflag
13 - (see `./minesviiper -h' for all keybindings)
14
15 GNU GPL v3, see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt
16 *******************************************************************************/
17
18
19 #define _POSIX_C_SOURCE 2 /*for getopt, sigaction in c99*/
20 #include <ctype.h>
21 #include <poll.h>
22 #include <signal.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <sys/ioctl.h>
27 #include <sys/time.h>
28 #include <termios.h>
29 #include <time.h>
30 #include <unistd.h>
31
32 #include "mines.h"
33 #include "schemes.h"
34
35 #define LINE_OFFSET 3
36 #define LINES_AFTER 2
37 #define COL_OFFSET 2
38 #define BIG_MOVE 5
39 #define MOUSE_MAX 231
40 #define STOMP_TIMEOUT 150 /*ms*/
41
42 #define MIN(a,b) (a>b?b:a)
43 #define MAX(a,b) (a>b?a:b)
44 #define CLAMP(a,m,M) (a<m?m:(a>M?M:a))
45 #define printm(n, s) for (int _loop = 0; _loop < n; _loop++) fputs (s, stdout)
46 #define print(str) fputs (str?str:"", stdout)
47 #define EMOT(e) op.scheme->emoticons[EMOT_ ## e]
48 #define BORDER(l, c) op.scheme->border[B_ ## l][B_ ## c]
49 #define CW op.scheme->cell_width /* for brevity */
50 #define DW op.scheme->display_width /* ditto. */
51 #define HI_CELL f.c[g.p[0]][g.p[1]]
52 #define LINE_BELOW LINE_OFFSET+f.h-1+LINES_AFTER
53 #define CTRL_ 0x1F &
54
55 #define AR_CELL f.c[ROW][COL] /* helper for AROUND() */
56 #define AROUND(l, c) /* gives us loop-variables ROW, COL, AR_CELL */ \
57 for (int ROW = MAX(l-1, 0); ROW <= MIN(l+1, f.h-1); ROW++) \
58 for (int COL = MAX(c-1, 0); COL <= MIN(c+1, f.w-1); COL++) \
59 if (!(ROW == l && COL == c)) /* skip itself */
60
61 #define PAUSE_TIMER \
62 for (int _break=(timer_setup(0),1); _break; _break=0, timer_setup(g.t))
63
64 struct minefield f;
65 struct game g;
66 struct opt op;
67
68 int main (int argc, char** argv) {
69 /* defaults: */
70 f.w = 30;
71 f.h = 16;
72 f.m = 99;
73 op.scheme = &symbols_mono;
74 op.mode = FLAG;
75
76 int optget;
77 opterr = 0; /* don't print message on unrecognized option */
78 while ((optget = getopt (argc, argv, "+hnfqbcd")) != -1) {
79 switch (optget) {
80 case 'n': op.mode = NOFLAG; break;
81 case 'f': op.mode = FLAG; break; /*default*/
82 case 'q': op.mode = QUESM; break; /*WARN:implicitly sets -f*/
83 case 'b': op.scheme = &symbols_mono; break;
84 case 'c': op.scheme = &symbols_col1; break;
85 case 'd': op.scheme = &symbols_doublewidth; break;
86 case 'h':
87 default:
88 fprintf (stderr, SHORTHELP LONGHELP KEYHELP, argv[0]);
89 return !(optget=='h');
90 }
91 } if (optind < argc) { /* parse Fieldspec */
92 if (parse_fieldspec (argv[optind])) {
93 fprintf (stderr, SHORTHELP FIELDHELP, argv[0]);
94 return 1;
95 }
96 }
97
98 signal_setup();
99 atexit (*quit);
100
101 newgame:
102 screen_setup(1);
103 switch (g.o = minesviiper()) {
104 case GAME_NEW: goto newgame;
105 case GAME_WON: goto game_end;
106 case GAME_LOST:goto game_end;
107 case GAME_QUIT:goto quit;
108 }
109
110 game_end:
111 timer_setup(0); /* stop timer */
112 int show_how = g.o==GAME_WON?SHOWFLAGS:SHOWMINES;
113 show_minefield (show_how);
114 for(;;) {
115 switch(getch_wrapper()) {
116 case WRAPPER_EMOTICON:
117 case 'r': goto newgame;
118 case 'q': goto quit;
119 case CTRL_'L':
120 /*WARN: updates the timer (would require fix in struct*/
121 screen_setup(1);
122 show_minefield (show_how);
123 break;
124 case CTRL_'R':
125 interactive_resize();
126 goto newgame;
127 }
128 }
129
130 quit:
131 return 0;
132 }
133
134 int minesviiper(void) {
135 f.c = alloc_array (f.h, f.w);
136 g = (const struct game){0}; /* reset all game-specific parameters */
137
138 show_minefield (NORMAL);
139
140 for(;;) {
141 int actor = KEYBOARD; /* WARN: feels like a hack :| */
142 switch (getch_wrapper()) {
143 case ' ':
144 if (HI_CELL.o == OPENED) goto open_cell;
145 if (g.s == MODE_OPEN) goto open_cell;
146 if (g.s == MODE_FLAG) goto flag_cell;
147 if (g.s == MODE_QUESM) goto quesm_cell;
148 break;
149 case 's':
150 g.s = (g.s+1)%(op.mode+1);
151 show_minefield (NORMAL);
152 break;
153 case CTRSEQ_MOUSE_LEFT:
154 actor = MOUSE;
155 /* fallthrough */
156 open_cell:
157 case 'o':
158 switch (do_uncover(&(g.n), actor)) {
159 case GAME_LOST: return GAME_LOST;
160 case GAME_WON: return GAME_WON;
161 }
162 break;
163 flag_cell:
164 case CTRSEQ_MOUSE_RIGHT:
165 case 'i': flag_square (g.p[0], g.p[1]); break;
166 quesm_cell:
167 case '?':quesm_square (g.p[0], g.p[1]); break;
168 case CTRSEQ_CURSOR_LEFT:
169 case 'h': move_hi (g.p[0], g.p[1]-1); break;
170 case CTRSEQ_CURSOR_DOWN:
171 case 'j': move_hi (g.p[0]+1, g.p[1] ); break;
172 case CTRSEQ_CURSOR_UP:
173 case 'k': move_hi (g.p[0]-1, g.p[1] ); break;
174 case CTRSEQ_CURSOR_RIGHT:
175 case 'l': move_hi (g.p[0], g.p[1]+1); break;
176 //TODO: W, B, U, D (bigword: only consider open/close state)
177 case 'w': to_next_boundary (g.p[0], g.p[1], '>'); break;
178 case 'b': to_next_boundary (g.p[0], g.p[1], '<'); break;
179 case 'u': to_next_boundary (g.p[0], g.p[1], '^'); break;
180 case 'd': to_next_boundary (g.p[0], g.p[1], 'v'); break;
181 case 'e': to_next_boundary (g.p[0], g.p[1], '>'); break;
182 case '0': /* fallthrough */
183 case '^': move_hi (g.p[0], 0 ); break;
184 case '$': move_hi (g.p[0], f.w-1 ); break;
185 case 'g': move_hi (0, g.p[1]); break;
186 case 'G': move_hi (f.h-1, g.p[1]); break;
187 case 'z': move_hi (f.h/2, f.w/2 ); break;
188 case 'm': set_mark(); break;
189 case'\'': /* fallthrough */
190 case '`': jump_mark(); break;
191 case 'f': find(getch_wrapper(), '>', 0); break;
192 case 'F': find(getch_wrapper(), '<', 0); break;
193 case 't': find(getch_wrapper(), '>',-1); break;
194 case 'T': find(getch_wrapper(), '<',-1); break;
195 case 'a': find(getch_wrapper(), '>',+1); break;
196 case 'A': find(getch_wrapper(), '<',+1); break;
197 //TODO: HJKL, ^H^J^K^L: <spacemode> up/down/left/right/45deg
198 //TODO: ;, (repeat last find/till/after)
199 case '!': grand_opening(&(g.n)); break;
200 case WRAPPER_EMOTICON:
201 case ':':
202 switch (ex_cmd()) {
203 case EX_QUIT: return GAME_QUIT;
204 case EX_NEW: timer_setup(0); return GAME_NEW;
205 case EX_HELP: printf (KEYHELP); break; //TODO: charset problems with vt220
206 case EX_RESZ:
207 timer_setup(0);
208 interactive_resize();
209 return GAME_NEW;
210 default:
211 printf ("\rinvalid command");
212 PAUSE_TIMER ungetc(getchar(), stdin);
213 printf("\033[2K"); /* clear line */
214 }
215 break;
216 case 'q': //TODO: redefine `q' as macro functionality
217 break;
218 case CTRL_'L':
219 screen_setup(1);
220 show_minefield (NORMAL);
221 break;
222 case '\\':
223 if (g.n == GAME_NEW) break; /* must open a cell first */
224 show_minefield (SHOWMINES);
225 wait_keypress(400);
226 show_minefield (NORMAL);
227 break;
228 }
229 }
230
231 }
232
233 void quit (void) {
234 screen_setup(0);
235 free_field ();
236 }
237
238 /* I haven't won as long as a cell exists, that
239 - I haven't opened, and
240 - is not a mine */
241 int everything_opened (void) {
242 for (int row = 0; row < f.h; row++)
243 for (int col = 0; col < f.w; col++)
244 if (f.c[row][col].o == CLOSED &&
245 f.c[row][col].m == NO_MINE ) return 0;
246 return 1;
247 }
248
249 int wait_mouse_up (int l, int c) {
250 unsigned char mouse2[3];
251 int level = 1;
252 int l2, c2;
253
254 /* show :o face */
255 move_ph (1, field2screen_c (f.w/2)-1); print (EMOT(OHH));
256
257 if (!(l < 0 || l >= f.h || c < 0 || c >= f.w)) {
258 /* remove keyboard's cursor (if it's there): */
259 redraw_cell (g.p[0], g.p[1], NORMAL);
260 /* show a pushed-in button if cursor is on minefield */
261 redraw_cell (l, c, HIGHLIGHT);
262
263 show_stomp(1, l, c);
264 }
265
266 while (level > 0) {
267 if (getctrlseq (mouse2) == CTRSEQ_MOUSE) {
268 /* ignore mouse wheel events: */
269 if (mouse2[0] & 0x40) continue;
270
271 else if((mouse2[0]&3) == 3) level--; /* release event */
272 else level++; /* another button pressed */
273 }
274 }
275
276 move_ph (1, field2screen_c (f.w/2)-1); print (get_emoticon());
277
278 if (!(l < 0 || l >= f.h || c < 0 || c >= f.w)) {
279 redraw_cell (l, c, g.o?SHOWMINES:NORMAL);
280 show_stomp(0, l, c);
281 }
282 c2 = screen2field_c(mouse2[1]);
283 l2 = screen2field_l(mouse2[2]);
284 return ((l2 == l) && (c2 == c));
285 }
286
287 void flagall_square (int line, int col) {
288 AROUND(line,col)
289 if (AR_CELL.f != FLAG) {
290 flag_square(ROW, COL);
291 }
292 }
293
294 int choord_square (int line, int col) {
295 AROUND(line,col)
296 if (AR_CELL.f != FLAG) {
297 if (uncover_square (ROW, COL))
298 return 1;
299 }
300
301 return 0;
302 }
303
304 int uncover_square (int l, int c) {
305 if (f.c[l][c].o == OPENED)
306 return 0; /* nothing to do */
307
308 f.c[l][c].o = OPENED;
309 f.c[l][c].f = NOFLAG; /*must not be QUESM, otherwise rendering issues*/
310 redraw_cell (l, c, NORMAL);
311
312 if (f.c[l][c].m) {
313 f.c[l][c].m = DEATH_MINE;
314 return 1;
315 }
316
317 /* check for chording */
318 if (f.c[l][c].n == 0) {
319 AROUND(l, c)
320 if (uncover_square (ROW, COL)) return 1;
321 }
322
323 return 0;
324 }
325
326 void flag_square (int l, int c) {
327 static char modechar[] = {'*', '!', '?'};
328
329 if (f.c[l][c].o != CLOSED) return;
330 /* cycle through flag/quesm/noflag: */
331 f.c[l][c].f = (f.c[l][c].f + 1) % (op.mode + 1);
332 if (f.c[l][c].f==FLAG) g.f++;
333 else if ((op.mode==FLAG && f.c[l][c].f==NOFLAG) ||
334 (op.mode==QUESM && f.c[l][c].f==QUESM)) g.f--;
335 redraw_cell (l, c, NORMAL);
336 move_ph (1, op.scheme->cell_width);
337 printf ("[%03d%c]", f.m - g.f, modechar[g.s]);
338 }
339
340 void quesm_square (int l, int c) {
341 /* toggle question mark / none. won't turn flags into question marks.
342 unlike flag_square, this function doesn't respect `-q'. */
343 if (f.c[l][c].o != CLOSED) return;
344 else if (f.c[l][c].f == NOFLAG) f.c[l][c].f = QUESM;
345 else if (f.c[l][c].f == QUESM) f.c[l][c].f = NOFLAG;
346 redraw_cell (l, c, NORMAL);
347 }
348
349 int do_uncover (int* is_newgame, int actor) {
350 if (*is_newgame == GAME_NEW) {
351 *is_newgame = GAME_INPROGRESS;
352 fill_minefield (g.p[0], g.p[1]);
353 timer_setup(1);
354 }
355
356 #ifdef COORD_ON_FLAG
357 if (HI_CELL.f == FLAG ) {
358 if (choord_square(g.p[0], g.p[1])) return GAME_LOST;
359 else return GAME_INPROGRESS;
360 }
361 #else
362 if (HI_CELL.f == FLAG ) return GAME_INPROGRESS;
363 #endif
364 if (HI_CELL.o == CLOSED) {
365 if (uncover_square (g.p[0], g.p[1])) return GAME_LOST;
366 } else if (get_neighbours (g.p[0], g.p[1], 1) == 0) {
367 if (choord_square (g.p[0], g.p[1])) return GAME_LOST;
368 #ifdef FLAGALL_ON_CHOORD
369 } else if (HI_CELL.n == closed_neighbours(g.p[0], g.p[1])) {
370 flagall_square(g.p[0], g.p[1]);
371 #endif
372 } else if (actor != MOUSE) {
373 show_stomp(1, g.p[0], g.p[1]);
374
375 wait_keypress(STOMP_TIMEOUT);
376
377 show_stomp(0, g.p[0], g.p[1]);
378 }
379 if (everything_opened()) return GAME_WON;
380
381 return GAME_INPROGRESS;
382 }
383
384 #define for_each_cell(r, c) \
385 for (int r = 0; r < f.h; r++) for (int c = 0; c < f.w; c++)
386 int grand_opening(int* is_newgame) {
387 /* Find the largest cluster of zero-cells and open it. This is a bad
388 implementation of a connected-component labelling algorithm and also
389 uses (gasp!) VLAs! */
390
391 if (*is_newgame == GAME_NEW) {
392 *is_newgame = GAME_INPROGRESS;
393 fill_minefield (-1, -1);
394 timer_setup(1);
395 } else return GAME_INPROGRESS; /* only allow this as the first move */
396
397 int clusters[f.h*f.w]; /* each 0-cell gets labelled with a cluster */
398 int cluster_id = 1; /* number. connected cells get the same. */
399 int largest = 1; /* the largest cluster will then be opened. */
400 memset(clusters, 0, f.h*f.w * sizeof(int));
401
402 /* assign cluster numbers: */
403 for_each_cell(r, c) {
404 if (assign_cluster(r, c, cluster_id, clusters))
405 cluster_id++;
406 }
407
408 /* calculate cluster sizes: */
409 int id_size[cluster_id];
410 memset(id_size, 0, cluster_id * sizeof(int));
411 for_each_cell(r, c)
412 id_size[ clusters[r*f.w+c] ]++;
413
414 /* find largest cluster and open it: */
415 for (int i = 1; i < cluster_id; i++)
416 if (id_size[i] > id_size[largest])
417 largest = i;
418 for_each_cell(r, c) {
419 if (clusters[r*f.w+c] == largest) {
420 g.p[0] = r;
421 g.p[1] = c;
422 return do_uncover(is_newgame, KEYBOARD);
423 }
424 }
425
426 return GAME_INPROGRESS; /* that shouln't ever happen(TM) */
427 }
428 #undef for_each_cell
429 int assign_cluster(int r, int c, int id, int *clusters) {
430 int tagged = 0;
431
432 if (clusters[r*f.w+c] > 0 /* already tagged */
433 || f.c[r][c].n > 0 /* cell not empty */
434 || f.c[r][c].m /* cell has mine */
435 || f.c[r][c].o ) /* cell already open */
436 return tagged;
437
438 /* else, tag the cell and its neighbours */
439
440 clusters[r*f.w+c] = id; tagged++;
441 AROUND(r, c)
442 tagged+= assign_cluster(ROW, COL, id, clusters);
443
444 return tagged;
445 }
446
447 int ex_cmd(void) {
448 char what[256];
449 printf ("\033[?1000l\033[?25h"); /* disable mouse, show cursor */
450 PAUSE_TIMER { /* timer spams ASCII STX (0x02) chars */
451 move_ph(LINE_BELOW, 0);
452 putchar(':'); /* prompt */
453
454 raw_mode(0);/*use cooked mode, so we get line editing for free*/
455 fgets(what, 256, stdin); //TODO: cancel on ^G, ESC, ^C, ...
456 raw_mode(1);
457
458 move_ph(LINE_BELOW, 0);
459 printf ("\033[0J"); /* clear to the end of the screen */
460 }
461 printf ("\033[?1000h\033[?25l"); /* enable mouse, hide cursor */
462
463 switch (what[0]) { //TODO: urgh.
464 case 'q': return EX_QUIT;
465 case 'n': return EX_NEW;
466 case 'h': return EX_HELP;
467 case 'r': return EX_RESZ;
468 default: return EX_INVALID;
469 }
470 }
471 void set_mark(void) {
472 int mark = tolower(getch_wrapper());
473 if (mark < 'a' || mark > 'z') return; /*out of bound*/
474
475 g.m[mark-'a'].l = g.p[0];
476 g.m[mark-'a'].c = g.p[1];
477 g.m[mark-'a'].s = 1;
478 }
479
480 void jump_mark(void) {
481 int mark = tolower(getch_wrapper());
482 /* check bounds and if set: */
483 if (mark < 'a' || mark > 'z' || !g.m[mark-'a'].s) return;
484 move_hi (g.m[mark-'a'].l, g.m[mark-'a'].c);
485 }
486
487 void fill_minefield (int l, int c) {
488 srand (time(0));
489 int mines_set = f.m;
490 while (mines_set) {
491 int line = rand() % f.h;
492 int col = rand() % f.w;
493
494 if (f.c[line][col].m) {
495 /* skip if field already has a mine */
496 continue;
497 } else if ((line == l) && (col == c)) {
498 /* don't put a mine on the already opened (first click) field */
499 continue;
500 } else {
501 mines_set--;
502 f.c[line][col].m = STD_MINE;
503 }
504 }
505
506 /* precalculate neighbours */
507 for (int l=0; l < f.h; l++)
508 for (int c=0; c < f.w; c++)
509 f.c[l][c].n = get_neighbours (l, c, NORMAL);
510 }
511
512 void move_ph (int line, int col) {
513 /* move printhead to zero-indexed position */
514 printf ("\033[%d;%dH", line+1, col+1);
515 }
516
517 void move_hi (int l, int c) {
518 /* move cursor and highlight to absolute coordinates */
519
520 redraw_cell (g.p[0], g.p[1], NORMAL);
521 /* update g.p */
522 g.p[0] = CLAMP(l, 0, f.h-1);
523 g.p[1] = CLAMP(c, 0, f.w-1);
524 move_ph (g.p[0]+LINE_OFFSET, field2screen_c(g.p[1]));
525
526 redraw_cell (g.p[0], g.p[1], HIGHLIGHT);
527 }
528
529 /* to_next_boundary(): move into the supplied direction until a change in open-
530 state or flag-state is found and move there. prefer landing on a closed cell by
531 advancing once more when landing on an opened cell. falls back to BIG_MOVE. */
532 #define FIND_BOUND(X, L, C, L1, C1, MAX, OP) do {\
533 new_ ## X OP ## = BIG_MOVE;\
534 for (int i = X OP 1; i > 0 && i < f.MAX-1; i OP ## OP)\
535 if (((f.c[L ][C ].o<<2) + f.c[L ][C ].f) \
536 != ((f.c[L1][C1].o<<2) + f.c[L1][C1].f)) {\
537 new_ ## X = i OP !f.c[L1][C1].o;\
538 break;\
539 }\
540 } while(0)
541 void to_next_boundary (int l, int c, char direction) {
542 int new_l = l;
543 int new_c = c;
544 switch (direction) {
545 case '>': FIND_BOUND(c, l, i, l, i+1, w, +); break;
546 case '<': FIND_BOUND(c, l, i, l, i-1, w, -); break;
547 case '^': FIND_BOUND(l, i, c, i-1, c, h, -); break;
548 case 'v': FIND_BOUND(l, i, c, i+1, c, h, +); break;
549 }
550
551 move_hi (new_l, new_c);
552 }
553 #undef FIND_BOUND
554
555 #define CELL f.c[g.p[0]][c]
556 #define FIND_NEXT(CONDITION, DIRECTION) do {\
557 int plusminus = DIRECTION-'='; /* -1 if '<', 1 if '>' */ \
558 for (int c = g.p[1]+plusminus; c >= 0 && c < f.w; c+=plusminus) \
559 if (CONDITION) { \
560 move_hi (g.p[0], c+(till_after*plusminus)); \
561 return 1; /* NOTE: break didn't work */ \
562 } \
563 return 0; \
564 } while(0)
565 int find (int what, char direction, int till_after) {
566 switch (what) {
567 case ' ': what = '0'; /* fallthrough */
568 case '0': case '1': case '2':
569 case '3': case '4': case '5':
570 case '6': case '7': case '8': /* numbers, opened */
571 FIND_NEXT(CELL.o && CELL.n == what-'0', direction);
572 case 'o': FIND_NEXT(CELL.o, direction); /* any opened */
573 case 'c': FIND_NEXT(!CELL.o, direction); /* any closed */
574 case 'f': case 'i': FIND_NEXT(CELL.f==FLAG, direction); /* is flagged */
575 case 'q': case '?': FIND_NEXT(CELL.f==QUESM, direction);/* questioned */
576 }
577
578 return 0;
579 }
580 #undef FIND_NEXT
581 #undef CELL
582
583 char* cell2schema (int l, int c, int mode) {
584 struct minecell cell = f.c[l][c];
585
586 if (mode == SHOWMINES) return (
587 cell.f == FLAG && cell.m ? op.scheme->field_flagged:
588 cell.f == FLAG && !cell.m ? op.scheme->mine_wrongf:
589 cell.m == STD_MINE ? op.scheme->mine_normal:
590 cell.m == DEATH_MINE ? op.scheme->mine_death:
591 cell.o == CLOSED ? op.scheme->field_closed:
592 /*.......................*/ op.scheme->number[f.c[l][c].n]);
593 else if (mode == SHOWFLAGS) return (
594 /* on win (everything opened, only correct flags left) */
595 cell.m == STD_MINE ? op.scheme->field_flagged:
596 /*.......................*/ op.scheme->number[f.c[l][c].n]);
597 else return (
598 cell.f == FLAG ? op.scheme->field_flagged:
599 cell.f == QUESM ? op.scheme->field_question:
600 cell.o == CLOSED ? op.scheme->field_closed:
601 cell.m == STD_MINE ? op.scheme->mine_normal:
602 cell.m == DEATH_MINE ? op.scheme->mine_death:
603 /*.......................*/ op.scheme->number[f.c[l][c].n]);
604 }
605
606 void redraw_cell (int l, int c, int mode) {
607 move_ph (l+LINE_OFFSET, field2screen_c(c));
608 if (mode == HIGHLIGHT) printf ("\033[7m"); /* reverse video */
609 print (cell2schema(l, c, mode));
610 if (mode == HIGHLIGHT) printf ("\033[0m"); /* reset all */
611 }
612
613 char* get_emoticon(void) {
614 return g.o==GAME_WON ? EMOT(WON):
615 g.o==GAME_LOST? EMOT(DEAD):
616 EMOT(SMILE);
617 }
618
619 /* https://zserge.com/blog/c-for-loop-tricks.html */
620 #define print_line(which) \
621 for (int _break = (printf("%s", BORDER(which,LEFT)), 1); _break; \
622 _break = 0, printf("%s\r\n", BORDER(which,RIGHT)))
623 #define print_border(which, width) \
624 print_line(which) printm (width, BORDER(which,MIDDLE))
625 void show_minefield (int mode) {
626 int dtime = difftime (time(NULL), g.t)*!!g.t;
627 int half_spaces = f.w*op.scheme->cell_width/2;
628 int left_spaces = MAX(0,half_spaces-7-(f.m-g.f>999));
629 int right_spaces = MAX(0,half_spaces-6-(dtime>999));
630 static char modechar[] = {'*', '!', '?'};
631
632 move_ph (0,0);
633
634 print_border(TOP, f.w);
635 print_line(STATUS) {
636 printf("[%03d%c]%*s%s%*s[%03d]",
637 /* [ */ f.m - g.f, modechar[g.s], /* ] */
638 left_spaces,"", get_emoticon(), right_spaces,"",
639 /* [ */ dtime /* ] */);
640 }
641 print_border(DIVIDER, f.w);
642 /* main body */
643 for (int l = 0; l < f.h; l++) print_line(FIELD)
644 printm (f.w, cell2schema(l, _loop, mode));
645 print_border(BOTTOM, f.w);
646 }
647
648 void show_stomp (int enable, int l, int c) {
649 if (enable) {
650 if (f.c[l][c].o == OPENED && get_neighbours (l, c, 1) != 0) {
651 /* show the stomp radius if we aren't fully flagged */
652 AROUND(l, c)
653 if (AR_CELL.o == CLOSED && AR_CELL.f != FLAG)
654 redraw_cell (ROW, COL, HIGHLIGHT);
655 fflush(stdout); /* won't display without */
656 }
657 } else {
658 AROUND(l, c) redraw_cell (ROW, COL, g.o?SHOWMINES:NORMAL);
659 }
660 }
661
662 void wait_keypress (int timeout) {
663 /* block SIGALRM, otherwise poll gets cancelled by the timer: */
664 sigset_t sig;
665 sigemptyset (&sig);
666 sigaddset(&sig, SIGALRM);
667 sigprocmask (SIG_BLOCK, &sig, NULL);
668
669 /* wait for timout or keypress: */
670 struct pollfd fds;
671 fds.fd = 0; fds.events = POLLIN;
672 poll(&fds, 1, timeout);
673
674 /* restore signal mask: */
675 sigprocmask (SIG_UNBLOCK, &sig, NULL);
676 }
677
678 int get_neighbours (int line, int col, int reduced_mode) {
679 /* counts mines surrounding a square
680 modes: 0=normal; 1=reduced */
681
682 int count = 0;
683 AROUND(line, col) {
684 count += !!AR_CELL.m;
685 count -= reduced_mode * AR_CELL.f==FLAG;
686 }
687 return count;
688 }
689
690 int closed_neighbours (int line, int col) {
691 /* counts closed cells surrounding a square */
692
693 int count = 0;
694 AROUND(line, col) {
695 count += !AR_CELL.o;
696 }
697 return count;
698 }
699
700 void interactive_resize(void) {
701 unsigned char buf[3];
702 int old_w = f.w;
703 int old_h = f.h;
704 for(;;) {
705 screen_setup(1); /* clears the screen */
706 show_minefield (RESIZEMODE);
707 /* show the new field size in the corner: */
708 move_ph(f.h+LINE_OFFSET-1,COL_OFFSET);
709 printf("%d x %d", f.w, f.h);
710 move_ph(LINE_BELOW, 0);
711 printf("Resize Mode: Enter to set, Q to abort");
712 //TODO: need escape seq. to print lowercase in `-d' mode!
713
714 free_field(); /* must free before resizing! */
715 switch (getctrlseq(buf)) {
716 case CTRSEQ_CURSOR_LEFT: case 'h': f.w--; break;
717 case CTRSEQ_CURSOR_DOWN: case 'j': f.h++; break;
718 case CTRSEQ_CURSOR_UP: case 'k': f.h--; break;
719 case CTRSEQ_CURSOR_RIGHT:case 'l': f.w++; break;
720 case 'w': f.w+=BIG_MOVE; break;
721 case 'b': f.w-=BIG_MOVE; break;
722 case 'u': f.h-=BIG_MOVE; break;
723 case 'd': f.h+=BIG_MOVE; break;
724 case 0xa: return; /* enter */
725 case 'q': /* abort */
726 f.w = old_w;
727 f.h = old_h;
728 screen_setup(1);
729 return;
730 }
731
732 clamp_fieldsize();
733 f.m = mines_percentage(f.w, f.h);
734 f.c = alloc_array (f.h, f.w);
735 }
736 }
737
738 struct minecell** alloc_array (int lines, int cols) {
739 free_field (); /* NOTE: this feels like a hack :| */
740 struct minecell** a = malloc (lines * sizeof(struct minecell*));
741 if (a == NULL) return NULL;
742 for (int l = 0; l < lines; l++) {
743 a[l] = calloc (cols, sizeof(struct minecell));
744 if (a[l] == NULL) goto unalloc;
745 }
746
747 return a;
748 unalloc:
749 for (int l = 0; l < lines; l++)
750 free (a[l]);
751 return NULL;
752 }
753
754 void free_field (void) {
755 if (f.c == NULL) return;
756 for (int l = 0; l < f.h; l++) {
757 free (f.c[l]);
758 }
759
760 free (f.c);
761 f.c = NULL;
762 }
763
764 int screen2field_l (int l) {
765 return (l-LINE_OFFSET) - 1;
766 }
767 int screen2field_c (int c) {
768 /* this depends on the cell width and only works when it is 1 or 2. */
769 return (c-COL_OFFSET+1 - 2*(CW%2))/2 - CW/2;
770 }
771 int field2screen_c (int c) {
772 return (CW*c+COL_OFFSET - (CW%2));
773 }
774 int clicked_emoticon (unsigned char* mouse) {
775 return (mouse[2] == LINE_OFFSET-1 && (
776 mouse[1] == f.w+COL_OFFSET ||
777 mouse[1] == f.w+COL_OFFSET+1));
778 }
779
780 enum esc_states {
781 START,
782 ESC_SENT,
783 CSI_SENT,
784 MOUSE_EVENT,
785 };
786 int getctrlseq (unsigned char* buf) {
787 int c;
788 int state = START;
789 int offset = 0x20; /* never sends control chars as data */
790 while ((c = getchar()) != EOF) {
791 switch (state) {
792 case START:
793 switch (c) {
794 case '\033': state=ESC_SENT; break;
795 default: return c;
796 }
797 break;
798 case ESC_SENT:
799 switch (c) {
800 case '[': state=CSI_SENT; break;
801 default: return CTRSEQ_INVALID;
802 }
803 break;
804 case CSI_SENT:
805 switch (c) {
806 case 'A': return CTRSEQ_CURSOR_UP;
807 case 'B': return CTRSEQ_CURSOR_DOWN;
808 case 'C': return CTRSEQ_CURSOR_RIGHT;
809 case 'D': return CTRSEQ_CURSOR_LEFT;
810 case 'M': state=MOUSE_EVENT; break;
811 default: return CTRSEQ_INVALID;
812 }
813 break;
814 case MOUSE_EVENT:
815 buf[0] = c - offset;
816 buf[1] = getchar() - offset;
817 buf[2] = getchar() - offset;
818 return CTRSEQ_MOUSE;
819 default:
820 return CTRSEQ_INVALID;
821 }
822 }
823 return 2;
824 }
825
826 int getch(unsigned char* buf) {
827 /* returns a character, EOF, or constant for an escape/control sequence - NOT
828 compatible with the ncurses implementation of same name */
829 int action = getctrlseq(buf);
830 int l, c;
831 switch (action) {
832 case CTRSEQ_MOUSE:
833 l = screen2field_l (buf[2]);
834 c = screen2field_c (buf[1]);
835
836 if (buf[0] > 3) break; /* ignore all but left/middle/right/up */
837 int success = wait_mouse_up(l, c);
838
839 /* mouse moved while pressed: */
840 if (!success) return CTRSEQ_INVALID;
841
842 switch (buf[0]) {
843 case 0: return CTRSEQ_MOUSE_LEFT;
844 case 1: return CTRSEQ_MOUSE_MIDDLE;
845 case 2: return CTRSEQ_MOUSE_RIGHT;
846 }
847 }
848
849 return action;
850 }
851
852 int getch_wrapper (void) {
853 unsigned char mouse[3];
854 int c;
855 /*skip over ASCII_STX=0x02 that gets sent when returning from SIGALRM:*/
856 while ( (c = getch(mouse)) == 0x02);
857
858 if (c == CTRSEQ_MOUSE_LEFT || c == CTRSEQ_MOUSE_RIGHT) {
859 if (clicked_emoticon(mouse))
860 return WRAPPER_EMOTICON;
861
862 if (screen2field_c (mouse[1]) < 0
863 || screen2field_c (mouse[1]) >= f.w
864 || screen2field_l (mouse[2]) < 0
865 || screen2field_l (mouse[2]) >= f.h)
866 return CTRSEQ_INVALID;
867
868 g.p[0] = screen2field_l (mouse[2]);
869 g.p[1] = screen2field_c (mouse[1]);
870
871 return c; /* CTRSEQ_MOUSE_LEFT || CTRSEQ_MOUSE_RIGHT */
872 }
873
874 return c;
875 }
876
877 void clamp_fieldsize (void) {
878 /* clamp field size to terminal size and mouse maximum: */
879 struct winsize w;
880 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
881
882 /* seven is the minimum width of the status bar */
883 /* NOTE: min of status in DEC mode: 13 (WONTFIX) */
884 if (f.w < 7) f.w = 7;
885 if (f.h < 7) f.h = 7;
886
887 if (COL_OFFSET + f.w*CW + COL_OFFSET > w.ws_col)
888 f.w = (w.ws_col - COL_OFFSET - COL_OFFSET)/DW;
889 if (LINE_OFFSET + f.h + LINES_AFTER > w.ws_row)
890 f.h = w.ws_row - (LINE_OFFSET+LINES_AFTER);
891 if (COL_OFFSET + f.w*CW > MOUSE_MAX)
892 f.w = MOUSE_MAX/CW - COL_OFFSET;
893 if (LINE_OFFSET + f.h > MOUSE_MAX)
894 f.h = MOUSE_MAX - LINE_OFFSET;
895 }
896
897 int mines_percentage(int w, int h) {
898 return w*h*(w*h<30*16?.15625:.20625);
899 }
900
901 int parse_fieldspec(char* str) {
902 /* parses the FIELDSPEC (WxHxM); returns 1 on error */
903 int n = sscanf (str, "%dx%dx%d", &f.w, &f.h, &f.m);
904
905 clamp_fieldsize();
906
907 if (n < 2) {
908 return 1; /* error */
909 } else if (n == 2) {
910 f.m = mines_percentage(f.w, f.h);
911 }
912
913 f.m = MIN(f.m, (f.w-1) * (f.h-1)); /* limit mines */
914
915 return 0;
916 }
917
918 void timer_setup (int enable) {
919 static struct itimerval tbuf;
920 tbuf.it_interval.tv_sec = 1;
921 tbuf.it_interval.tv_usec = 0;
922
923 if (enable) {
924 g.t = time(NULL);
925 tbuf.it_value.tv_sec = 1;
926 tbuf.it_value.tv_usec = 0;
927 if (setitimer(ITIMER_REAL, &tbuf, NULL) == -1) {
928 perror("setitimer");
929 exit(1);
930 }
931 } else {
932 tbuf.it_value.tv_sec = 0;
933 tbuf.it_value.tv_usec = 0;
934 if ( setitimer(ITIMER_REAL, &tbuf, NULL) == -1 ) {
935 perror("setitimer");
936 exit(1);
937 }
938 }
939
940 }
941
942 void signal_setup (void) {
943 struct sigaction saction;
944
945 saction.sa_handler = signal_handler;
946 sigemptyset(&saction.sa_mask);
947 saction.sa_flags = 0;
948 if (sigaction(SIGALRM, &saction, NULL) < 0 ) {
949 perror("SIGALRM");
950 exit(1);
951 }
952
953 if (sigaction(SIGTSTP, &saction, NULL) < 0 ) {
954 perror ("SIGTSTP");
955 exit (1);
956 }
957
958 if (sigaction(SIGCONT, &saction, NULL) < 0 ) {
959 perror ("SIGCONT");
960 exit (1);
961 }
962
963 if (sigaction(SIGINT, &saction, NULL) < 0 ) {
964 perror ("SIGINT");
965 exit (1);
966 }
967 }
968
969 void signal_handler (int signum) {
970 int dtime;
971 switch (signum) {
972 case SIGALRM:
973 dtime = difftime (time(NULL), g.t);
974 move_ph (1, f.w*CW-(CW%2)-3-(dtime>999));
975 printf ("[%03d]", g.t?dtime:0);
976 break;
977 case SIGTSTP: /* interactive stop (C-z) */
978 screen_setup(0); fflush(stdout);
979 signal(SIGTSTP, SIG_DFL); /* NOTE: assumes SysV semantics! */
980 raise(SIGTSTP);
981 break;
982 case SIGCONT:
983 /* NOTE: will leave the VT220 in special graphics charset */
984 screen_setup(1);
985 show_minefield (NORMAL);
986 break;
987 case SIGINT:
988 exit(128+SIGINT);
989 }
990 }
991
992 void screen_setup (int enable) {
993 static int sent_init;
994 if (enable) {
995 raw_mode(1);
996 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
997 printf ("\033[H\033[J"); /* reset cursor, clear screen */
998 printf ("\033[?1000h\033[?25l"); /* enable mouse, hide cursor */
999 if (!sent_init++) /* swich charset, if necessary and only once*/
1000 print (op.scheme->init_seq);
1001 } else {
1002 print (op.scheme->reset_seq); /* reset charset, if necessary */
1003 printf ("\033[?1000l\033[?25h");/* disable mouse, show cursor */
1004 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
1005 raw_mode(0);
1006 sent_init = 0;
1007 }
1008 }
1009
1010 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
1011 void raw_mode(int enable) {
1012 static struct termios saved_term_mode;
1013 struct termios raw_term_mode;
1014
1015 if (enable) {
1016 if (saved_term_mode.c_lflag == 0)/*don't overwrite stored mode*/
1017 tcgetattr(STDIN_FILENO, &saved_term_mode);
1018 raw_term_mode = saved_term_mode;
1019 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
1020 raw_term_mode.c_cc[VMIN] = 1 ;
1021 raw_term_mode.c_cc[VTIME] = 0;
1022 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
1023 } else {
1024 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
1025 }
1026 }
Imprint / Impressum