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