]> git.gir.st - minesVIiper.git/blob - mines.c
redo makefile
[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], '>', 1); break;
178 case 'b': to_next_boundary (g.p[0], g.p[1], '<', 1); break;
179 case 'u': to_next_boundary (g.p[0], g.p[1], '^', 1); break;
180 case 'd': to_next_boundary (g.p[0], g.p[1], 'v', 1); break;
181 case 'e': to_next_boundary (g.p[0], g.p[1], '>', 0); 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. falls back to BIG_MOVE. */
520 #define FIND_BOUND(X, L, C, L1, C1, MAX, OP) do {\
521 new_ ## X OP ## = BIG_MOVE;\
522 for (int i = X OP 1; i > 0 && i < f.MAX-1; i OP ## OP)\
523 if (((f.c[L ][C ].o<<2) + f.c[L ][C ].f) \
524 != ((f.c[L1][C1].o<<2) + f.c[L1][C1].f)) {\
525 new_ ## X = i OP advance;\
526 break;\
527 }\
528 } while(0)
529 void to_next_boundary (int l, int c, char direction, int advance) {
530 int new_l = l;
531 int new_c = c;
532 switch (direction) {
533 case '>': FIND_BOUND(c, l, i, l, i+1, w, +); break;
534 case '<': FIND_BOUND(c, l, i, l, i-1, w, -); break;
535 case '^': FIND_BOUND(l, i, c, i-1, c, h, -); break;
536 case 'v': FIND_BOUND(l, i, c, i+1, c, h, +); break;
537 }
538
539 move_hi (new_l, new_c);
540 }
541 #undef FIND_BOUND
542
543 #define CELL f.c[g.p[0]][c]
544 #define FIND_NEXT(CONDITION, DIRECTION) do {\
545 int plusminus = DIRECTION-'='; /* -1 if '<', 1 if '>' */ \
546 for (int c = g.p[1]+plusminus; c >= 0 && c < f.w; c+=plusminus) \
547 if (CONDITION) { \
548 move_hi (g.p[0], c+(till_after*plusminus)); \
549 return 1; /* NOTE: break didn't work */ \
550 } \
551 return 0; \
552 } while(0)
553 int find (int what, char direction, int till_after) {
554 switch (what) {
555 case ' ': what = '0'; /* fallthrough */
556 case '0': case '1': case '2':
557 case '3': case '4': case '5':
558 case '6': case '7': case '8': /* numbers, opened */
559 FIND_NEXT(CELL.o && CELL.n == what-'0', direction);
560 case 'o': FIND_NEXT(CELL.o, direction); /* any opened */
561 case 'c': FIND_NEXT(!CELL.o, direction); /* any closed */
562 case 'f': case 'i': FIND_NEXT(CELL.f==FLAG, direction); /* is flagged */
563 case 'q': case '?': FIND_NEXT(CELL.f==QUESM, direction);/* questioned */
564 }
565
566 return 0;
567 }
568 #undef FIND_NEXT
569 #undef CELL
570
571 char* cell2schema (int l, int c, int mode) {
572 struct minecell cell = f.c[l][c];
573
574 if (mode == SHOWMINES) return (
575 cell.f == FLAG && cell.m ? op.scheme->field_flagged:
576 cell.f == FLAG && !cell.m ? op.scheme->mine_wrongf:
577 cell.m == STD_MINE ? op.scheme->mine_normal:
578 cell.m == DEATH_MINE ? op.scheme->mine_death:
579 cell.o == CLOSED ? op.scheme->field_closed:
580 /*.......................*/ op.scheme->number[f.c[l][c].n]);
581 else if (mode == SHOWFLAGS) return (
582 /* on win (everything opened, only correct flags left) */
583 cell.m == STD_MINE ? op.scheme->field_flagged:
584 /*.......................*/ op.scheme->number[f.c[l][c].n]);
585 else return (
586 cell.f == FLAG ? op.scheme->field_flagged:
587 cell.f == QUESM ? op.scheme->field_question:
588 cell.o == CLOSED ? op.scheme->field_closed:
589 cell.m == STD_MINE ? op.scheme->mine_normal:
590 cell.m == DEATH_MINE ? op.scheme->mine_death:
591 /*.......................*/ op.scheme->number[f.c[l][c].n]);
592 }
593
594 void redraw_cell (int l, int c, int mode) {
595 move_ph (l+LINE_OFFSET, field2screen_c(c));
596 if (mode == HIGHLIGHT) printf ("\033[7m"); /* reverse video */
597 print (cell2schema(l, c, mode));
598 if (mode == HIGHLIGHT) printf ("\033[0m"); /* reset all */
599 }
600
601 char* get_emoticon(void) {
602 return g.o==GAME_WON ? EMOT(WON):
603 g.o==GAME_LOST? EMOT(DEAD):
604 EMOT(SMILE);
605 }
606
607 /* https://zserge.com/blog/c-for-loop-tricks.html */
608 #define print_line(which) \
609 for (int _break = (printf("%s", BORDER(which,LEFT)), 1); _break; \
610 _break = 0, printf("%s\r\n", BORDER(which,RIGHT)))
611 #define print_border(which, width) \
612 print_line(which) printm (width, BORDER(which,MIDDLE))
613 void show_minefield (int mode) {
614 int dtime = difftime (time(NULL), g.t)*!!g.t;
615 int half_spaces = f.w*op.scheme->cell_width/2;
616 int left_spaces = MAX(0,half_spaces-7-(f.m-g.f>999));
617 int right_spaces = MAX(0,half_spaces-6-(dtime>999));
618 static char modechar[] = {'*', '!', '?'};
619
620 move_ph (0,0);
621
622 print_border(TOP, f.w);
623 print_line(STATUS) {
624 printf("[%03d%c]%*s%s%*s[%03d]",
625 /* [ */ f.m - g.f, modechar[g.s], /* ] */
626 left_spaces,"", get_emoticon(), right_spaces,"",
627 /* [ */ dtime /* ] */);
628 }
629 print_border(DIVIDER, f.w);
630 /* main body */
631 for (int l = 0; l < f.h; l++) print_line(FIELD)
632 printm (f.w, cell2schema(l, _loop, mode));
633 print_border(BOTTOM, f.w);
634 }
635
636 void show_stomp (int enable, int l, int c) {
637 if (enable) {
638 if (f.c[l][c].o == OPENED && get_neighbours (l, c, 1) != 0) {
639 /* show the stomp radius if we aren't fully flagged */
640 AROUND(l, c)
641 if (AR_CELL.o == CLOSED && AR_CELL.f != FLAG)
642 redraw_cell (ROW, COL, HIGHLIGHT);
643 fflush(stdout); /* won't display without */
644 }
645 } else {
646 AROUND(l, c) redraw_cell (ROW, COL, g.o?SHOWMINES:NORMAL);
647 }
648 }
649
650 void wait_stomp (void) {
651 /* block SIGALRM, otherwise poll gets cancelled by the timer: */
652 sigset_t sig;
653 sigemptyset (&sig);
654 sigaddset(&sig, SIGALRM);
655 sigprocmask (SIG_BLOCK, &sig, NULL);
656
657 /* wait for timout or keypress: */
658 struct pollfd fds;
659 fds.fd = 0; fds.events = POLLIN;
660 poll(&fds, 1, STOMP_TIMEOUT);
661
662 /* restore signal mask: */
663 sigprocmask (SIG_UNBLOCK, &sig, NULL);
664 }
665
666 int get_neighbours (int line, int col, int reduced_mode) {
667 /* counts mines surrounding a square
668 modes: 0=normal; 1=reduced */
669
670 int count = 0;
671 AROUND(line, col) {
672 count += !!AR_CELL.m;
673 count -= reduced_mode * AR_CELL.f==FLAG;
674 }
675 return count;
676 }
677
678 void interactive_resize(void) {
679 unsigned char buf[3];
680 int old_w = f.w;
681 int old_h = f.h;
682 for(;;) {
683 screen_setup(1); /* clears the screen */
684 show_minefield (RESIZEMODE);
685 /* show the new field size in the corner: */
686 move_ph(f.h+LINE_OFFSET-1,COL_OFFSET);
687 printf("%d x %d", f.w, f.h);
688 move_ph(LINE_BELOW, 0);
689 printf("Resize Mode: Enter to set, Q to abort");
690 //TODO: need escape seq. to print lowercase in `-d' mode!
691
692 free_field(); /* must free before resizing! */
693 switch (getctrlseq(buf)) {
694 case CTRSEQ_CURSOR_LEFT: case 'h': f.w--; break;
695 case CTRSEQ_CURSOR_DOWN: case 'j': f.h++; break;
696 case CTRSEQ_CURSOR_UP: case 'k': f.h--; break;
697 case CTRSEQ_CURSOR_RIGHT:case 'l': f.w++; break;
698 case 'w': f.w+=BIG_MOVE; break;
699 case 'b': f.w-=BIG_MOVE; break;
700 case 'u': f.h-=BIG_MOVE; break;
701 case 'd': f.h+=BIG_MOVE; break;
702 case 0xa: return; /* enter */
703 case 'q': /* abort */
704 f.w = old_w;
705 f.h = old_h;
706 screen_setup(1);
707 return;
708 }
709
710 clamp_fieldsize();
711 f.m = mines_percentage(f.w, f.h);
712 f.c = alloc_array (f.h, f.w);
713 }
714 }
715
716 struct minecell** alloc_array (int lines, int cols) {
717 free_field (); /* NOTE: this feels like a hack :| */
718 struct minecell** a = malloc (lines * sizeof(struct minecell*));
719 if (a == NULL) return NULL;
720 for (int l = 0; l < lines; l++) {
721 a[l] = calloc (cols, sizeof(struct minecell));
722 if (a[l] == NULL) goto unalloc;
723 }
724
725 return a;
726 unalloc:
727 for (int l = 0; l < lines; l++)
728 free (a[l]);
729 return NULL;
730 }
731
732 void free_field (void) {
733 if (f.c == NULL) return;
734 for (int l = 0; l < f.h; l++) {
735 free (f.c[l]);
736 }
737
738 free (f.c);
739 f.c = NULL;
740 }
741
742 int screen2field_l (int l) {
743 return (l-LINE_OFFSET) - 1;
744 }
745 int screen2field_c (int c) {
746 /* this depends on the cell width and only works when it is 1 or 2. */
747 return (c-COL_OFFSET+1 - 2*(CW%2))/2 - CW/2;
748 }
749 int field2screen_c (int c) {
750 return (CW*c+COL_OFFSET - (CW%2));
751 }
752 int clicked_emoticon (unsigned char* mouse) {
753 return (mouse[2] == LINE_OFFSET-1 && (
754 mouse[1] == f.w+COL_OFFSET ||
755 mouse[1] == f.w+COL_OFFSET+1));
756 }
757
758 enum esc_states {
759 START,
760 ESC_SENT,
761 CSI_SENT,
762 MOUSE_EVENT,
763 };
764 int getctrlseq (unsigned char* buf) {
765 int c;
766 int state = START;
767 int offset = 0x20; /* never sends control chars as data */
768 while ((c = getchar()) != EOF) {
769 switch (state) {
770 case START:
771 switch (c) {
772 case '\033': state=ESC_SENT; break;
773 default: return c;
774 }
775 break;
776 case ESC_SENT:
777 switch (c) {
778 case '[': state=CSI_SENT; break;
779 default: return CTRSEQ_INVALID;
780 }
781 break;
782 case CSI_SENT:
783 switch (c) {
784 case 'A': return CTRSEQ_CURSOR_UP;
785 case 'B': return CTRSEQ_CURSOR_DOWN;
786 case 'C': return CTRSEQ_CURSOR_RIGHT;
787 case 'D': return CTRSEQ_CURSOR_LEFT;
788 case 'M': state=MOUSE_EVENT; break;
789 default: return CTRSEQ_INVALID;
790 }
791 break;
792 case MOUSE_EVENT:
793 buf[0] = c - offset;
794 buf[1] = getchar() - offset;
795 buf[2] = getchar() - offset;
796 return CTRSEQ_MOUSE;
797 default:
798 return CTRSEQ_INVALID;
799 }
800 }
801 return 2;
802 }
803
804 int getch(unsigned char* buf) {
805 /* returns a character, EOF, or constant for an escape/control sequence - NOT
806 compatible with the ncurses implementation of same name */
807 int action = getctrlseq(buf);
808 int l, c;
809 switch (action) {
810 case CTRSEQ_MOUSE:
811 l = screen2field_l (buf[2]);
812 c = screen2field_c (buf[1]);
813
814 if (buf[0] > 3) break; /* ignore all but left/middle/right/up */
815 int success = wait_mouse_up(l, c);
816
817 /* mouse moved while pressed: */
818 if (!success) return CTRSEQ_INVALID;
819
820 switch (buf[0]) {
821 case 0: return CTRSEQ_MOUSE_LEFT;
822 case 1: return CTRSEQ_MOUSE_MIDDLE;
823 case 2: return CTRSEQ_MOUSE_RIGHT;
824 }
825 }
826
827 return action;
828 }
829
830 int getch_wrapper (void) {
831 unsigned char mouse[3];
832 int c;
833 /*skip over ASCII_STX=0x02 that gets sent when returning from SIGALRM:*/
834 while ( (c = getch(mouse)) == 0x02);
835
836 if (c == CTRSEQ_MOUSE_LEFT || c == CTRSEQ_MOUSE_RIGHT) {
837 if (clicked_emoticon(mouse))
838 return WRAPPER_EMOTICON;
839
840 if (screen2field_c (mouse[1]) < 0
841 || screen2field_c (mouse[1]) >= f.w
842 || screen2field_l (mouse[2]) < 0
843 || screen2field_l (mouse[2]) >= f.h)
844 return CTRSEQ_INVALID;
845
846 g.p[0] = screen2field_l (mouse[2]);
847 g.p[1] = screen2field_c (mouse[1]);
848
849 return c; /* CTRSEQ_MOUSE_LEFT || CTRSEQ_MOUSE_RIGHT */
850 }
851
852 return c;
853 }
854
855 void clamp_fieldsize (void) {
856 /* clamp field size to terminal size and mouse maximum: */
857 struct winsize w;
858 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
859
860 /* seven is the minimum width of the status bar */
861 /* NOTE: min of status in DEC mode: 13 (WONTFIX) */
862 if (f.w < 7) f.w = 7;
863 if (f.h < 7) f.h = 7;
864
865 if (COL_OFFSET + f.w*CW + COL_OFFSET > w.ws_col)
866 f.w = (w.ws_col - COL_OFFSET - COL_OFFSET)/DW;
867 if (LINE_OFFSET + f.h + LINES_AFTER > w.ws_row)
868 f.h = w.ws_row - (LINE_OFFSET+LINES_AFTER);
869 if (COL_OFFSET + f.w*CW > MOUSE_MAX)
870 f.w = MOUSE_MAX/CW - COL_OFFSET;
871 if (LINE_OFFSET + f.h > MOUSE_MAX)
872 f.h = MOUSE_MAX - LINE_OFFSET;
873 }
874
875 int mines_percentage(int w, int h) {
876 return w*h*(w*h<30*16?.15625:.20625);
877 }
878
879 int parse_fieldspec(char* str) {
880 /* parses the FIELDSPEC (WxHxM); returns 1 on error */
881 int n = sscanf (str, "%dx%dx%d", &f.w, &f.h, &f.m);
882
883 clamp_fieldsize();
884
885 if (n < 2) {
886 return 1; /* error */
887 } else if (n == 2) {
888 f.m = mines_percentage(f.w, f.h);
889 }
890
891 f.m = MIN(f.m, (f.w-1) * (f.h-1)); /* limit mines */
892
893 return 0;
894 }
895
896 void timer_setup (int enable) {
897 static struct itimerval tbuf;
898 tbuf.it_interval.tv_sec = 1;
899 tbuf.it_interval.tv_usec = 0;
900
901 if (enable) {
902 g.t = time(NULL);
903 tbuf.it_value.tv_sec = 1;
904 tbuf.it_value.tv_usec = 0;
905 if (setitimer(ITIMER_REAL, &tbuf, NULL) == -1) {
906 perror("setitimer");
907 exit(1);
908 }
909 } else {
910 tbuf.it_value.tv_sec = 0;
911 tbuf.it_value.tv_usec = 0;
912 if ( setitimer(ITIMER_REAL, &tbuf, NULL) == -1 ) {
913 perror("setitimer");
914 exit(1);
915 }
916 }
917
918 }
919
920 void signal_setup (void) {
921 struct sigaction saction;
922
923 saction.sa_handler = signal_handler;
924 sigemptyset(&saction.sa_mask);
925 saction.sa_flags = 0;
926 if (sigaction(SIGALRM, &saction, NULL) < 0 ) {
927 perror("SIGALRM");
928 exit(1);
929 }
930
931 if (sigaction(SIGTSTP, &saction, NULL) < 0 ) {
932 perror ("SIGTSTP");
933 exit (1);
934 }
935
936 if (sigaction(SIGCONT, &saction, NULL) < 0 ) {
937 perror ("SIGCONT");
938 exit (1);
939 }
940
941 if (sigaction(SIGINT, &saction, NULL) < 0 ) {
942 perror ("SIGINT");
943 exit (1);
944 }
945 }
946
947 void signal_handler (int signum) {
948 int dtime;
949 switch (signum) {
950 case SIGALRM:
951 dtime = difftime (time(NULL), g.t);
952 move_ph (1, f.w*CW-(CW%2)-3-(dtime>999));
953 printf ("[%03d]", g.t?dtime:0);
954 break;
955 case SIGTSTP: /* interactive stop (C-z) */
956 screen_setup(0); fflush(stdout);
957 signal(SIGTSTP, SIG_DFL); /* NOTE: assumes SysV semantics! */
958 raise(SIGTSTP);
959 break;
960 case SIGCONT:
961 /* NOTE: will leave the VT220 in special graphics charset */
962 screen_setup(1);
963 show_minefield (g.c?SHOWMINES:NORMAL);
964 break;
965 case SIGINT:
966 exit(128+SIGINT);
967 }
968 }
969
970 void screen_setup (int enable) {
971 static int sent_init;
972 if (enable) {
973 raw_mode(1);
974 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
975 printf ("\033[H\033[J"); /* reset cursor, clear screen */
976 printf ("\033[?1000h\033[?25l"); /* enable mouse, hide cursor */
977 if (!sent_init++) /* swich charset, if necessary and only once*/
978 print (op.scheme->init_seq);
979 } else {
980 print (op.scheme->reset_seq); /* reset charset, if necessary */
981 printf ("\033[?1000l\033[?25h");/* disable mouse, show cursor */
982 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
983 raw_mode(0);
984 sent_init = 0;
985 }
986 }
987
988 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
989 void raw_mode(int enable) {
990 static struct termios saved_term_mode;
991 struct termios raw_term_mode;
992
993 if (enable) {
994 if (saved_term_mode.c_lflag == 0)/*don't overwrite stored mode*/
995 tcgetattr(STDIN_FILENO, &saved_term_mode);
996 raw_term_mode = saved_term_mode;
997 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
998 raw_term_mode.c_cc[VMIN] = 1 ;
999 raw_term_mode.c_cc[VTIME] = 0;
1000 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
1001 } else {
1002 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
1003 }
1004 }
Imprint / Impressum