]> git.gir.st - VIper.git/blob - viiper.c
refactor pause screen; todos, readme updated
[VIper.git] / viiper.c
1 /*******************************************************************************
2 viiper 0.1
3 By Tobias Girstmair, 2018
4
5 ./viiper 40x25
6 (see ./viiper -h for full list of options)
7
8 KEYBINDINGS: - hjkl to move
9 - p to pause and resume
10 - r to restart
11 - q to quit
12 - (see `./minesviiper -h' for all keybindings)
13
14 GNU GPL v3, see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt
15 *******************************************************************************/
16
17
18 #define _POSIX_C_SOURCE 2 /*for getopt and sigaction in c99, sigsetjmp*/
19 #include <setjmp.h>
20 #include <signal.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.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 "viiper.h"
31 #include "schemes.h"
32
33 #define MIN(a,b) (a>b?b:a)
34 #define MAX(a,b) (a>b?a:b)
35 #define CLAMP(a,m,M) (a<m?m:(a>M?M:a))
36 #define printm(n, s) for (int _loop = 0; _loop < n; _loop++) fputs (s, stdout)
37 #define print(str) fputs (str?str:"", stdout)
38 #define CTRL_ 0x1F &
39
40 #define OPPOSITE(dir) ( \
41 dir == EAST ? WEST : \
42 dir == WEST ? EAST : \
43 dir == NORTH ? SOUTH : \
44 dir == SOUTH ? NORTH : -1)
45
46 #define COL_OFFSET 1
47 #define LINE_OFFSET 1
48 #define LINES_AFTER 1
49 #define CW op.sch->cell_width
50
51 #define SPEEDUP_AFTER 100 /* increment speed every n points */
52 #define BONUS_INTERVAL 90 /* how often a bonus item is spawned */
53 #define BONUS_DURATION 15 /* how long one can catch the bonus */
54 #define BONUS_WARN 5 /* how long before the removal to warn */
55
56 struct game {
57 int w; /* field width */
58 int h; /* field height */
59 int d; /* direction the snake is looking */
60 int p; /* score */
61 float v; /* velocity in moves per second */
62 time_t t; /* time of game start */
63 time_t b; /* time of next bonus item spawn */
64 struct snake* s; /* snek */
65 struct item* i; /* items (food, boni) */
66 struct directions {
67 int h; /* write head */
68 int n; /* number of elements */
69 int c[16];
70 } k; /* ring buffer for direction events */
71 } g;
72
73 struct opt {
74 int l; /* initial snake length */
75 int s; /* initial snake speed */
76 struct scheme* sch;
77 } op;
78
79 jmp_buf game_over;
80
81 int main (int argc, char** argv) {
82 /* defaults: */
83 g.w = 30;
84 g.h = 20;
85 op.l = 10;
86 op.s = 8;
87 op.sch = &unic0de;
88
89 int optget;
90 opterr = 0; /* don't print message on unrecognized option */
91 while ((optget = getopt (argc, argv, "+s:l:dh")) != -1) {
92 switch (optget) {
93 case 's':
94 op.s = atof(optarg);
95 if (op.s < 1) {
96 fprintf (stderr, "speed must be >= 1\n");
97 return 1;
98 }
99 break;
100 case 'l':
101 op.l = atoi(optarg);
102 if (op.s < 2 || op.s > g.w*g.h-1) {
103 fprintf (stderr, "length must be >= 2 and < W*H\n");
104 return 1;
105 }
106 break;
107 case 'd': op.sch = &vt220_charset; break;
108 case 'h':
109 default:
110 fprintf (stderr, SHORTHELP LONGHELP, argv[0]);
111 return !(optget=='h');
112 }
113 } if (optind < argc) { /* parse Fieldspec */
114 int n = sscanf (argv[optind], "%dx%d", &g.w, &g.h);
115
116 if (n < 2) {
117 fprintf(stderr,"FIELDSIZE is WxH (width 'x' height)\n");
118 return 1;
119 }
120 }
121
122 clamp_fieldsize();
123
124 srand(time(0));
125 signal_setup();
126 screen_setup(1);
127 atexit (*quit);
128
129 char* end_screen_msg = "";
130 restart:
131 switch (sigsetjmp(game_over, 1)) {
132 case GAME_INIT:
133 case GAME_START:
134 viiper();
135 break; /* function doesn't return, but `-Wextra' complains */
136 case GAME_OVER:
137 end_screen_msg = " GAME OVER ";
138 goto end_screen;
139 case GAME_WON:
140 end_screen_msg = "CONGRATULATIONS!";
141 goto end_screen;
142 end_screen:
143 timer_setup(0);
144 show_playfield();
145 for (;;) switch (end_screen(end_screen_msg)) {
146 case 'r': goto restart;
147 case 'q': goto quit;
148 case CTRL_'L':
149 screen_setup(1);
150 show_playfield();
151 break;
152 default: continue;
153 }
154 case GAME_EXIT:
155 goto quit;
156 }
157
158 quit:
159 return 0;
160 }
161
162 int viiper(void) {
163 init_snake();
164 show_playfield ();
165 g.d = EAST;
166 g.v = op.s;
167
168 timer_setup(1);
169 g.t = time(NULL);
170 g.p = 0;
171 g.k.n = 0;
172 g.b = time(NULL) + BONUS_INTERVAL;
173
174 spawn_item(FOOD, rand() % NUM_FOODS, NULL); //TODO: shape distribution, so bigger values get selected less
175
176 for(;;) {
177 switch (getctrlseq()) {
178 case 'h': case CTRSEQ_CURSOR_LEFT: append_movement(WEST); break;
179 case 'j': case CTRSEQ_CURSOR_DOWN: append_movement(SOUTH);break;
180 case 'k': case CTRSEQ_CURSOR_UP: append_movement(NORTH);break;
181 case 'l': case CTRSEQ_CURSOR_RIGHT:append_movement(EAST); break;
182 case 'p': pause_game(); break;
183 case 'r': siglongjmp(game_over, GAME_START);
184 case 'q': siglongjmp(game_over, GAME_EXIT);
185 case CTRL_'L':
186 screen_setup(1);
187 show_playfield();
188 break;
189 case 0x02: /* STX; gets sent when returning from SIGALRM */
190 continue;
191 }
192 }
193
194 }
195
196 #define pop_dir() (g.k.n? g.k.c[(16+g.k.h-g.k.n--)%16] : NONE)
197 void snake_advance (void) {
198 int respawn = 0;
199 struct item* i; /*temporary item (defined here to respawn at the end) */
200 int new_dir = pop_dir();
201 /* switch direction if new one is in the buffer and it won't kill us: */
202 if (new_dir && g.d != OPPOSITE(new_dir)) g.d = new_dir;
203
204 int new_row = g.s->r +(g.d==SOUTH) -(g.d==NORTH);
205 int new_col = g.s->c +(g.d==EAST) -(g.d==WEST);
206
207 /* detect food hit and spawn a new food */
208 for (i = g.i; i; i = i->next) {
209 if (i->r == new_row && i->c == new_col) {
210 consume_item (i);
211
212 switch (i->t) {
213 case FOOD: respawn = 1; break;
214 case BONUS: remove_bonus(i); break;
215 }
216 break;
217 }
218 }
219
220 if (new_row >= g.h || new_col >= g.w || new_row < 0 || new_col < 0)
221 siglongjmp(game_over, GAME_OVER);
222
223 struct snake* new_head;
224 struct snake* new_tail; /* former second-to-last element */
225 for (new_tail = g.s; new_tail->next->next; new_tail = new_tail->next)
226 /*use the opportunity of looping to check if we eat ourselves:*/
227 if(new_tail->next->r == new_row && new_tail->next->c == new_col)
228 siglongjmp(game_over, GAME_OVER);
229 int old_tail[2] = {new_tail->next->r, new_tail->next->c};/*gets erased*/
230 new_head = new_tail->next; /* reuse element instead of malloc() */
231 new_tail->next = NULL;
232
233 new_head->r = new_row;
234 new_head->c = new_col;
235 new_head->next = g.s;
236
237 g.s = new_head;
238
239 if (respawn) spawn_item(FOOD, rand() % NUM_FOODS, i);
240 draw_sprites (old_tail[0], old_tail[1]);
241 }
242
243 void spawn_item (int type, int value, struct item* p_item) {
244 int row, col;
245 char occupied[g.w][g.h]; int snake_len = 0;
246 memset(*occupied, 0, g.w*g.h);
247 try_again:
248 row = rand() % g.h;
249 col = rand() % g.w;
250 if (snake_len >= g.w*g.h-1) siglongjmp(game_over, GAME_WON);
251 /* loop through snake to check if we aren't on it */
252 if (occupied[row][col]) goto try_again; /* shortcut */
253 for (struct snake* s = g.s; s; s = s->next)
254 if (s->r == row && s->c == col) {
255 occupied[s->r][s->c] = 1; snake_len++;
256 goto try_again;
257 }
258
259 /* if we got a item buffer reuse it, otherwise create a new one: */
260 struct item* new_item;
261 if (p_item) new_item = p_item;
262 else new_item = malloc (sizeof(struct item));
263
264 new_item->r = row;
265 new_item->c = col;
266 new_item->t = type;
267 new_item->v = value;
268 new_item->s = time(0);
269 if (g.i) g.i->prev = new_item;
270 new_item->next = g.i;
271 new_item->prev = NULL;
272
273 g.i = new_item;
274 }
275
276 void consume_item (struct item* i) {
277 int old_score = g.p;
278
279 switch (i->t) {
280 case FOOD:
281 switch (i->v) {
282 case FOOD_5: g.p += 5; break;
283 case FOOD_10: g.p += 10; break;
284 case FOOD_20: g.p += 20; break;
285 }
286 snake_append(&g.s, -1, -1);
287 break; /* will be reused as the head before it is drawn */
288 case BONUS:
289 switch (i->v) {
290 case BONUS_SNIP:
291 for (int i = 5; i && g.s->next->next; i--) {
292 struct snake* p = g.s;
293 while (p->next->next) p = p->next;
294 free (p->next);
295 p->next = NULL;
296 }
297 show_playfield();
298 break;
299 case BONUS_GROW:
300 for (int i = 5; i; i--) snake_append(&g.s, -1, -1);
301 break;
302 case BONUS_SLOW:
303 if (g.v > 1) g.v--;
304 timer_setup(1);
305 break;
306 case BONUS_FAST:
307 g.v++;
308 timer_setup(1);
309 break;
310 }
311 break;
312 }
313
314 if (i->next) i->next->prev = i->prev;
315 if (i->prev) i->prev->next = i->next;
316 else g.i = i->next;
317
318 /* snake speedup every 100 points: */
319 if (g.p/SPEEDUP_AFTER - old_score/SPEEDUP_AFTER) g.v++, timer_setup(1);
320 }
321
322 void spawn_bonus(void) {
323 for (struct item* i = g.i; i; i = i->next)
324 if (i->t == BONUS) { /* bonus already there */
325 if (((i->s+BONUS_DURATION)-time(NULL)) < 0) {
326 remove_bonus(i); /* remove if over lifetime */
327 }
328 return;
329 }
330 if (g.b < time(NULL)) { /* time to spawn item: */
331 spawn_item(BONUS, rand() % NUM_BONI, NULL);
332 g.b = time(NULL) + BONUS_INTERVAL; //TODO: only start counting after old bonus was removed/eaten
333 }
334 }
335
336 void show_playfield (void) {
337 move_ph (0,0);
338
339 /* top border */
340 print(BORDER(T,L));
341 printm (g.w, BORDER(T,C));
342 printf ("%s\n", BORDER(T,R));
343
344 /* main area */
345 for (int row = 0; row < g.h; row++)
346 printf ("%s%*s%s\n", BORDER(C,L), CW*g.w, "", BORDER(C,R));
347
348 /* bottom border */
349 print(BORDER(B,L));
350 printm (g.w, BORDER(B,C));
351 print (BORDER(B,R));
352
353 draw_sprites (-1,-1);
354 }
355
356 void draw_sprites (int erase_r, int erase_c) {
357 /* erase old tail, if any */
358 if (erase_r >= 0 && erase_c >= 0) {
359 move_ph (erase_r+LINE_OFFSET, erase_c*CW+COL_OFFSET);
360 printm (CW, " ");
361 }
362
363 /* print snake */
364 struct snake* last = NULL;
365 int color = 2;
366 for (struct snake* s = g.s; s; s = s->next) {
367 if (s->r < 0 || s->c < 0) continue; /*can't draw outside term.*/
368 move_ph (s->r+LINE_OFFSET, s->c*CW+COL_OFFSET);
369
370 int predecessor = (last==NULL)?NONE:
371 (last->r < s->r) ? NORTH:
372 (last->r > s->r) ? SOUTH:
373 (last->c > s->c) ? EAST:
374 (last->c < s->c) ? WEST:NONE;
375 int successor = (s->next == NULL)?NONE:
376 (s->next->r < s->r) ? NORTH:
377 (s->next->r > s->r) ? SOUTH:
378 (s->next->c > s->c) ? EAST:
379 (s->next->c < s->c) ? WEST:NONE;
380
381 printf ("\033[%sm", op.sch->color[color]);
382 print (op.sch->snake[predecessor][successor]);
383 printf ("\033[0m");
384 last = s;
385 color = !color;
386 }
387
388 /* print item queue */
389 for (struct item* i = g.i; i; i = i->next) {
390 move_ph (i->r+LINE_OFFSET, i->c*CW+COL_OFFSET);
391 if (i->t == FOOD) print(op.sch->food[i->v]);
392 else if (i->t == BONUS) {
393 if (i->s + BONUS_DURATION-BONUS_WARN < time(NULL))
394 printf("\033[5m%s\033[25m", op.sch->boni[i->v]);
395 else print(op.sch->boni[i->v]);
396 }
397 }
398
399 /* print score */
400 int score_width = g.p > 9999?6:4;
401 move_ph (0, (g.w*CW-score_width)/2-COL_OFFSET);
402 printf ("%s %0*d %s", BORDER(S,L), score_width, g.p, BORDER(S,R));
403 }
404
405 void pause_game (void) {
406 time_t pause_start = time(NULL);
407 time_t pause_diff;
408 timer_setup(0);
409
410 move_ph (g.h/2+LINE_OFFSET, g.w*CW/2);
411 printf ("\033[5;7m PAUSE \033[0m"); /* blinking reverse text */
412 if (getchar() == 'q')
413 siglongjmp(game_over, GAME_EXIT);
414
415 /* update all timers, so bonus items don't get out of sync: */
416 pause_diff = time(NULL) - pause_start;
417 g.b += pause_diff;
418 for (struct item* i = g.i; i; i = i->next)
419 i->s += pause_diff;
420
421 show_playfield();
422 timer_setup(1);
423 }
424
425 #define MOVE_POPUP(WIDTH, LINE) \
426 move_ph(g.h/2+LINE_OFFSET-1+LINE,(g.w*op.sch->display_width-WIDTH)/2)
427 //TODO: macro does not correctly centre in DEC mode
428 int end_screen(char* message) {
429 int msg_w = strlen(message);
430 MOVE_POPUP(msg_w, -1);
431 print(BORDER(T,L));
432 printm ((msg_w+2)/op.sch->display_width, BORDER(T,C));
433 print (BORDER(T,R));
434
435 MOVE_POPUP(msg_w, 0);
436 printf("%s %s %s", BORDER(C,L), message, BORDER(C,R));
437 MOVE_POPUP(msg_w, 1);
438 //TODO: requires shifting into ASCII/multilingual charset in DEC mode -- put graphics into upper/right charset?
439 printf("%s `r' restart%*s%s", BORDER(C,L), msg_w-10, "", BORDER(C,R));
440 MOVE_POPUP(msg_w, 2);
441 printf("%s `q' quit%*s%s", BORDER(C,L), msg_w-7, "", BORDER(C,R));
442
443 MOVE_POPUP(msg_w, 3);
444 print(BORDER(B,L));
445 printm ((msg_w+2)/op.sch->display_width, BORDER(B,C));
446 print (BORDER(B,R));
447 fflush(stdout);
448
449 return getctrlseq();
450 }
451
452 void snake_append (struct snake** s, int row, int col) {
453 struct snake* new = malloc (sizeof(struct snake));
454 new->r = row;
455 new->c = col;
456 new->next = NULL;
457
458 if (*s) {
459 struct snake* p = *s;
460 while (p->next) p = p->next;
461 p->next = new;
462 } else {
463 *s = new;
464 }
465 }
466
467 void remove_bonus (struct item* i) {
468 if (i->next) i->next->prev = i->prev;
469 if (i->prev) i->prev->next = i->next;
470 else g.i = i->next;
471
472 draw_sprites (i->r, i->c); /* overwrite sprite */
473
474 free(i);
475 }
476
477 #define free_ll(head) do{ \
478 while (head) { \
479 void* tmp = head; \
480 head = head->next; \
481 free(tmp); \
482 } \
483 head = NULL; \
484 }while(0)
485
486 void init_snake() {
487 free_ll(g.s);
488 free_ll(g.i);
489
490 int direction = WEST;
491 int r = g.h/2;
492 int c = g.w/2;
493 int min_r = 0;
494 int max_r = g.h-1;
495 int min_c = 0;
496 int max_c = g.w-1;
497 for (int i = 0; i < op.l; i++) {
498 switch (direction) {
499 case NORTH: r--; if(r <= min_r){direction=EAST; min_r++;}break;
500 case EAST: c++; if(c >= max_c){direction=SOUTH;max_c--;}break;
501 case SOUTH: r++; if(r >= max_r){direction=WEST; max_r--;}break;
502 case WEST: c--; if(c <= min_c){direction=NORTH;min_c++;}break;
503 }
504
505 snake_append(&g.s, r, c);
506 }
507 }
508
509 void quit (void) {
510 screen_setup(0);
511 free_ll(g.s);
512 free_ll(g.i);
513 }
514
515 enum esc_states {
516 START,
517 ESC_SENT,
518 CSI_SENT,
519 MOUSE_EVENT,
520 };
521 int getctrlseq (void) {
522 int c;
523 int state = START;
524 while ((c = getchar()) != EOF) {
525 switch (state) {
526 case START:
527 switch (c) {
528 case '\033': state=ESC_SENT; break;
529 default: return c;
530 }
531 break;
532 case ESC_SENT:
533 switch (c) {
534 case '[': state=CSI_SENT; break;
535 default: return CTRSEQ_INVALID;
536 }
537 break;
538 case CSI_SENT:
539 switch (c) {
540 case 'A': return CTRSEQ_CURSOR_UP;
541 case 'B': return CTRSEQ_CURSOR_DOWN;
542 case 'C': return CTRSEQ_CURSOR_RIGHT;
543 case 'D': return CTRSEQ_CURSOR_LEFT;
544 default: return CTRSEQ_INVALID;
545 }
546 break;
547 default:
548 return CTRSEQ_INVALID;
549 }
550 }
551 return 2;
552 }
553
554 void append_movement (int dir) {
555 if (g.k.n > 15) return; /* no space in buffer */
556 if (g.k.n && g.k.c[(16+g.k.h-1)%16] == dir)
557 return; /* don't add the same direction twice */
558
559 g.k.c[g.k.h] = dir;
560 g.k.n++;
561 g.k.h = (g.k.h+1) % 16;
562 }
563
564 void move_ph (int line, int col) {
565 /* move printhead to zero-indexed position */
566 printf ("\033[%d;%dH", line+1, col+1);
567 }
568
569 void clamp_fieldsize (void) {
570 /* clamp field size to terminal size and mouse maximum: */
571 struct winsize w;
572 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
573
574 if (g.w < 10) g.w = 10;
575 if (g.h < 10) g.h = 10;
576
577 if (COL_OFFSET + g.w*CW + COL_OFFSET > w.ws_col)
578 g.w = (w.ws_col - 2*COL_OFFSET) / op.sch->display_width;
579 if (LINE_OFFSET + g.h + LINES_AFTER > w.ws_row)
580 g.h = w.ws_row - (LINE_OFFSET+LINES_AFTER);
581 }
582
583 void timer_setup (int enable) {
584 static struct itimerval tbuf;
585 tbuf.it_interval.tv_sec = 0;
586 tbuf.it_interval.tv_usec = (1000000/g.v)-1; /*WARN: 1 <= g.v <= 999999*/
587
588 if (enable) {
589 tbuf.it_value.tv_sec = tbuf.it_interval.tv_sec;
590 tbuf.it_value.tv_usec = tbuf.it_interval.tv_usec;
591 } else {
592 tbuf.it_value.tv_sec = 0;
593 tbuf.it_value.tv_usec = 0;
594 }
595
596 if ( setitimer(ITIMER_REAL, &tbuf, NULL) == -1 ) {
597 perror("setitimer");
598 exit(1);
599 }
600
601 }
602
603 void signal_setup (void) {
604 struct sigaction saction;
605
606 saction.sa_handler = signal_handler;
607 sigemptyset(&saction.sa_mask);
608 saction.sa_flags = 0;
609 if (sigaction(SIGALRM, &saction, NULL) < 0 ) {
610 perror("SIGALRM");
611 exit(1);
612 }
613
614 if (sigaction(SIGINT, &saction, NULL) < 0 ) {
615 perror ("SIGINT");
616 exit (1);
617 }
618
619 if (sigaction(SIGCONT, &saction, NULL) < 0 ) {
620 perror ("SIGCONT");
621 exit (1);
622 }
623 }
624
625 void signal_handler (int signum) {
626 switch (signum) {
627 case SIGALRM:
628 snake_advance();
629 spawn_bonus(); //TODO: currently, a bonus is spawned every x secs. should be x secs after last bonus disappeared.
630 break;
631 case SIGINT:
632 exit(128+SIGINT);
633 case SIGCONT:
634 screen_setup(1);
635 show_playfield();
636 }
637 }
638
639 void screen_setup (int enable) {
640 if (enable) {
641 raw_mode(1);
642 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
643 printf ("\033[H\033[J"); /* reset cursor, clear screen */
644 printf ("\033[?25l"); /* hide cursor */
645 print (op.sch->init_seq); /* swich charset, if necessary */
646 } else {
647 print (op.sch->reset_seq); /* reset charset, if necessary */
648 printf ("\033[?25h"); /* show cursor */
649 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
650 raw_mode(0);
651 }
652 }
653
654 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
655 void raw_mode(int enable) {
656 static struct termios saved_term_mode;
657 struct termios raw_term_mode;
658
659 if (enable) {
660 tcgetattr(STDIN_FILENO, &saved_term_mode);
661 raw_term_mode = saved_term_mode;
662 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
663 raw_term_mode.c_cc[VMIN] = 1 ;
664 raw_term_mode.c_cc[VTIME] = 0;
665 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
666 } else {
667 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
668 }
669 }
Imprint / Impressum