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