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