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