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