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