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