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