]> git.gir.st - minesVIiper.git/blob - mines_2017.c
fix segfault when clicking out of bound and then using the keyboard
[minesVIiper.git] / mines_2017.c
1 /*******************************************************************************
2 minesviiper 0.3.1459
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 - bduw to jump left/down/up/right by 5 cells
12 - o to open and choord
13 - i to flag/unflag
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 <signal.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <sys/ioctl.h>
25 #include <sys/time.h>
26 #include <termios.h>
27 #include <time.h>
28 #include <unistd.h>
29
30 #include "schemes.h"
31
32 #define LINE_OFFSET 3
33 #define COL_OFFSET 2
34 #define BIG_MOVE 5
35
36 #define MIN(a,b) (a>b?b:a)
37 #define MAX(a,b) (a>b?a:b)
38 #define CLAMP(a,m,M) (a<m?m:(a>M?M:a))
39 #define printm(n, s) for (int _loop = 0; _loop < n; _loop++) fputs (s, stdout)
40 #define print(str) fputs (str?str:"", stdout)
41 #define EMOT(e) op.scheme->emoticons[EMOT_ ## e]
42 #define BORDER(l, c) op.scheme->border[B_ ## l][B_ ## c]
43
44 struct minecell {
45 unsigned m:2; /* mine?1:killmine?2:0 */
46 unsigned o:1; /* open?1:0 */
47 unsigned f:2; /* flagged?1:questioned?2:0 */
48 unsigned n:4; /* 0<= neighbours <=8 */
49 };
50 struct minefield {
51 struct minecell **c;
52 //TODO: rename w, h to L, C
53 int w; /* width */
54 int h; /* height */
55 int m; /* number of mines */
56
57 int f; /* flags counter */
58 int t; /* time of game start */
59 int p[2]; /* cursor position {line, col} */
60 int s; /* space mode */
61 int o; /* mode */
62 } f;
63
64 struct opt {
65 struct minescheme* scheme;
66 int mode; /* allow flags? quesm? */
67 } op;
68
69 struct line_col {
70 int l;
71 int c;
72 };
73
74 void fill_minefield (int, int);
75 void move (int, int);
76 void cursor_move (int, int);
77 void to_next_boundary (int l, int c, char direction);
78 int getch (unsigned char*);
79 int getctrlseq (unsigned char*);
80 int everything_opened (void);
81 int wait_mouse_up (int, int);
82 void partial_show_minefield (int, int, int);
83 void show_minefield (int);
84 int get_neighbours (int, int, int);
85 int uncover_square (int, int);
86 void flag_square (int, int);
87 void quesm_square (int, int);
88 int choord_square (int, int);
89 int do_uncover (int*);
90 struct minecell** alloc_array (int, int);
91 void free_field (void);
92 char* get_emoticon(void);
93 int screen2field_l (int);
94 int screen2field_c (int);
95 int field2screen_l (int);
96 int field2screen_c (int);
97 void quit(void);
98 void signal_handler (int signum);
99 void timer_setup (int);
100
101 enum modes {
102 NORMAL,
103 REDUCED,
104 SHOWMINES,
105 HIGHLIGHT,
106 };
107 enum flagtypes {
108 NOFLAG,
109 FLAG,
110 QUESM,
111 };
112 enum fieldopenstates {
113 CLOSED,
114 OPENED,
115 };
116 enum game_states {
117 GAME_INPROGRESS,
118 GAME_NEW,
119 GAME_WON,
120 GAME_LOST,
121 };
122 enum space_modes {
123 MODE_OPEN,
124 MODE_FLAG,
125 MODE_QUESM,
126 };
127 enum event {
128 /* for getctrlseq() */
129 CTRSEQ_NULL = 0,
130 CTRSEQ_EOF = -1,
131 CTRSEQ_INVALID = -2,
132 CTRSEQ_MOUSE = -3,
133 /* for getch() */
134 CTRSEQ_MOUSE_LEFT = -4,
135 CTRSEQ_MOUSE_MIDDLE = -5,
136 CTRSEQ_MOUSE_RIGHT = -6,
137 CTRSEQ_CURSOR_LEFT = -7,
138 CTRSEQ_CURSOR_DOWN = -8,
139 CTRSEQ_CURSOR_UP = -9,
140 CTRSEQ_CURSOR_RIGHT = -10,
141 };
142 enum mine_types {
143 NO_MINE,
144 STD_MINE,
145 DEATH_MINE,
146 };
147
148 #define CW op.scheme->cell_width
149 void signal_handler (int signum) {
150 int dtime;
151 switch (signum) {
152 case SIGALRM:
153 dtime = difftime (time(NULL), f.t);
154 move (1, f.w*CW-(CW%2)-3-(dtime>999));
155 printf ("[%03d]", f.t?dtime:0);
156 break;
157 case SIGINT:
158 exit(128+SIGINT);
159 }
160 }
161 #undef CW
162
163 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
164 struct termios saved_term_mode;
165 struct termios set_raw_term_mode() {
166 struct termios cur_term_mode, raw_term_mode;
167
168 tcgetattr(STDIN_FILENO, &cur_term_mode);
169 raw_term_mode = cur_term_mode;
170 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
171 raw_term_mode.c_cc[VMIN] = 1 ;
172 raw_term_mode.c_cc[VTIME] = 0;
173 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
174
175 return cur_term_mode;
176 }
177 void restore_term_mode(struct termios saved_term_mode) {
178 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
179 }
180
181
182 int main (int argc, char** argv) {
183 struct sigaction saction;
184 saved_term_mode = set_raw_term_mode();
185
186 atexit (*quit);
187
188 saction.sa_handler = signal_handler;
189 sigemptyset(&saction.sa_mask);
190 saction.sa_flags = 0;
191 if (sigaction(SIGALRM, &saction, NULL) < 0 ) {
192 perror("SIGALRM");
193 exit(1);
194 }
195
196 if (sigaction(SIGINT, &saction, NULL) < 0 ) {
197 perror ("SIGINT");
198 exit (1);
199 }
200 /* end screen setup */
201
202 op.scheme = &symbols_mono;
203 op.mode = FLAG;
204 /* end defaults */
205 /* parse options */
206 int optget;
207 opterr = 0; /* don't print message on unrecognized option */
208 while ((optget = getopt (argc, argv, "+hnfqcdx")) != -1) {
209 switch (optget) {
210 case 'n': op.mode = NOFLAG; break;
211 case 'f': op.mode = FLAG; break; /*default*/
212 case 'q': op.mode = QUESM; break;
213 case 'c': op.scheme = &symbols_col1; break;
214 case 'd': op.scheme = &symbols_doublewidth; break;
215 case 'h':
216 default:
217 fprintf (stderr, "%s [OPTIONS] [FIELDSPEC]\n"
218 "OPTIONS:\n"
219 " -n(o flagging)\n"
220 " -f(lagging)\n"
221 " -q(uestion marks)\n"
222 " -c(olored symbols)\n"
223 " -d(ec charset symbols)\n"
224 "FIELDSPEC:\n"
225 " WxH[xM] (width 'x' height 'x' mines)\n"
226 " defaults to 30x16x99; mines default to ~20%%\n"
227 "\n"
228 "Keybindings:\n"
229 " hjkl: move left/down/up/right\n"
230 " bduw: move to next boundary\n"
231 " ^Gg$: move to the left/bottom/top/right\n"
232 " o: open/choord\n"
233 " i: flag/unflag\n"
234 " space:modeful cursor (either open or flag)\n"
235 " a: toggle mode for space (open/flag)\n"
236 " mX: set a mark for letter X\n"
237 " `X: move to mark X (aliased to ')\n"
238 " r: start a new game\n"
239 " q: quit\n", argv[0]);
240 _exit(0);
241 }
242 }
243 /* end parse options*/
244 if (optind < argc) { /* parse Fieldspec */
245 int n = sscanf (argv[optind], "%dx%dx%d", &f.w, &f.h, &f.m);
246 struct winsize w;
247 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
248 #define CW op.scheme->cell_width
249 #define WW w.ws_col /*window width */
250 #define WH w.ws_row /*window height */
251 #define FW f.w /* field width */
252 #define FH f.h /* field height */
253 #define MM 231 /* mouse maximum*/
254 #define LB 2 /* left border */
255 #define RB 2 /* right border */
256 #define TB 3 /* top border */
257 #define BB 2 /*bottom border */
258
259 if (LB + FW*CW + RB > WW) FW = WW/CW - (LB+RB);
260 if (TB + FH + BB > WH) FH = WH - (TB+BB);
261 if (LB + FW*CW > MM) FW = MM/CW - LB;
262 if (TB + FH > MM) FH = MM - TB;
263
264 if (n < 2) {
265 fprintf (stderr, "FIELDSPEC: WxH[xM]"
266 " (width 'x' height 'x' mines)\n");
267 return 1;
268 } else if (n == 2) {
269 if (f.w < 30) f.m = f.w*f.h*.15625;
270 else f.m = f.w*f.h*.20625;
271 }
272 #undef CW
273 #undef WW
274 #undef WH
275 #undef FW
276 #undef FH
277 #undef MM
278 #undef LB
279 #undef RB
280 #undef TB
281 #undef BB
282 } else { /* use defaults */
283 f.w = 30;
284 f.h = 16;
285 f.m = 99;
286 }
287 /* check boundaries */
288 if (f.m > (f.w-1) * (f.h-1)) {
289 f.m = (f.w-1) * (f.h-1);
290 fprintf (stderr, "too many mines. reduced to %d.\r\n", f.m);
291 }
292 /* end check */
293
294 newgame:
295 f.c = alloc_array (f.h, f.w);
296
297 f.f = 0;
298 f.t = 0;
299 f.p[0] = 0;
300 f.p[1] = 0;
301
302 int is_newgame = 1;
303 int cheatmode = 0;
304 f.s = MODE_OPEN;
305 f.o = GAME_NEW;
306 struct line_col markers[26];
307 for (int i=26; i; markers[--i].l = -1);
308
309 /* switch to alternate screen */
310 printf ("\033[?47h");
311 /* reset cursor, clear screen */
312 printf ("\033[H\033[J");
313
314 /* swich charset, if necessary */
315 if (op.scheme->init_seq != NULL) print (op.scheme->init_seq);
316
317 show_minefield (NORMAL);
318
319 /* enable mouse, hide cursor */
320 printf ("\033[?1000h\033[?25l");
321
322 while (1) {
323 int l, c;
324 int action;
325 unsigned char mouse[3];
326
327 action = getch(mouse);
328 switch (action) {
329 case ' ':
330 if (f.s == MODE_OPEN ||
331 f.c[f.p[0]][f.p[1]].o == OPENED) {
332 switch (do_uncover(&is_newgame)) {
333 case GAME_LOST: goto lose;
334 case GAME_WON: goto win;
335 }
336 } else if (f.s == MODE_FLAG) {
337 flag_square (f.p[0], f.p[1]);
338 } else if (f.s == MODE_QUESM) {
339 quesm_square (f.p[0], f.p[1]);
340 }
341 break;
342 case 'a':
343 f.s = (f.s+1)%(op.mode+1);
344 show_minefield (cheatmode?SHOWMINES:NORMAL);
345 break;
346 case CTRSEQ_MOUSE_LEFT:
347 /* :D clicked: TODO: won't work in single-width mode! */
348 if (mouse[2] == LINE_OFFSET-1 &&
349 (mouse[1] == f.w+COL_OFFSET ||
350 mouse[1] == f.w+COL_OFFSET+1)) {
351 free_field ();
352 goto newgame;
353 }
354 if (screen2field_c (mouse[1]) < 0 ||
355 screen2field_c (mouse[1]) >= f.w ||
356 screen2field_l (mouse[2]) < 0 ||
357 screen2field_l (mouse[2]) >= f.h) break;
358 f.p[0] = screen2field_l (mouse[2]);
359 f.p[1] = screen2field_c (mouse[1]);
360 /* fallthrough */
361 case 'o':
362 switch (do_uncover(&is_newgame)) {
363 case GAME_LOST: goto lose;
364 case GAME_WON: goto win;
365 }
366 break;
367 case CTRSEQ_MOUSE_RIGHT:
368 if (screen2field_c (mouse[1]) < 0 ||
369 screen2field_c (mouse[1]) >= f.w ||
370 screen2field_l (mouse[2]) < 0 ||
371 screen2field_l (mouse[2]) >= f.h) break;
372 f.p[0] = screen2field_l (mouse[2]);
373 f.p[1] = screen2field_c (mouse[1]);
374 /* fallthrough */
375 case 'i': flag_square (f.p[0], f.p[1]); break;
376 case '?':quesm_square (f.p[0], f.p[1]); break;
377 case CTRSEQ_CURSOR_LEFT:
378 case 'h': cursor_move (f.p[0], f.p[1]-1 ); break;
379 case CTRSEQ_CURSOR_DOWN:
380 case 'j': cursor_move (f.p[0]+1, f.p[1] ); break;
381 case CTRSEQ_CURSOR_UP:
382 case 'k': cursor_move (f.p[0]-1, f.p[1] ); break;
383 case CTRSEQ_CURSOR_RIGHT:
384 case 'l': cursor_move (f.p[0], f.p[1]+1 ); break;
385 case 'w': to_next_boundary (f.p[0], f.p[1], '>'); break;
386 case 'b': to_next_boundary (f.p[0], f.p[1], '<'); break;
387 case 'u': to_next_boundary (f.p[0], f.p[1], '^'); break;
388 case 'd': to_next_boundary (f.p[0], f.p[1], 'v'); break;
389 case '0': /* fallthrough */
390 case '^': cursor_move (f.p[0], 0 ); break;
391 case '$': cursor_move (f.p[0], f.w-1 ); break;
392 case 'g': cursor_move (0, f.p[1] ); break;
393 case 'G': cursor_move (f.h-1, f.p[1] ); break;
394 case 'm':
395 action = tolower(getch(mouse));
396 if (action < 'a' || action > 'z') break;/*out of bound*/
397 markers[action-'a'].l = f.p[0];
398 markers[action-'a'].c = f.p[1];
399 break;
400 case'\'': /* fallthrough */
401 case '`':
402 action = tolower(getch(mouse));
403 if (action < 'a' || action > 'z' /* out of bound or */
404 || markers[action-'a'].l == -1) break; /* unset */
405 cursor_move (markers[action-'a'].l, markers[action-'a'].c);
406 break;
407 case 'r': /* start a new game */
408 free_field ();
409 goto newgame;
410 case 'q':
411 goto quit;
412 case '\014': /* Ctrl-L -- redraw */
413 show_minefield (NORMAL);
414 break;
415 case '\\':
416 if (is_newgame) {
417 is_newgame = 0;
418 fill_minefield (-1, -1);
419 timer_setup(1);
420 }
421 show_minefield (cheatmode?NORMAL:SHOWMINES);
422 cheatmode = !cheatmode;
423 break;
424 }
425 }
426
427 win: f.o = GAME_WON; goto endgame;
428 lose: f.o = GAME_LOST; goto endgame;
429 endgame:
430 timer_setup(0); /* stop timer */
431 show_minefield (SHOWMINES);
432 int gotaction;
433 do {
434 unsigned char mouse[3];
435 gotaction = getch(mouse);
436 /* :D clicked: TODO: won't work in single-width mode! */
437 if (gotaction==CTRSEQ_MOUSE_LEFT && mouse[2]==LINE_OFFSET-1 &&
438 (mouse[1]==f.w+COL_OFFSET || mouse[1]==f.w+COL_OFFSET+1)) {
439 free_field ();
440 goto newgame;
441 } else if (gotaction == 'r') {
442 free_field ();
443 goto newgame;
444 } else if (gotaction == 'q') {
445 goto quit;
446 }
447 } while (1);
448
449 quit:
450 return 0;
451 }
452
453 void quit (void) {
454 //move(0,0); //move(f.h+LINE_OFFSET+2, 0);
455 printf ("\033[?9l\033[?25h"); /* disable mouse, show cursor */
456 print (op.scheme->reset_seq); /* reset charset, if necessary */
457 printf ("\033[?47l"); /* revert to primary screen */
458 free_field ();
459 restore_term_mode(saved_term_mode);
460 }
461
462 /* I haven't won as long as a cell exists, that
463 - I haven't opened, and
464 - is not a mine */
465 int everything_opened (void) {
466 for (int row = 0; row < f.h; row++)
467 for (int col = 0; col < f.w; col++)
468 if (f.c[row][col].o == CLOSED &&
469 f.c[row][col].m == NO_MINE ) return 0;
470 return 1;
471 }
472
473 int wait_mouse_up (int l, int c) {
474 unsigned char mouse2[3];
475 int level = 1;
476 int l2, c2;
477
478 /* show :o face */
479 move (1, field2screen_c (f.w/2)-1); print (EMOT(OHH));
480
481 if (!(l < 0 || l >= f.h || c < 0 || c >= f.w)) {
482 /* show a pushed-in button if cursor is on minefield */
483 move (l+LINE_OFFSET, field2screen_c(c));
484 fputs (op.scheme->mouse_highlight, stdout);
485 }
486
487 while (level > 0) {
488 if (getctrlseq (mouse2) == CTRSEQ_MOUSE) {
489 /* ignore mouse wheel events: */
490 if (mouse2[0] & 0x40) continue;
491
492 else if (mouse2[0]&3 == 3) level--; /* release event */
493 else level++; /* another button pressed */
494 }
495 }
496
497 move (1, field2screen_c (f.w/2)-1); print (get_emoticon());
498
499 if (!(l < 0 || l >= f.h || c < 0 || c >= f.w)) {
500 partial_show_minefield (l, c, NORMAL);
501 }
502 c2 = screen2field_c(mouse2[1]);
503 l2 = screen2field_l(mouse2[2]);
504 return ((l2 == l) && (c2 == c));
505 }
506
507 int choord_square (int line, int col) {
508 for (int l = MAX(line-1, 0); l <= MIN(line+1, f.h-1); l++) {
509 for (int c = MAX(col-1, 0); c <= MIN(col+1, f.w-1); c++) {
510 if (f.c[l][c].f != FLAG) {
511 if (uncover_square (l, c))
512 return 1;
513 }
514 }
515 }
516
517 return 0;
518 }
519
520 int uncover_square (int l, int c) {
521 f.c[l][c].o = OPENED;
522 f.c[l][c].f = NOFLAG; /*must not be QUESM, otherwise rendering issues*/
523 partial_show_minefield (l, c, NORMAL);
524
525 if (f.c[l][c].m) {
526 f.c[l][c].m = DEATH_MINE;
527 return 1;
528 }
529
530 /* check for chording */
531 if (f.c[l][c].n == 0) {
532 for (int choord_l = -1; choord_l <= 1; choord_l++) {
533 for (int choord_c = -1; choord_c <= 1; choord_c++) {
534 int newl = l + choord_l;
535 int newc = c + choord_c;
536 if (newl >= 0 && newl < f.h &&
537 newc >= 0 && newc < f.w &&
538 f.c[newl][newc].o == CLOSED &&
539 uncover_square (newl, newc)) {
540 return 1;
541 }
542 }
543 }
544 }
545
546 return 0;
547 }
548
549 void flag_square (int l, int c) {
550 static char modechar[] = {'*', '!', '?'};
551
552 if (f.c[l][c].o != CLOSED) return;
553 /* cycles through flag/quesm/noflag (uses op.mode to detect which ones
554 are allowed) */
555 f.c[l][c].f = (f.c[l][c].f + 1) % (op.mode + 1);
556 if (f.c[l][c].f==FLAG) f.f++;
557 else f.f--; //WARN: breaks on `-q'!
558 partial_show_minefield (l, c, NORMAL);
559 move (1, op.scheme->cell_width);
560 printf ("[%03d%c]", f.m - f.f, modechar[f.s]);
561 }
562
563 void quesm_square (int l, int c) {
564 /* toggle question mark / none. won't turn flags into question marks.
565 unlike flag_square, this function doesn't respect `-q'. */
566 if (f.c[l][c].o != CLOSED) return;
567 else if (f.c[l][c].f == NOFLAG) f.c[l][c].f = QUESM;
568 else if (f.c[l][c].f == QUESM) f.c[l][c].f = NOFLAG;
569 partial_show_minefield (l, c, NORMAL);
570 }
571
572 int do_uncover (int* is_newgame) {
573 if (*is_newgame) {
574 *is_newgame = 0;
575 fill_minefield (f.p[0], f.p[1]);
576 timer_setup(1);
577 }
578
579 if (f.c[f.p[0]][f.p[1]].f == FLAG ) return GAME_INPROGRESS;
580 if (f.c[f.p[0]][f.p[1]].o == CLOSED) {
581 if (uncover_square (f.p[0], f.p[1])) return GAME_LOST;
582 } else if (get_neighbours (f.p[0], f.p[1], 1) == 0) {
583 if (choord_square (f.p[0], f.p[1])) return GAME_LOST;
584 }
585 if (everything_opened()) return GAME_WON;
586
587 return GAME_INPROGRESS;
588 }
589
590 void fill_minefield (int l, int c) {
591 srand (time(0));
592 int mines_set = f.m;
593 while (mines_set) {
594 int line = rand() % f.h;
595 int col = rand() % f.w;
596
597 if (f.c[line][col].m) {
598 /* skip if field already has a mine */
599 continue;
600 } else if ((line == l) && (col == c)) {
601 /* don't put a mine on the already opened (first click) field */
602 continue;
603 } else {
604 mines_set--;
605 f.c[line][col].m = STD_MINE;
606 }
607 }
608
609 /* precalculate neighbours */
610 for (int l=0; l < f.h; l++)
611 for (int c=0; c < f.w; c++)
612 f.c[l][c].n = get_neighbours (l, c, NORMAL);
613 }
614
615 void move (int line, int col) {
616 printf ("\033[%d;%dH", line+1, col+1);
617 }
618
619 /* absolute coordinates! */
620 void cursor_move (int l, int c) {
621 partial_show_minefield (f.p[0], f.p[1], NORMAL);
622 /* update f.p */
623 f.p[0] = CLAMP(l, 0, f.h-1);
624 f.p[1] = CLAMP(c, 0, f.w-1);
625 move (f.p[0]+LINE_OFFSET, field2screen_c(f.p[1]));
626 //fputs (op.scheme->mouse_highlight, stdout);
627
628 /* invert unless ! or ? (and flag_offset is used in the scheme): */
629 if (!f.c[f.p[0]][f.p[1]].f || !op.scheme->flag_offset)
630 print("\033[7m");
631 partial_show_minefield (f.p[0], f.p[1], HIGHLIGHT);
632 print("\033[0m");//un-invert
633 }
634
635 /* to_next_boundary(): move into the supplied direction until a change in open-
636 state or flag-state is found and move there. falls back to BIG_MOVE. */
637 #define FIND_NEXT(X, L, C, L1, C1, MAX, OP) do {\
638 new_ ## X OP ## = BIG_MOVE;\
639 for (int i = X OP 1; i > 0 && i < f.MAX-1; i OP ## OP)\
640 if ((f.c[L ][C ].o<<2 + f.c[L ][C ].f) \
641 != (f.c[L1][C1].o<<2 + f.c[L1][C1].f)) {\
642 new_ ## X = i OP 1;\
643 break;\
644 }\
645 } while(0)
646 void to_next_boundary (int l, int c, char direction) {
647 int new_l = l;
648 int new_c = c;
649 switch (direction) {
650 case '>': FIND_NEXT(c, l, i, l, i+1, w, +); break;
651 case '<': FIND_NEXT(c, l, i, l, i-1, w, -); break;
652 case '^': FIND_NEXT(l, i, c, i-1, c, h, -); break;
653 case 'v': FIND_NEXT(l, i, c, i+1, c, h, +); break;
654 }
655
656 cursor_move (new_l, new_c);
657 }
658 #undef FIND_NEXT
659
660 char* cell2schema (int l, int c, int mode) {
661 struct minecell cell = f.c[l][c];
662 /* move past invert-ctrlsequence when highlighting the cursor: */
663 int offset = ((mode==HIGHLIGHT)*op.scheme->flag_offset);
664
665 if (mode == SHOWMINES) return (
666 cell.f == FLAG && cell.m ? op.scheme->field_flagged+offset:
667 cell.f == FLAG && !cell.m ? op.scheme->mine_wrongf:
668 cell.m == STD_MINE ? op.scheme->mine_normal:
669 cell.m == DEATH_MINE ? op.scheme->mine_death:
670 cell.o == CLOSED ? op.scheme->field_closed:
671 /*.......................*/ op.scheme->number[f.c[l][c].n]);
672 else return (
673 cell.f == FLAG ? op.scheme->field_flagged+offset:
674 cell.f == QUESM ? op.scheme->field_question+offset:
675 cell.o == CLOSED ? op.scheme->field_closed:
676 cell.m == STD_MINE ? op.scheme->mine_normal:
677 cell.m == DEATH_MINE ? op.scheme->mine_death:
678 /*.......................*/ op.scheme->number[f.c[l][c].n]);
679 }
680
681 void partial_show_minefield (int l, int c, int mode) {
682 move (l+LINE_OFFSET, field2screen_c(c));
683
684 print (cell2schema(l, c, mode));
685 }
686
687 char* get_emoticon(void) {
688 return f.o==GAME_WON ? EMOT(WON):
689 f.o==GAME_LOST? EMOT(DEAD):
690 EMOT(SMILE);
691 }
692
693 /* https://zserge.com/blog/c-for-loop-tricks.html */
694 #define print_line(which) \
695 for (int _break = (printf(BORDER(which,LEFT)), 1); _break; \
696 _break = 0, printf("%s\r\n", BORDER(which,RIGHT)))
697 #define print_border(which, width) \
698 print_line(which) printm (width, BORDER(which,MIDDLE))
699 void show_minefield (int mode) {
700 int dtime;
701 int half_spaces = f.w*op.scheme->cell_width/2;
702 int left_spaces = MAX(0,half_spaces-7-(f.m-f.f>999)+2);
703 int right_spaces = MAX(0,half_spaces-6-(dtime>999));
704 static char modechar[] = {'*', '!', '?'};
705
706 move (0,0);
707
708 dtime = (f.t == 0)?0: difftime (time(NULL), f.t);
709
710 print_border(TOP, f.w);
711 print_line(STATUS) {
712 printf("[%03d%c]%*s%*s[%03d]",
713 /* [ */ f.m - f.f, modechar[f.s], /* ] */
714 left_spaces, get_emoticon(), right_spaces,"",
715 /* [ */ dtime /* ] */);
716 }
717 print_border(DIVIDER, f.w);
718 /* main body */
719 for (int l = 0; l < f.h; l++) print_line(FIELD)
720 printm (f.w, cell2schema(l, _loop, mode));
721 print_border(BOTTOM, f.w);
722 }
723
724 int get_neighbours (int line, int col, int reduced_mode) {
725 /* counts mines surrounding a square
726 modes: 0=normal; 1=reduced */
727
728 int count = 0;
729
730 for (int l = MAX(line-1, 0); l <= MIN(line+1, f.h-1); l++) {
731 for (int c = MAX(col-1, 0); c <= MIN(col+1, f.w-1); c++) {
732 if (!l && !c) continue;
733
734 count += !!f.c[l][c].m;
735 count -= reduced_mode * f.c[l][c].f==FLAG;
736 }
737 }
738 return count;
739 }
740
741 struct minecell** alloc_array (int lines, int cols) {
742 struct minecell** a = malloc (lines * sizeof(struct minecell*));
743 if (a == NULL) return NULL;
744 for (int l = 0; l < lines; l++) {
745 a[l] = calloc (cols, sizeof(struct minecell));
746 if (a[l] == NULL) goto unalloc;
747 }
748
749 return a;
750 unalloc:
751 for (int l = 0; l < lines; l++)
752 free (a[l]);
753 return NULL;
754 }
755
756 void free_field (void) {
757 if (f.c == NULL) return;
758 for (int l = 0; l < f.h; l++) {
759 free (f.c[l]);
760 }
761
762 free (f.c);
763 f.c = NULL;
764 }
765
766 int screen2field_l (int l) {
767 return (l-LINE_OFFSET) - 1;
768 }
769 /* some trickery is required to extract the mouse position from the cell width,
770 depending on wheather we are using full width characters or double line width.
771 WARN: tested only with scheme.cell_width = 1 and scheme.cell_width = 2. */
772 #define CW op.scheme->cell_width
773 int screen2field_c (int c) {
774 return (c-COL_OFFSET+1 - 2*(CW%2))/2 - CW/2;
775 }
776 #undef CW
777 int field2screen_l (int l) {
778 return 0; //TODO: is never used, therefore not implemented
779 }
780 int field2screen_c (int c) {
781 return (op.scheme->cell_width*c+COL_OFFSET - (op.scheme->cell_width%2));
782 }
783
784 enum esc_states {
785 START,
786 ESC_SENT,
787 CSI_SENT,
788 MOUSE_EVENT,
789 };
790 int getctrlseq (unsigned char* buf) {
791 int c;
792 int state = START;
793 int offset = 0x20; /* never sends control chars as data */
794 while ((c = getchar()) != EOF) {
795 switch (state) {
796 case START:
797 switch (c) {
798 case '\033': state=ESC_SENT; break;
799 default: return c;
800 }
801 break;
802 case ESC_SENT:
803 switch (c) {
804 case '[': state=CSI_SENT; break;
805 default: return CTRSEQ_INVALID;
806 }
807 break;
808 case CSI_SENT:
809 switch (c) {
810 case 'A': return CTRSEQ_CURSOR_UP;
811 case 'B': return CTRSEQ_CURSOR_DOWN;
812 case 'C': return CTRSEQ_CURSOR_RIGHT;
813 case 'D': return CTRSEQ_CURSOR_LEFT;
814 case 'M': state=MOUSE_EVENT; break;
815 default: return CTRSEQ_INVALID;
816 }
817 break;
818 case MOUSE_EVENT:
819 buf[0] = c - offset;
820 buf[1] = getchar() - offset;
821 buf[2] = getchar() - offset;
822 return CTRSEQ_MOUSE;
823 default:
824 return CTRSEQ_INVALID;
825 }
826 }
827 return 2;
828 }
829
830 int getch(unsigned char* buf) {
831 /* returns a character, EOF, or constant for an escape/control sequence - NOT
832 compatible with the ncurses implementation of same name */
833 int action = getctrlseq(buf);
834 int l, c;
835 switch (action) {
836 case CTRSEQ_MOUSE:
837 l = screen2field_l (buf[2]);
838 c = screen2field_c (buf[1]);
839
840 if (buf[0] > 3) break; /* ignore all but left/middle/right/up */
841 int success = wait_mouse_up(l, c);
842
843 /* mouse moved while pressed: */
844 if (!success) return CTRSEQ_INVALID;
845
846 switch (buf[0]) {
847 case 0: return CTRSEQ_MOUSE_LEFT;
848 case 1: return CTRSEQ_MOUSE_MIDDLE;
849 case 2: return CTRSEQ_MOUSE_RIGHT;
850 }
851 }
852
853 return action;
854 }
855
856 void timer_setup (int enable) {
857 static struct itimerval tbuf;
858 tbuf.it_interval.tv_sec = 1;
859 tbuf.it_interval.tv_usec = 0;
860
861 if (enable) {
862 f.t = time(NULL);
863 tbuf.it_value.tv_sec = 1;
864 tbuf.it_value.tv_usec = 0;
865 if (setitimer(ITIMER_REAL, &tbuf, NULL) == -1) {
866 perror("setitimer");
867 exit(1);
868 }
869 } else {
870 tbuf.it_value.tv_sec = 0;
871 tbuf.it_value.tv_usec = 0;
872 if ( setitimer(ITIMER_REAL, &tbuf, NULL) == -1 ) {
873 perror("setitimer");
874 exit(1);
875 }
876 }
877
878 }
Imprint / Impressum