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