]> git.gir.st - minesVIiper.git/blob - mines.c
shave off 4 bytes in DEC scheme (II)
[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_'R':
111 interactive_resize();
112 goto newgame;
113 }
114 }
115
116 quit:
117 return 0;
118 }
119
120 int minesviiper(void) {
121 f.c = alloc_array (f.h, f.w);
122 g = (const struct game){0}; /* reset all game-specific parameters */
123
124 show_minefield (NORMAL);
125
126 for(;;) {
127 switch (getch_wrapper()) {
128 case ' ':
129 if (HI_CELL.o == OPENED) goto open_cell;
130 if (g.s == MODE_OPEN) goto open_cell;
131 if (g.s == MODE_FLAG) goto flag_cell;
132 if (g.s == MODE_QUESM) goto quesm_cell;
133 break;
134 case 'a':
135 g.s = (g.s+1)%(op.mode+1);
136 show_minefield (g.c?SHOWMINES:NORMAL);
137 break;
138 open_cell:
139 case CTRSEQ_MOUSE_LEFT:
140 case 'o':
141 switch (do_uncover(&(g.n))) {
142 case GAME_LOST: return GAME_LOST;
143 case GAME_WON: return GAME_WON;
144 }
145 break;
146 flag_cell:
147 case CTRSEQ_MOUSE_RIGHT:
148 case 'i': flag_square (g.p[0], g.p[1]); break;
149 quesm_cell:
150 case '?':quesm_square (g.p[0], g.p[1]); break;
151 case CTRSEQ_CURSOR_LEFT:
152 case 'h': move_hi (g.p[0], g.p[1]-1); break;
153 case CTRSEQ_CURSOR_DOWN:
154 case 'j': move_hi (g.p[0]+1, g.p[1] ); break;
155 case CTRSEQ_CURSOR_UP:
156 case 'k': move_hi (g.p[0]-1, g.p[1] ); break;
157 case CTRSEQ_CURSOR_RIGHT:
158 case 'l': move_hi (g.p[0], g.p[1]+1); break;
159 case 'w': to_next_boundary (g.p[0], g.p[1], '>'); break;
160 case 'b': to_next_boundary (g.p[0], g.p[1], '<'); break;
161 case 'u': to_next_boundary (g.p[0], g.p[1], '^'); break;
162 case 'd': to_next_boundary (g.p[0], g.p[1], 'v'); break;
163 case '0': /* fallthrough */
164 case '^': move_hi (g.p[0], 0 ); break;
165 case '$': move_hi (g.p[0], f.w-1 ); break;
166 case 'g': move_hi (0, g.p[1] ); break;
167 case 'G': move_hi (f.h-1, g.p[1] ); break;
168 case 'z': move_hi (f.h/2, f.w/2); break;
169 case 'm': set_mark(); break;
170 case'\'': /* fallthrough */
171 case '`': jump_mark(); break;
172 case WRAPPER_EMOTICON:
173 case 'r': return GAME_NEW;
174 case 'q': return GAME_QUIT;
175 case CTRL_'L':
176 screen_setup(1);
177 show_minefield (NORMAL);
178 break;
179 case CTRL_'R':
180 interactive_resize();
181 return GAME_NEW;
182 case '\\':
183 if (g.n == GAME_NEW) break; /* must open a cell first */
184 g.c = !g.c;
185 show_minefield (g.c?SHOWMINES:NORMAL);
186 break;
187 }
188 }
189
190 }
191
192 void quit (void) {
193 screen_setup(0);
194 free_field ();
195 }
196
197 /* I haven't won as long as a cell exists, that
198 - I haven't opened, and
199 - is not a mine */
200 int everything_opened (void) {
201 for (int row = 0; row < f.h; row++)
202 for (int col = 0; col < f.w; col++)
203 if (f.c[row][col].o == CLOSED &&
204 f.c[row][col].m == NO_MINE ) return 0;
205 return 1;
206 }
207
208 int wait_mouse_up (int l, int c) { /* TODO: should not take minefield-coords but absolute ones */
209 //TODO: make stomp radius visible while mouse is down instead of after mouse up
210 unsigned char mouse2[3];
211 int level = 1;
212 int l2, c2;
213
214 /* show :o face */
215 move_ph (1, field2screen_c (f.w/2)-1); print (EMOT(OHH));
216
217 if (!(l < 0 || l >= f.h || c < 0 || c >= f.w)) {
218 /* show a pushed-in button if cursor is on minefield */
219 partial_show_minefield (l, c, HIGHLIGHT);
220 }
221
222 while (level > 0) {
223 if (getctrlseq (mouse2) == CTRSEQ_MOUSE) {
224 /* ignore mouse wheel events: */
225 if (mouse2[0] & 0x40) continue;
226
227 else if (mouse2[0]&3 == 3) level--; /* release event */
228 else level++; /* another button pressed */
229 }
230 }
231
232 move_ph (1, field2screen_c (f.w/2)-1); print (get_emoticon());
233
234 if (!(l < 0 || l >= f.h || c < 0 || c >= f.w)) {
235 partial_show_minefield (l, c, NORMAL);
236 }
237 c2 = screen2field_c(mouse2[1]);
238 l2 = screen2field_l(mouse2[2]);
239 return ((l2 == l) && (c2 == c));
240 }
241
242 int choord_square (int line, int col) {
243 if (uncover_square (line, col)) return 1;
244 AROUND(line,col)
245 if (AR_CELL.f != FLAG) {
246 if (uncover_square (ROW, COL))
247 return 1;
248 }
249
250 return 0;
251 }
252
253 int uncover_square (int l, int c) {
254 if (f.c[l][c].o == OPENED)
255 return 0; /* nothing to do */
256
257 f.c[l][c].o = OPENED;
258 f.c[l][c].f = NOFLAG; /*must not be QUESM, otherwise rendering issues*/
259 partial_show_minefield (l, c, NORMAL);
260
261 if (f.c[l][c].m) {
262 f.c[l][c].m = DEATH_MINE;
263 return 1;
264 }
265
266 /* check for chording */
267 if (f.c[l][c].n == 0) {
268 AROUND(l, c)
269 if (uncover_square (ROW, COL)) return 1;
270 }
271
272 return 0;
273 }
274
275 void flag_square (int l, int c) {
276 static char modechar[] = {'*', '!', '?'};
277
278 if (f.c[l][c].o != CLOSED) return;
279 /* cycle through flag/quesm/noflag: */
280 f.c[l][c].f = (f.c[l][c].f + 1) % (op.mode + 1);
281 if (f.c[l][c].f==FLAG) g.f++;
282 else if ((op.mode==FLAG && f.c[l][c].f==NOFLAG) ||
283 (op.mode==QUESM && f.c[l][c].f==QUESM)) g.f--;
284 partial_show_minefield (l, c, NORMAL);
285 move_ph (1, op.scheme->cell_width);
286 printf ("[%03d%c]", f.m - g.f, modechar[g.s]);
287 }
288
289 void quesm_square (int l, int c) {
290 /* toggle question mark / none. won't turn flags into question marks.
291 unlike flag_square, this function doesn't respect `-q'. */
292 if (f.c[l][c].o != CLOSED) return;
293 else if (f.c[l][c].f == NOFLAG) f.c[l][c].f = QUESM;
294 else if (f.c[l][c].f == QUESM) f.c[l][c].f = NOFLAG;
295 partial_show_minefield (l, c, NORMAL);
296 }
297
298 int do_uncover (int* is_newgame) {
299 if (*is_newgame == GAME_NEW) {
300 *is_newgame = GAME_INPROGRESS;
301 fill_minefield (g.p[0], g.p[1]);
302 timer_setup(1);
303 }
304
305 if (HI_CELL.f == FLAG ) return GAME_INPROGRESS;
306 if (HI_CELL.o == CLOSED) {
307 if (uncover_square (g.p[0], g.p[1])) return GAME_LOST;
308 } else if (get_neighbours (g.p[0], g.p[1], 1) == 0) {
309 if (choord_square (g.p[0], g.p[1])) return GAME_LOST;
310 } else {
311 /* show the stomp radius if we aren't fully flagged */
312 AROUND(g.p[0], g.p[1])
313 if (AR_CELL.o == CLOSED && AR_CELL.f !=FLAG)
314 partial_show_minefield (ROW, COL, HIGHLIGHT);
315 fflush(stdout); /* won't display without */
316
317 /* block SIGALRM, otherwise poll gets cancelled by the timer: */
318 sigset_t sig;
319 sigemptyset (&sig);
320 sigaddset(&sig, SIGALRM);
321 sigprocmask (SIG_BLOCK, &sig, NULL);
322 /* wait for timout or keypress: */
323 struct pollfd fds;
324 fds.fd = 0; fds.events = POLLIN;
325 poll(&fds, 1, STOMP_TIMEOUT);
326 /* restore signal mask: */
327 sigprocmask (SIG_UNBLOCK, &sig, NULL);
328
329 AROUND(g.p[0], g.p[1]) partial_show_minefield(ROW, COL, NORMAL);
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 partial_show_minefield (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 partial_show_minefield (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 char* cell2schema (int l, int c, int mode) {
420 struct minecell cell = f.c[l][c];
421
422 if (mode == SHOWMINES) return (
423 cell.f == FLAG && cell.m ? op.scheme->field_flagged:
424 cell.f == FLAG && !cell.m ? op.scheme->mine_wrongf:
425 cell.m == STD_MINE ? op.scheme->mine_normal:
426 cell.m == DEATH_MINE ? op.scheme->mine_death:
427 cell.o == CLOSED ? op.scheme->field_closed:
428 /*.......................*/ op.scheme->number[f.c[l][c].n]);
429 else return (
430 cell.f == FLAG ? op.scheme->field_flagged:
431 cell.f == QUESM ? op.scheme->field_question:
432 cell.o == CLOSED ? op.scheme->field_closed:
433 cell.m == STD_MINE ? op.scheme->mine_normal:
434 cell.m == DEATH_MINE ? op.scheme->mine_death:
435 /*.......................*/ op.scheme->number[f.c[l][c].n]);
436 }
437
438 void partial_show_minefield (int l, int c, int mode) {
439 move_ph (l+LINE_OFFSET, field2screen_c(c));
440 if (mode == HIGHLIGHT) printf ("\033[7m"); /* reverse video */
441 print (cell2schema(l, c, mode));
442 if (mode == HIGHLIGHT) printf ("\033[0m"); /* reset all */
443 }
444
445 char* get_emoticon(void) {
446 return g.o==GAME_WON ? EMOT(WON):
447 g.o==GAME_LOST? EMOT(DEAD):
448 EMOT(SMILE);
449 }
450
451 /* https://zserge.com/blog/c-for-loop-tricks.html */
452 #define print_line(which) \
453 for (int _break = (printf("%s", BORDER(which,LEFT)), 1); _break; \
454 _break = 0, printf("%s\r\n", BORDER(which,RIGHT)))
455 #define print_border(which, width) \
456 print_line(which) printm (width, BORDER(which,MIDDLE))
457 void show_minefield (int mode) {
458 int dtime = difftime (time(NULL), g.t)*!!g.t;
459 int half_spaces = f.w*op.scheme->cell_width/2;
460 int left_spaces = MAX(0,half_spaces-7-(f.m-g.f>999));
461 int right_spaces = MAX(0,half_spaces-6-(dtime>999));
462 static char modechar[] = {'*', '!', '?'};
463
464 move_ph (0,0);
465
466 print_border(TOP, f.w);
467 print_line(STATUS) {
468 if (mode == RESIZEMODE) printf ("%-*s", 2*half_spaces,
469 f.w>20?"Resize Mode: HJKL to resize, Enter to set":
470 f.w>11?"Resize Mode: HJKL/Enter":"HJKL/Enter");
471 else printf("[%03d%c]%*s%s%*s[%03d]",
472 /* [ */ f.m - g.f, modechar[g.s], /* ] */
473 left_spaces,"", get_emoticon(), right_spaces,"",
474 /* [ */ dtime /* ] */);
475 }
476 print_border(DIVIDER, f.w);
477 /* main body */
478 for (int l = 0; l < f.h; l++) print_line(FIELD)
479 printm (f.w, cell2schema(l, _loop, mode));
480 print_border(BOTTOM, f.w);
481 }
482
483 int get_neighbours (int line, int col, int reduced_mode) {
484 /* counts mines surrounding a square
485 modes: 0=normal; 1=reduced */
486
487 int count = 0;
488 AROUND(line, col) {
489 count += !!AR_CELL.m;
490 count -= reduced_mode * AR_CELL.f==FLAG;
491 }
492 return count;
493 }
494
495 void interactive_resize(void) {
496 unsigned char buf[3];
497 for(;;) {
498 screen_setup(1); /* clears the screen */
499 show_minefield (RESIZEMODE);
500 /* show the new field size in the corner: */
501 move_ph(f.h+LINE_OFFSET-1,COL_OFFSET);
502 printf("%d x %d", f.w, f.h);
503
504 free_field(); /* must free before resizing! */
505 switch (getctrlseq(buf)) {
506 case 'h': f.w--; break;
507 case 'j': f.h++; break;
508 case 'k': f.h--; break;
509 case 'l': f.w++; break;
510 case 0xa: /* enter, fallthrough */
511 case 'q': return;
512 }
513
514 clamp_fieldsize();
515 f.m = mines_percentage(f.w, f.h);
516 f.c = alloc_array (f.h, f.w);
517 }
518 }
519
520 struct minecell** alloc_array (int lines, int cols) {
521 free_field (); /* NOTE: this feels like a hack :| */
522 struct minecell** a = malloc (lines * sizeof(struct minecell*));
523 if (a == NULL) return NULL;
524 for (int l = 0; l < lines; l++) {
525 a[l] = calloc (cols, sizeof(struct minecell));
526 if (a[l] == NULL) goto unalloc;
527 }
528
529 return a;
530 unalloc:
531 for (int l = 0; l < lines; l++)
532 free (a[l]);
533 return NULL;
534 }
535
536 void free_field (void) {
537 if (f.c == NULL) return;
538 for (int l = 0; l < f.h; l++) {
539 free (f.c[l]);
540 }
541
542 free (f.c);
543 f.c = NULL;
544 }
545
546 int screen2field_l (int l) {
547 return (l-LINE_OFFSET) - 1;
548 }
549 int screen2field_c (int c) {
550 /* this depends on the cell width and only works when it is 1 or 2. */
551 return (c-COL_OFFSET+1 - 2*(CW%2))/2 - CW/2;
552 }
553 int field2screen_c (int c) {
554 return (CW*c+COL_OFFSET - (CW%2));
555 }
556 int clicked_emoticon (unsigned char* mouse) {
557 return (mouse[2] == LINE_OFFSET-1 && (
558 mouse[1] == f.w+COL_OFFSET ||
559 mouse[1] == f.w+COL_OFFSET+1));
560 }
561
562 enum esc_states {
563 START,
564 ESC_SENT,
565 CSI_SENT,
566 MOUSE_EVENT,
567 };
568 int getctrlseq (unsigned char* buf) {
569 int c;
570 int state = START;
571 int offset = 0x20; /* never sends control chars as data */
572 while ((c = getchar()) != EOF) {
573 switch (state) {
574 case START:
575 switch (c) {
576 case '\033': state=ESC_SENT; break;
577 default: return c;
578 }
579 break;
580 case ESC_SENT:
581 switch (c) {
582 case '[': state=CSI_SENT; break;
583 default: return CTRSEQ_INVALID;
584 }
585 break;
586 case CSI_SENT:
587 switch (c) {
588 case 'A': return CTRSEQ_CURSOR_UP;
589 case 'B': return CTRSEQ_CURSOR_DOWN;
590 case 'C': return CTRSEQ_CURSOR_RIGHT;
591 case 'D': return CTRSEQ_CURSOR_LEFT;
592 case 'M': state=MOUSE_EVENT; break;
593 default: return CTRSEQ_INVALID;
594 }
595 break;
596 case MOUSE_EVENT:
597 buf[0] = c - offset;
598 buf[1] = getchar() - offset;
599 buf[2] = getchar() - offset;
600 return CTRSEQ_MOUSE;
601 default:
602 return CTRSEQ_INVALID;
603 }
604 }
605 return 2;
606 }
607
608 int getch(unsigned char* buf) {
609 /* returns a character, EOF, or constant for an escape/control sequence - NOT
610 compatible with the ncurses implementation of same name */
611 int action = getctrlseq(buf);
612 int l, c;
613 switch (action) {
614 case CTRSEQ_MOUSE:
615 l = screen2field_l (buf[2]);
616 c = screen2field_c (buf[1]);
617
618 if (buf[0] > 3) break; /* ignore all but left/middle/right/up */
619 int success = wait_mouse_up(l, c);
620
621 /* mouse moved while pressed: */
622 if (!success) return CTRSEQ_INVALID;
623
624 switch (buf[0]) {
625 case 0: return CTRSEQ_MOUSE_LEFT;
626 case 1: return CTRSEQ_MOUSE_MIDDLE;
627 case 2: return CTRSEQ_MOUSE_RIGHT;
628 }
629 }
630
631 return action;
632 }
633
634 int getch_wrapper (void) {
635 unsigned char mouse[3];
636 int c = getch(mouse);
637
638 if (c == CTRSEQ_MOUSE_LEFT || c == CTRSEQ_MOUSE_RIGHT) {
639 if (clicked_emoticon(mouse))
640 return WRAPPER_EMOTICON;
641
642 if (screen2field_c (mouse[1]) < 0
643 || screen2field_c (mouse[1]) >= f.w
644 || screen2field_l (mouse[2]) < 0
645 || screen2field_l (mouse[2]) >= f.h)
646 return CTRSEQ_INVALID;
647
648 g.p[0] = screen2field_l (mouse[2]);
649 g.p[1] = screen2field_c (mouse[1]);
650
651 return c; /* CTRSEQ_MOUSE_LEFT || CTRSEQ_MOUSE_RIGHT */
652 }
653
654 return c;
655 }
656
657 void clamp_fieldsize (void) {
658 /* clamp field size to terminal size and mouse maximum: */
659 struct winsize w;
660 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
661
662 if (COL_OFFSET + f.w*CW + COL_OFFSET > w.ws_col)
663 f.w = w.ws_col/CW - (COL_OFFSET+COL_OFFSET);
664 if (LINE_OFFSET + f.h + LINES_AFTER > w.ws_row)
665 f.h = w.ws_row - (LINE_OFFSET+LINES_AFTER);
666 if (COL_OFFSET + f.w*CW > MOUSE_MAX)
667 f.w = MOUSE_MAX/CW - COL_OFFSET;
668 if (LINE_OFFSET + f.h > MOUSE_MAX)
669 f.h = MOUSE_MAX - LINE_OFFSET;
670 }
671
672 int mines_percentage(int w, int h) {
673 return w*h*(w*h<30*16?.15625:.20625);
674 }
675
676 int parse_fieldspec(char* str) {
677 /* parses the FIELDSPEC (WxHxM); returns 1 on error */
678 int n = sscanf (str, "%dx%dx%d", &f.w, &f.h, &f.m);
679
680 clamp_fieldsize();
681
682 if (n < 2) {
683 return 1; /* error */
684 } else if (n == 2) {
685 f.m = mines_percentage(f.w, f.h);
686 }
687
688 f.m = MIN(f.m, (f.w-1) * (f.h-1)); /* limit mines */
689
690 return 0;
691 }
692
693 void timer_setup (int enable) {
694 static struct itimerval tbuf;
695 tbuf.it_interval.tv_sec = 1;
696 tbuf.it_interval.tv_usec = 0;
697
698 if (enable) {
699 g.t = time(NULL);
700 tbuf.it_value.tv_sec = 1;
701 tbuf.it_value.tv_usec = 0;
702 if (setitimer(ITIMER_REAL, &tbuf, NULL) == -1) {
703 perror("setitimer");
704 exit(1);
705 }
706 } else {
707 tbuf.it_value.tv_sec = 0;
708 tbuf.it_value.tv_usec = 0;
709 if ( setitimer(ITIMER_REAL, &tbuf, NULL) == -1 ) {
710 perror("setitimer");
711 exit(1);
712 }
713 }
714
715 }
716
717 void signal_setup (void) {
718 struct sigaction saction;
719
720 saction.sa_handler = signal_handler;
721 sigemptyset(&saction.sa_mask);
722 saction.sa_flags = 0;
723 if (sigaction(SIGALRM, &saction, NULL) < 0 ) {
724 perror("SIGALRM");
725 exit(1);
726 }
727
728 if (sigaction(SIGINT, &saction, NULL) < 0 ) {
729 perror ("SIGINT");
730 exit (1);
731 }
732 }
733
734 void signal_handler (int signum) {
735 int dtime;
736 switch (signum) {
737 case SIGALRM:
738 dtime = difftime (time(NULL), g.t);
739 move_ph (1, f.w*CW-(CW%2)-3-(dtime>999));
740 printf ("[%03d]", g.t?dtime:0);
741 break;
742 case SIGINT:
743 exit(128+SIGINT);
744 }
745 }
746
747 void screen_setup (int enable) {
748 if (enable) {
749 raw_mode(1);
750 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
751 printf ("\033[H\033[J"); /* reset cursor, clear screen */
752 printf ("\033[?1000h\033[?25l"); /* enable mouse, hide cursor */
753 print (op.scheme->init_seq); /* swich charset, if necessary */
754 } else {
755 print (op.scheme->reset_seq); /* reset charset, if necessary */
756 printf ("\033[?9l\033[?25h"); /* disable mouse, show cursor */
757 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
758 raw_mode(0);
759 }
760 }
761
762 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
763 void raw_mode(int enable) {
764 static struct termios saved_term_mode;
765 struct termios raw_term_mode;
766
767 if (enable) {
768 tcgetattr(STDIN_FILENO, &saved_term_mode);
769 raw_term_mode = saved_term_mode;
770 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
771 raw_term_mode.c_cc[VMIN] = 1 ;
772 raw_term_mode.c_cc[VTIME] = 0;
773 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
774 } else {
775 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
776 }
777 }
Imprint / Impressum