]> git.gir.st - minesVIiper.git/blob - mines.c
fix stray STX messing with `m', `f', `t'
[minesVIiper.git] / mines.c
1 /*******************************************************************************
2 minesviiper 0.4
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 <sys/ioctl.h>
26 #include <sys/time.h>
27 #include <termios.h>
28 #include <time.h>
29 #include <unistd.h>
30
31 #include "mines.h"
32 #include "schemes.h"
33
34 #define LINE_OFFSET 3
35 #define LINES_AFTER 2
36 #define COL_OFFSET 2
37 #define BIG_MOVE 5
38 #define MOUSE_MAX 231
39 #define STOMP_TIMEOUT 150 /*ms*/
40
41 #define MIN(a,b) (a>b?b:a)
42 #define MAX(a,b) (a>b?a:b)
43 #define CLAMP(a,m,M) (a<m?m:(a>M?M:a))
44 #define printm(n, s) for (int _loop = 0; _loop < n; _loop++) fputs (s, stdout)
45 #define print(str) fputs (str?str:"", stdout)
46 #define EMOT(e) op.scheme->emoticons[EMOT_ ## e]
47 #define BORDER(l, c) op.scheme->border[B_ ## l][B_ ## c]
48 #define CW op.scheme->cell_width /* for brevity */
49 #define HI_CELL f.c[g.p[0]][g.p[1]]
50 #define CTRL_ 0x1F &
51
52 #define AR_CELL f.c[ROW][COL] /* helper for AROUND() */
53 #define AROUND(l, c) /* gives us loop-variables ROW, COL, AR_CELL */ \
54 for (int ROW = MAX(l-1, 0); ROW <= MIN(l+1, f.h-1); ROW++) \
55 for (int COL = MAX(c-1, 0); COL <= MIN(c+1, f.w-1); COL++) \
56 if (!(ROW == l && COL == c)) /* skip itself */
57
58 struct minefield f;
59 struct game g;
60 struct opt op;
61
62 int main (int argc, char** argv) {
63 /* defaults: */
64 f.w = 30;
65 f.h = 16;
66 f.m = 99;
67 op.scheme = &symbols_mono;
68 op.mode = FLAG;
69
70 int optget;
71 opterr = 0; /* don't print message on unrecognized option */
72 while ((optget = getopt (argc, argv, "+hnfqcdx")) != -1) {
73 switch (optget) {
74 case 'n': op.mode = NOFLAG; break;
75 case 'f': op.mode = FLAG; break; /*default*/
76 case 'q': op.mode = QUESM; break; /*WARN:implicitly sets -f*/
77 case 'c': op.scheme = &symbols_col1; break;
78 case 'd': op.scheme = &symbols_doublewidth; break;
79 case 'h':
80 default:
81 fprintf (stderr, SHORTHELP LONGHELP, argv[0]);
82 return !(optget=='h');
83 }
84 } if (optind < argc) { /* parse Fieldspec */
85 if (parse_fieldspec (argv[optind])) {
86 fprintf (stderr, SHORTHELP FIELDHELP, argv[0]);
87 return 1;
88 }
89 }
90
91 signal_setup();
92 screen_setup(1);
93 atexit (*quit);
94
95 newgame:
96 switch (minesviiper()) {
97 case GAME_NEW: goto newgame;
98 case GAME_WON: g.o = GAME_WON; break;
99 case GAME_LOST:g.o = GAME_LOST;break;
100 case GAME_QUIT:goto quit;
101 }
102
103 timer_setup(0); /* stop timer */
104 show_minefield (SHOWMINES);
105 for(;;) {
106 switch(getch_wrapper()) {
107 case WRAPPER_EMOTICON:
108 case 'r': goto newgame;
109 case 'q': goto quit;
110 case CTRL_'L': //TODO: updates the timer (fix in show_minefield())
111 screen_setup(1);
112 show_minefield (SHOWMINES);
113 break;
114 case CTRL_'R':
115 interactive_resize();
116 goto newgame;
117 }
118 }
119
120 quit:
121 return 0;
122 }
123
124 int minesviiper(void) {
125 f.c = alloc_array (f.h, f.w);
126 g = (const struct game){0}; /* reset all game-specific parameters */
127
128 show_minefield (NORMAL);
129
130 for(;;) {
131 int actor = KEYBOARD; /* WARN: feels like a hack :| */
132 switch (getch_wrapper()) {
133 case ' ':
134 if (HI_CELL.o == OPENED) goto open_cell;
135 if (g.s == MODE_OPEN) goto open_cell;
136 if (g.s == MODE_FLAG) goto flag_cell;
137 if (g.s == MODE_QUESM) goto quesm_cell;
138 break;
139 case 'a':
140 g.s = (g.s+1)%(op.mode+1);
141 show_minefield (g.c?SHOWMINES:NORMAL);
142 break;
143 case CTRSEQ_MOUSE_LEFT:
144 actor = MOUSE;
145 /* fallthrough */
146 open_cell:
147 case 'o':
148 switch (do_uncover(&(g.n), actor)) {
149 case GAME_LOST: return GAME_LOST;
150 case GAME_WON: return GAME_WON;
151 }
152 break;
153 flag_cell:
154 case CTRSEQ_MOUSE_RIGHT:
155 case 'i': flag_square (g.p[0], g.p[1]); break;
156 quesm_cell:
157 case '?':quesm_square (g.p[0], g.p[1]); break;
158 case CTRSEQ_CURSOR_LEFT:
159 case 'h': move_hi (g.p[0], g.p[1]-1); break;
160 case CTRSEQ_CURSOR_DOWN:
161 case 'j': move_hi (g.p[0]+1, g.p[1] ); break;
162 case CTRSEQ_CURSOR_UP:
163 case 'k': move_hi (g.p[0]-1, g.p[1] ); break;
164 case CTRSEQ_CURSOR_RIGHT:
165 case 'l': move_hi (g.p[0], g.p[1]+1); break;
166 case 'w': to_next_boundary (g.p[0], g.p[1], '>'); break;
167 case 'b': to_next_boundary (g.p[0], g.p[1], '<'); break;
168 case 'u': to_next_boundary (g.p[0], g.p[1], '^'); break;
169 case 'd': to_next_boundary (g.p[0], g.p[1], 'v'); break;
170 case '0': /* fallthrough */
171 case '^': move_hi (g.p[0], 0 ); break;
172 case '$': move_hi (g.p[0], f.w-1 ); break;
173 case 'g': move_hi (0, g.p[1] ); break;
174 case 'G': move_hi (f.h-1, g.p[1] ); break;
175 case 'z': move_hi (f.h/2, f.w/2); break;
176 case 'm': set_mark(); break;
177 case'\'': /* fallthrough */
178 case '`': jump_mark(); break;
179 case 'f': find(getch_wrapper(), '>'); break;
180 case 'F': find(getch_wrapper(), '<'); break;
181 case 't': till(getch_wrapper(), '>'); break;
182 case 'T': till(getch_wrapper(), '<'); break;
183 case WRAPPER_EMOTICON:
184 case 'r': timer_setup(0); return GAME_NEW;
185 case 'q': return GAME_QUIT;
186 case CTRL_'L':
187 screen_setup(1);
188 show_minefield (NORMAL);
189 break;
190 case CTRL_'R':
191 timer_setup(0);
192 interactive_resize();
193 return GAME_NEW;
194 case '\\':
195 if (g.n == GAME_NEW) break; /* must open a cell first */
196 g.c = !g.c;
197 show_minefield (g.c?SHOWMINES:NORMAL);
198 break;
199 }
200 }
201
202 }
203
204 void quit (void) {
205 screen_setup(0);
206 free_field ();
207 }
208
209 /* I haven't won as long as a cell exists, that
210 - I haven't opened, and
211 - is not a mine */
212 int everything_opened (void) {
213 for (int row = 0; row < f.h; row++)
214 for (int col = 0; col < f.w; col++)
215 if (f.c[row][col].o == CLOSED &&
216 f.c[row][col].m == NO_MINE ) return 0;
217 return 1;
218 }
219
220 int wait_mouse_up (int l, int c) { /* TODO: should not take minefield-coords but absolute ones */
221 unsigned char mouse2[3];
222 int level = 1;
223 int l2, c2;
224
225 /* show :o face */
226 move_ph (1, field2screen_c (f.w/2)-1); print (EMOT(OHH));
227
228 if (!(l < 0 || l >= f.h || c < 0 || c >= f.w)) {
229 /* show a pushed-in button if cursor is on minefield */
230 redraw_cell (l, c, HIGHLIGHT);
231
232 show_stomp(1, l, c);
233 }
234
235 while (level > 0) {
236 if (getctrlseq (mouse2) == CTRSEQ_MOUSE) {
237 /* ignore mouse wheel events: */
238 if (mouse2[0] & 0x40) continue;
239
240 else if (mouse2[0]&3 == 3) level--; /* release event */
241 else level++; /* another button pressed */
242 }
243 }
244
245 move_ph (1, field2screen_c (f.w/2)-1); print (get_emoticon());
246
247 if (!(l < 0 || l >= f.h || c < 0 || c >= f.w)) {
248 redraw_cell (l, c, g.o?SHOWMINES:NORMAL);
249 show_stomp(0, l, c);
250 }
251 c2 = screen2field_c(mouse2[1]);
252 l2 = screen2field_l(mouse2[2]);
253 return ((l2 == l) && (c2 == c));
254 }
255
256 int choord_square (int line, int col) {
257 if (uncover_square (line, col)) return 1;
258 AROUND(line,col)
259 if (AR_CELL.f != FLAG) {
260 if (uncover_square (ROW, COL))
261 return 1;
262 }
263
264 return 0;
265 }
266
267 int uncover_square (int l, int c) {
268 if (f.c[l][c].o == OPENED)
269 return 0; /* nothing to do */
270
271 f.c[l][c].o = OPENED;
272 f.c[l][c].f = NOFLAG; /*must not be QUESM, otherwise rendering issues*/
273 redraw_cell (l, c, NORMAL);
274
275 if (f.c[l][c].m) {
276 f.c[l][c].m = DEATH_MINE;
277 return 1;
278 }
279
280 /* check for chording */
281 if (f.c[l][c].n == 0) {
282 AROUND(l, c)
283 if (uncover_square (ROW, COL)) return 1;
284 }
285
286 return 0;
287 }
288
289 void flag_square (int l, int c) {
290 static char modechar[] = {'*', '!', '?'};
291
292 if (f.c[l][c].o != CLOSED) return;
293 /* cycle through flag/quesm/noflag: */
294 f.c[l][c].f = (f.c[l][c].f + 1) % (op.mode + 1);
295 if (f.c[l][c].f==FLAG) g.f++;
296 else if ((op.mode==FLAG && f.c[l][c].f==NOFLAG) ||
297 (op.mode==QUESM && f.c[l][c].f==QUESM)) g.f--;
298 redraw_cell (l, c, NORMAL);
299 move_ph (1, op.scheme->cell_width);
300 printf ("[%03d%c]", f.m - g.f, modechar[g.s]);
301 }
302
303 void quesm_square (int l, int c) {
304 /* toggle question mark / none. won't turn flags into question marks.
305 unlike flag_square, this function doesn't respect `-q'. */
306 if (f.c[l][c].o != CLOSED) return;
307 else if (f.c[l][c].f == NOFLAG) f.c[l][c].f = QUESM;
308 else if (f.c[l][c].f == QUESM) f.c[l][c].f = NOFLAG;
309 redraw_cell (l, c, NORMAL);
310 }
311
312 int do_uncover (int* is_newgame, int actor) {
313 if (*is_newgame == GAME_NEW) {
314 *is_newgame = GAME_INPROGRESS;
315 fill_minefield (g.p[0], g.p[1]);
316 timer_setup(1);
317 }
318
319 if (HI_CELL.f == FLAG ) return GAME_INPROGRESS;
320 if (HI_CELL.o == CLOSED) {
321 if (uncover_square (g.p[0], g.p[1])) return GAME_LOST;
322 } else if (get_neighbours (g.p[0], g.p[1], 1) == 0) {
323 if (choord_square (g.p[0], g.p[1])) return GAME_LOST;
324 } else if (actor != MOUSE) {
325 show_stomp(1, g.p[0], g.p[1]);
326
327 wait_stomp();
328
329 show_stomp(0, g.p[0], g.p[1]);
330 }
331 if (everything_opened()) return GAME_WON;
332
333 return GAME_INPROGRESS;
334 }
335
336 void set_mark(void) {
337 int mark = tolower(getch_wrapper());
338 if (mark < 'a' || mark > 'z') return; /*out of bound*/
339
340 g.m[mark-'a'].l = g.p[0];
341 g.m[mark-'a'].c = g.p[1];
342 g.m[mark-'a'].s = 1;
343 }
344
345 void jump_mark(void) {
346 int mark = tolower(getch_wrapper());
347 /* check bounds and if set: */
348 if (mark < 'a' || mark > 'z' || !g.m[mark-'a'].s) return;
349 move_hi (g.m[mark-'a'].l, g.m[mark-'a'].c);
350 }
351
352 void fill_minefield (int l, int c) {
353 srand (time(0));
354 int mines_set = f.m;
355 while (mines_set) {
356 int line = rand() % f.h;
357 int col = rand() % f.w;
358
359 if (f.c[line][col].m) {
360 /* skip if field already has a mine */
361 continue;
362 } else if ((line == l) && (col == c)) {
363 /* don't put a mine on the already opened (first click) field */
364 continue;
365 } else {
366 mines_set--;
367 f.c[line][col].m = STD_MINE;
368 }
369 }
370
371 /* precalculate neighbours */
372 for (int l=0; l < f.h; l++)
373 for (int c=0; c < f.w; c++)
374 f.c[l][c].n = get_neighbours (l, c, NORMAL);
375 }
376
377 void move_ph (int line, int col) {
378 /* move printhead to zero-indexed position */
379 printf ("\033[%d;%dH", line+1, col+1);
380 }
381
382 void move_hi (int l, int c) {
383 /* move cursor and highlight to absolute coordinates */
384
385 redraw_cell (g.p[0], g.p[1], NORMAL);
386 /* update g.p */
387 g.p[0] = CLAMP(l, 0, f.h-1);
388 g.p[1] = CLAMP(c, 0, f.w-1);
389 move_ph (g.p[0]+LINE_OFFSET, field2screen_c(g.p[1]));
390
391 redraw_cell (g.p[0], g.p[1], HIGHLIGHT);
392 }
393
394 /* to_next_boundary(): move into the supplied direction until a change in open-
395 state or flag-state is found and move there. falls back to BIG_MOVE. */
396 #define FIND_NEXT(X, L, C, L1, C1, MAX, OP) do {\
397 new_ ## X OP ## = BIG_MOVE;\
398 for (int i = X OP 1; i > 0 && i < f.MAX-1; i OP ## OP)\
399 if (((f.c[L ][C ].o<<2) + f.c[L ][C ].f) \
400 != ((f.c[L1][C1].o<<2) + f.c[L1][C1].f)) {\
401 new_ ## X = i OP 1;\
402 break;\
403 }\
404 } while(0)
405 void to_next_boundary (int l, int c, char direction) {
406 int new_l = l;
407 int new_c = c;
408 switch (direction) {
409 case '>': FIND_NEXT(c, l, i, l, i+1, w, +); break;
410 case '<': FIND_NEXT(c, l, i, l, i-1, w, -); break;
411 case '^': FIND_NEXT(l, i, c, i-1, c, h, -); break;
412 case 'v': FIND_NEXT(l, i, c, i+1, c, h, +); break;
413 }
414
415 move_hi (new_l, new_c);
416 }
417 #undef FIND_NEXT
418
419 #define CELL f.c[g.p[0]][c]
420 #define FIND_WHAT(CONDITION, DIRECTION) do {\
421 int plusminus = DIRECTION-'='; /* -1 if '<', 1 if '>' */ \
422 for (int c = g.p[1]+plusminus; c >= 0 && c < f.w; c+=plusminus) \
423 if (CONDITION) { \
424 move_hi (g.p[0], c); \
425 return 1; \
426 } \
427 } while(0)
428 int find (int what, char direction) {
429 switch (what) {
430 case ' ': what = '0'; /* numbers, opened; fallthrough */
431 case '0': case '1': case '2':
432 case '3': case '4': case '5':
433 case '6': case '7': case '8':
434 FIND_WHAT(CELL.o && CELL.n == what-'0', direction);
435 case 'f': case 'i': FIND_WHAT(CELL.f==FLAG, direction); /* is flagged */
436 case 'o': FIND_WHAT(CELL.o, direction); /* any opened */
437 case '?': FIND_WHAT(CELL.f==QUESM, direction);/* questioned */
438 case 'c': FIND_WHAT(!CELL.o, direction); /* any closed */
439 }
440
441 return 0;
442 }
443 #undef FIND_WHAT
444 #undef CELL
445
446 void till (int what, char direction) {
447 /* if we found what we were looking for move one cell back */
448 if (find (what, direction)) move_hi(g.p[0], g.p[1]-(direction-'='));
449 }
450
451 char* cell2schema (int l, int c, int mode) {
452 struct minecell cell = f.c[l][c];
453
454 if (mode == SHOWMINES) return (
455 cell.f == FLAG && cell.m ? op.scheme->field_flagged:
456 cell.f == FLAG && !cell.m ? op.scheme->mine_wrongf:
457 cell.m == STD_MINE ? op.scheme->mine_normal:
458 cell.m == DEATH_MINE ? op.scheme->mine_death:
459 cell.o == CLOSED ? op.scheme->field_closed:
460 /*.......................*/ op.scheme->number[f.c[l][c].n]);
461 else return (
462 cell.f == FLAG ? op.scheme->field_flagged:
463 cell.f == QUESM ? op.scheme->field_question:
464 cell.o == CLOSED ? op.scheme->field_closed:
465 cell.m == STD_MINE ? op.scheme->mine_normal:
466 cell.m == DEATH_MINE ? op.scheme->mine_death:
467 /*.......................*/ op.scheme->number[f.c[l][c].n]);
468 }
469
470 void redraw_cell (int l, int c, int mode) {
471 move_ph (l+LINE_OFFSET, field2screen_c(c));
472 if (mode == HIGHLIGHT) printf ("\033[7m"); /* reverse video */
473 print (cell2schema(l, c, mode));
474 if (mode == HIGHLIGHT) printf ("\033[0m"); /* reset all */
475 }
476
477 char* get_emoticon(void) {
478 return g.o==GAME_WON ? EMOT(WON):
479 g.o==GAME_LOST? EMOT(DEAD):
480 EMOT(SMILE);
481 }
482
483 /* https://zserge.com/blog/c-for-loop-tricks.html */
484 #define print_line(which) \
485 for (int _break = (printf("%s", BORDER(which,LEFT)), 1); _break; \
486 _break = 0, printf("%s\r\n", BORDER(which,RIGHT)))
487 #define print_border(which, width) \
488 print_line(which) printm (width, BORDER(which,MIDDLE))
489 void show_minefield (int mode) {
490 //TODO: in `-d' mode if f.w is odd we are 1 char short in the status line
491 //TODO: in `-d' mode we need to specify a charset to print lowercase (-> resize mode)
492 int dtime = difftime (time(NULL), g.t)*!!g.t;
493 int half_spaces = f.w*op.scheme->cell_width/2;
494 int left_spaces = MAX(0,half_spaces-7-(f.m-g.f>999));
495 int right_spaces = MAX(0,half_spaces-6-(dtime>999));
496 static char modechar[] = {'*', '!', '?'};
497
498 move_ph (0,0);
499
500 print_border(TOP, f.w);
501 print_line(STATUS) {
502 if (mode == RESIZEMODE) printf ("%-*s", 2*half_spaces,
503 f.w*CW>53?"Resize Mode: HJKL to resize, Enter to set, Q to abort":
504 f.w*CW>25?"Resize Mode: HJKL/Enter/Q":"HJKL/Enter/Q");
505 else printf("[%03d%c]%*s%s%*s[%03d]",
506 /* [ */ f.m - g.f, modechar[g.s], /* ] */
507 left_spaces,"", get_emoticon(), right_spaces,"",
508 /* [ */ dtime /* ] */);
509 }
510 print_border(DIVIDER, f.w);
511 /* main body */
512 for (int l = 0; l < f.h; l++) print_line(FIELD)
513 printm (f.w, cell2schema(l, _loop, mode));
514 print_border(BOTTOM, f.w);
515 }
516
517 void show_stomp (int enable, int l, int c) {
518 if (enable) {
519 if (f.c[l][c].o == OPENED && get_neighbours (l, c, 1) != 0) {
520 /* show the stomp radius if we aren't fully flagged */
521 AROUND(l, c)
522 if (AR_CELL.o == CLOSED && AR_CELL.f != FLAG)
523 redraw_cell (ROW, COL, HIGHLIGHT);
524 fflush(stdout); /* won't display without */
525
526 }
527 } else {
528 AROUND(l, c) redraw_cell (ROW, COL, g.o?SHOWMINES:NORMAL);
529 }
530 }
531
532 void wait_stomp (void) {
533 /* block SIGALRM, otherwise poll gets cancelled by the timer: */
534 sigset_t sig;
535 sigemptyset (&sig);
536 sigaddset(&sig, SIGALRM);
537 sigprocmask (SIG_BLOCK, &sig, NULL);
538
539 /* wait for timout or keypress: */
540 struct pollfd fds;
541 fds.fd = 0; fds.events = POLLIN;
542 poll(&fds, 1, STOMP_TIMEOUT);
543
544 /* restore signal mask: */
545 sigprocmask (SIG_UNBLOCK, &sig, NULL);
546 }
547
548 int get_neighbours (int line, int col, int reduced_mode) {
549 /* counts mines surrounding a square
550 modes: 0=normal; 1=reduced */
551
552 int count = 0;
553 AROUND(line, col) {
554 count += !!AR_CELL.m;
555 count -= reduced_mode * AR_CELL.f==FLAG;
556 }
557 return count;
558 }
559
560 void interactive_resize(void) {
561 unsigned char buf[3];
562 int old_w = f.w;
563 int old_h = f.h;
564 for(;;) {
565 screen_setup(1); /* clears the screen */
566 show_minefield (RESIZEMODE);
567 /* show the new field size in the corner: */
568 move_ph(f.h+LINE_OFFSET-1,COL_OFFSET);
569 printf("%d x %d", f.w, f.h);
570
571 free_field(); /* must free before resizing! */
572 switch (getctrlseq(buf)) {
573 case CTRSEQ_CURSOR_LEFT: case 'h': f.w--; break;
574 case CTRSEQ_CURSOR_DOWN: case 'j': f.h++; break;
575 case CTRSEQ_CURSOR_UP: case 'k': f.h--; break;
576 case CTRSEQ_CURSOR_RIGHT:case 'l': f.w++; break;
577 case 'w': f.w+=BIG_MOVE; break;
578 case 'b': f.w-=BIG_MOVE; break;
579 case 'u': f.h-=BIG_MOVE; break;
580 case 'd': f.h+=BIG_MOVE; break;
581 case 0xa: return; /* enter */
582 case 'q': /* abort */
583 f.w = old_w;
584 f.h = old_h;
585 screen_setup(1);
586 return;
587 }
588
589 clamp_fieldsize();
590 f.m = mines_percentage(f.w, f.h);
591 f.c = alloc_array (f.h, f.w);
592 }
593 }
594
595 struct minecell** alloc_array (int lines, int cols) {
596 free_field (); /* NOTE: this feels like a hack :| */
597 struct minecell** a = malloc (lines * sizeof(struct minecell*));
598 if (a == NULL) return NULL;
599 for (int l = 0; l < lines; l++) {
600 a[l] = calloc (cols, sizeof(struct minecell));
601 if (a[l] == NULL) goto unalloc;
602 }
603
604 return a;
605 unalloc:
606 for (int l = 0; l < lines; l++)
607 free (a[l]);
608 return NULL;
609 }
610
611 void free_field (void) {
612 if (f.c == NULL) return;
613 for (int l = 0; l < f.h; l++) {
614 free (f.c[l]);
615 }
616
617 free (f.c);
618 f.c = NULL;
619 }
620
621 int screen2field_l (int l) {
622 return (l-LINE_OFFSET) - 1;
623 }
624 int screen2field_c (int c) {
625 /* this depends on the cell width and only works when it is 1 or 2. */
626 return (c-COL_OFFSET+1 - 2*(CW%2))/2 - CW/2;
627 }
628 int field2screen_c (int c) {
629 return (CW*c+COL_OFFSET - (CW%2));
630 }
631 int clicked_emoticon (unsigned char* mouse) {
632 return (mouse[2] == LINE_OFFSET-1 && (
633 mouse[1] == f.w+COL_OFFSET ||
634 mouse[1] == f.w+COL_OFFSET+1));
635 }
636
637 enum esc_states {
638 START,
639 ESC_SENT,
640 CSI_SENT,
641 MOUSE_EVENT,
642 };
643 int getctrlseq (unsigned char* buf) {
644 int c;
645 int state = START;
646 int offset = 0x20; /* never sends control chars as data */
647 while ((c = getchar()) != EOF) {
648 switch (state) {
649 case START:
650 switch (c) {
651 case '\033': state=ESC_SENT; break;
652 default: return c;
653 }
654 break;
655 case ESC_SENT:
656 switch (c) {
657 case '[': state=CSI_SENT; break;
658 default: return CTRSEQ_INVALID;
659 }
660 break;
661 case CSI_SENT:
662 switch (c) {
663 case 'A': return CTRSEQ_CURSOR_UP;
664 case 'B': return CTRSEQ_CURSOR_DOWN;
665 case 'C': return CTRSEQ_CURSOR_RIGHT;
666 case 'D': return CTRSEQ_CURSOR_LEFT;
667 case 'M': state=MOUSE_EVENT; break;
668 default: return CTRSEQ_INVALID;
669 }
670 break;
671 case MOUSE_EVENT:
672 buf[0] = c - offset;
673 buf[1] = getchar() - offset;
674 buf[2] = getchar() - offset;
675 return CTRSEQ_MOUSE;
676 default:
677 return CTRSEQ_INVALID;
678 }
679 }
680 return 2;
681 }
682
683 int getch(unsigned char* buf) {
684 /* returns a character, EOF, or constant for an escape/control sequence - NOT
685 compatible with the ncurses implementation of same name */
686 int action = getctrlseq(buf);
687 int l, c;
688 switch (action) {
689 case CTRSEQ_MOUSE:
690 l = screen2field_l (buf[2]);
691 c = screen2field_c (buf[1]);
692
693 if (buf[0] > 3) break; /* ignore all but left/middle/right/up */
694 int success = wait_mouse_up(l, c);
695
696 /* mouse moved while pressed: */
697 if (!success) return CTRSEQ_INVALID;
698
699 switch (buf[0]) {
700 case 0: return CTRSEQ_MOUSE_LEFT;
701 case 1: return CTRSEQ_MOUSE_MIDDLE;
702 case 2: return CTRSEQ_MOUSE_RIGHT;
703 }
704 }
705
706 return action;
707 }
708
709 int getch_wrapper (void) {
710 unsigned char mouse[3];
711 int c;
712 /*skip over ASCII_STX=0x02 that gets sent when returning from SIGALRM:*/
713 while ( (c = getch(mouse)) == 0x02);
714
715 if (c == CTRSEQ_MOUSE_LEFT || c == CTRSEQ_MOUSE_RIGHT) {
716 if (clicked_emoticon(mouse))
717 return WRAPPER_EMOTICON;
718
719 if (screen2field_c (mouse[1]) < 0
720 || screen2field_c (mouse[1]) >= f.w
721 || screen2field_l (mouse[2]) < 0
722 || screen2field_l (mouse[2]) >= f.h)
723 return CTRSEQ_INVALID;
724
725 g.p[0] = screen2field_l (mouse[2]);
726 g.p[1] = screen2field_c (mouse[1]);
727
728 return c; /* CTRSEQ_MOUSE_LEFT || CTRSEQ_MOUSE_RIGHT */
729 }
730
731 return c;
732 }
733
734 void clamp_fieldsize (void) {
735 /* clamp field size to terminal size and mouse maximum: */
736 struct winsize w;
737 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
738
739 if (f.w < 1) f.w = 1;
740 if (f.h < 1) f.h = 1;
741
742 if (COL_OFFSET + f.w*CW + COL_OFFSET > w.ws_col)
743 f.w = (w.ws_col - COL_OFFSET - COL_OFFSET)/CW; //TODO: does not work in `-d' (in xterm)
744 if (LINE_OFFSET + f.h + LINES_AFTER > w.ws_row)
745 f.h = w.ws_row - (LINE_OFFSET+LINES_AFTER);
746 if (COL_OFFSET + f.w*CW > MOUSE_MAX)
747 f.w = MOUSE_MAX/CW - COL_OFFSET;
748 if (LINE_OFFSET + f.h > MOUSE_MAX)
749 f.h = MOUSE_MAX - LINE_OFFSET;
750 }
751
752 int mines_percentage(int w, int h) {
753 return w*h*(w*h<30*16?.15625:.20625);
754 }
755
756 int parse_fieldspec(char* str) {
757 /* parses the FIELDSPEC (WxHxM); returns 1 on error */
758 int n = sscanf (str, "%dx%dx%d", &f.w, &f.h, &f.m);
759
760 clamp_fieldsize();
761
762 if (n < 2) {
763 return 1; /* error */
764 } else if (n == 2) {
765 f.m = mines_percentage(f.w, f.h);
766 }
767
768 f.m = MIN(f.m, (f.w-1) * (f.h-1)); /* limit mines */
769
770 return 0;
771 }
772
773 void timer_setup (int enable) {
774 static struct itimerval tbuf;
775 tbuf.it_interval.tv_sec = 1;
776 tbuf.it_interval.tv_usec = 0;
777
778 if (enable) {
779 g.t = time(NULL);
780 tbuf.it_value.tv_sec = 1;
781 tbuf.it_value.tv_usec = 0;
782 if (setitimer(ITIMER_REAL, &tbuf, NULL) == -1) {
783 perror("setitimer");
784 exit(1);
785 }
786 } else {
787 tbuf.it_value.tv_sec = 0;
788 tbuf.it_value.tv_usec = 0;
789 if ( setitimer(ITIMER_REAL, &tbuf, NULL) == -1 ) {
790 perror("setitimer");
791 exit(1);
792 }
793 }
794
795 }
796
797 void signal_setup (void) {
798 struct sigaction saction;
799
800 saction.sa_handler = signal_handler;
801 sigemptyset(&saction.sa_mask);
802 saction.sa_flags = 0;
803 if (sigaction(SIGALRM, &saction, NULL) < 0 ) {
804 perror("SIGALRM");
805 exit(1);
806 }
807
808 if (sigaction(SIGINT, &saction, NULL) < 0 ) {
809 perror ("SIGINT");
810 exit (1);
811 }
812 }
813
814 void signal_handler (int signum) {
815 int dtime;
816 switch (signum) {
817 case SIGALRM:
818 dtime = difftime (time(NULL), g.t);
819 move_ph (1, f.w*CW-(CW%2)-3-(dtime>999));
820 printf ("[%03d]", g.t?dtime:0);
821 break;
822 case SIGINT:
823 exit(128+SIGINT);
824 }
825 }
826
827 void screen_setup (int enable) {
828 if (enable) {
829 raw_mode(1);
830 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
831 printf ("\033[H\033[J"); /* reset cursor, clear screen */
832 printf ("\033[?1000h\033[?25l"); /* enable mouse, hide cursor */
833 print (op.scheme->init_seq); /* swich charset, if necessary */
834 } else {
835 print (op.scheme->reset_seq); /* reset charset, if necessary */
836 printf ("\033[?9l\033[?25h"); /* disable mouse, show cursor */
837 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
838 raw_mode(0);
839 }
840 }
841
842 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
843 void raw_mode(int enable) {
844 static struct termios saved_term_mode;
845 struct termios raw_term_mode;
846
847 if (enable) {
848 tcgetattr(STDIN_FILENO, &saved_term_mode);
849 raw_term_mode = saved_term_mode;
850 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
851 raw_term_mode.c_cc[VMIN] = 1 ;
852 raw_term_mode.c_cc[VTIME] = 0;
853 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
854 } else {
855 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
856 }
857 }
Imprint / Impressum