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