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