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