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