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