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