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