]> git.gir.st - VIper.git/blob - viiper.c
readme: small blurb about dependencies, todo item->done
[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 t; /* time of game start */
61 int p; /* score */
62 int b; /* time of next bonus item spawn */
63 float v; /* velocity in moves per second */
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 CTRSEQ_CURSOR_LEFT: case 'h':append_movement(WEST); break;
179 case CTRSEQ_CURSOR_DOWN: case 'j':append_movement(SOUTH); break;
180 case CTRSEQ_CURSOR_UP: case 'k':append_movement(NORTH); break;
181 case CTRSEQ_CURSOR_RIGHT:case 'l':append_movement(EAST); break;
182 case 'p': //TODO: causes bonus items to be spawned too early; have to increase all timers
183 timer_setup(0);
184 move_ph (g.h/2+LINE_OFFSET, g.w*CW/2);
185 printf ("\033[5mPAUSE\033[0m"); /* blinking text */
186 if (getchar() == 'q') exit(0);
187 show_playfield();
188 timer_setup(1);
189 break;
190 case 'r': siglongjmp(game_over, GAME_START);
191 case 'q': siglongjmp(game_over, GAME_EXIT);
192 case CTRL_'L':
193 screen_setup(1);
194 show_playfield();
195 break;
196 case 0x02: /* STX; gets sent when returning from SIGALRM */
197 continue;
198 }
199 }
200
201 }
202
203 #define pop_dir() (g.k.n? g.k.c[(16+g.k.h-g.k.n--)%16] : NONE)
204 void snake_advance (void) {
205 int respawn = 0;
206 struct item* i; /*temporary item (defined here to respawn at the end) */
207 int new_dir = pop_dir();
208 /* switch direction if new one is in the buffer and it won't kill us: */
209 if (new_dir && g.d != OPPOSITE(new_dir)) g.d = new_dir;
210
211 int new_row = g.s->r +(g.d==SOUTH) -(g.d==NORTH);
212 int new_col = g.s->c +(g.d==EAST) -(g.d==WEST);
213
214 /* detect food hit and spawn a new food */
215 for (i = g.i; i; i = i->next) {
216 if (i->r == new_row && i->c == new_col) {
217 consume_item (i);
218
219 switch (i->t) {
220 case FOOD: respawn = 1; break;
221 case BONUS: remove_bonus(i); break;
222 }
223 break;
224 }
225 }
226
227 if (new_row >= g.h || new_col >= g.w || new_row < 0 || new_col < 0)
228 siglongjmp(game_over, GAME_OVER);
229
230 struct snake* new_head;
231 struct snake* new_tail; /* former second-to-last element */
232 for (new_tail = g.s; new_tail->next->next; new_tail = new_tail->next)
233 /*use the opportunity of looping to check if we eat ourselves:*/
234 if(new_tail->next->r == new_row && new_tail->next->c == new_col)
235 siglongjmp(game_over, GAME_OVER);
236 int old_tail[2] = {new_tail->next->r, new_tail->next->c};/*gets erased*/
237 new_head = new_tail->next; /* reuse element instead of malloc() */
238 new_tail->next = NULL;
239
240 new_head->r = new_row;
241 new_head->c = new_col;
242 new_head->next = g.s;
243
244 g.s = new_head;
245
246 if (respawn) spawn_item(FOOD, rand() % NUM_FOODS, i);
247 draw_sprites (old_tail[0], old_tail[1]);
248 }
249
250 void spawn_item (int type, int value, struct item* p_item) {
251 int row, col;
252 char occupied[g.w][g.h]; int snake_len = 0;
253 memset(*occupied, 0, g.w*g.h);
254 try_again:
255 row = rand() % g.h;
256 col = rand() % g.w;
257 if (snake_len >= g.w*g.h-1) siglongjmp(game_over, GAME_WON);
258 /* loop through snake to check if we aren't on it */
259 if (occupied[row][col]) goto try_again; /* shortcut */
260 for (struct snake* s = g.s; s; s = s->next)
261 if (s->r == row && s->c == col) {
262 occupied[s->r][s->c] = 1; snake_len++;
263 goto try_again;
264 }
265
266 /* if we got a item buffer reuse it, otherwise create a new one: */
267 struct item* new_item;
268 if (p_item) new_item = p_item;
269 else new_item = malloc (sizeof(struct item));
270
271 new_item->r = row;
272 new_item->c = col;
273 new_item->t = type;
274 new_item->v = value;
275 new_item->s = time(0);
276 if (g.i) g.i->prev = new_item;
277 new_item->next = g.i;
278 new_item->prev = NULL;
279
280 g.i = new_item;
281 }
282
283 void consume_item (struct item* i) {
284 int old_score = g.p;
285
286 switch (i->t) {
287 case FOOD:
288 switch (i->v) {
289 case FOOD_5: g.p += 5; break;
290 case FOOD_10: g.p += 10; break;
291 case FOOD_20: g.p += 20; break;
292 }
293 snake_append(&g.s, -1, -1);
294 break; /* will be reused as the head before it is drawn */
295 case BONUS:
296 switch (i->v) {
297 case BONUS_SNIP:
298 for (int i = 5; i && g.s->next->next; i--) {
299 struct snake* p = g.s;
300 while (p->next->next) p = p->next;
301 free (p->next);
302 p->next = NULL;
303 }
304 show_playfield();
305 break;
306 case BONUS_GROW:
307 for (int i = 5; i; i--) snake_append(&g.s, -1, -1);
308 break;
309 case BONUS_SLOW: //TODO: this sometimes speeds the snake up?!
310 if (g.v > 1) g.v--;
311 timer_setup(1);
312 break;
313 case BONUS_FAST:
314 g.v++;
315 timer_setup(1);
316 break;
317 }
318 break;
319 }
320
321 if (i->next) i->next->prev = i->prev;
322 if (i->prev) i->prev->next = i->next;
323 else g.i = i->next;
324
325 /* snake speedup every 100 points: */
326 if (g.p/SPEEDUP_AFTER - old_score/SPEEDUP_AFTER) g.v++;
327 }
328
329 void spawn_bonus(void) {
330 for (struct item* i = g.i; i; i = i->next)
331 if (i->t == BONUS) { /* bonus already there */
332 if (((i->s+BONUS_DURATION)-time(NULL)) < 0) {
333 remove_bonus(i); /* remove if over lifetime */
334 }
335 return;
336 }
337 if (g.b < time(NULL)) { /* time to spawn item: */
338 spawn_item(BONUS, rand() % NUM_BONI, NULL);
339 g.b = time(NULL) + BONUS_INTERVAL;
340 }
341 }
342
343 void show_playfield (void) {
344 move_ph (0,0);
345
346 /* top border */
347 print(BORDER(T,L));
348 printm (g.w, BORDER(T,C));
349 printf ("%s\n", BORDER(T,R));
350
351 /* main area */
352 for (int row = 0; row < g.h; row++)
353 printf ("%s%*s%s\n", BORDER(C,L), CW*g.w, "", BORDER(C,R));
354
355 /* bottom border */
356 print(BORDER(B,L));
357 printm (g.w, BORDER(B,C));
358 print (BORDER(B,R));
359
360 draw_sprites (-1,-1);
361 }
362
363 void draw_sprites (int erase_r, int erase_c) {
364 /* erase old tail, if any */
365 if (erase_r >= 0 && erase_c >= 0) {
366 move_ph (erase_r+LINE_OFFSET, erase_c*CW+COL_OFFSET);
367 printm (CW, " ");
368 }
369
370 /* print snake */
371 struct snake* last = NULL;
372 int color = 2;
373 for (struct snake* s = g.s; s; s = s->next) {
374 if (s->r < 0 || s->c < 0) continue; /*can't draw outside term.*/
375 move_ph (s->r+LINE_OFFSET, s->c*CW+COL_OFFSET);
376
377 int predecessor = (last==NULL)?NONE:
378 (last->r < s->r) ? NORTH:
379 (last->r > s->r) ? SOUTH:
380 (last->c > s->c) ? EAST:
381 (last->c < s->c) ? WEST:NONE;
382 int successor = (s->next == NULL)?NONE:
383 (s->next->r < s->r) ? NORTH:
384 (s->next->r > s->r) ? SOUTH:
385 (s->next->c > s->c) ? EAST:
386 (s->next->c < s->c) ? WEST:NONE;
387
388 printf ("\033[%sm", op.sch->color[color]);
389 print (op.sch->snake[predecessor][successor]);
390 printf ("\033[0m");
391 last = s;
392 color = !color;
393 }
394
395 /* print item queue */
396 for (struct item* i = g.i; i; i = i->next) {
397 move_ph (i->r+LINE_OFFSET, i->c*CW+COL_OFFSET);
398 if (i->t == FOOD) print(op.sch->food[i->v]);
399 else if (i->t == BONUS) {
400 if (i->s + BONUS_DURATION-BONUS_WARN < time(NULL))
401 printf("\033[5m%s\033[25m", op.sch->boni[i->v]);
402 else print(op.sch->boni[i->v]);
403 }
404 }
405
406 /* print score */
407 int score_width = g.p > 9999?6:4;
408 move_ph (0, (g.w*CW-score_width)/2-COL_OFFSET);
409 printf ("%s %0*d %s", BORDER(S,L), score_width, g.p, BORDER(S,R));
410 printf ("->%f<-", g.v); //TODO: debug only! (BONUS_SLOW)
411 }
412
413 #define MOVE_POPUP(WIDTH, LINE) \
414 move_ph(g.h/2+LINE_OFFSET-1+LINE,(g.w*op.sch->display_width-WIDTH)/2)
415 int end_screen(char* message) {
416 int msg_w = strlen(message);
417 MOVE_POPUP(msg_w, -1);
418 print(BORDER(T,L));
419 printm ((msg_w+2)/op.sch->display_width, BORDER(T,C));
420 print (BORDER(T,R));
421
422 MOVE_POPUP(msg_w, 0);
423 printf("%s %s %s", BORDER(C,L), message, BORDER(C,R));
424 MOVE_POPUP(msg_w, 1);
425 printf("%s `r' restart%*s%s", BORDER(C,L), msg_w-10, "", BORDER(C,R));
426 MOVE_POPUP(msg_w, 2);
427 printf("%s `q' quit%*s%s", BORDER(C,L), msg_w-7, "", BORDER(C,R));
428
429 MOVE_POPUP(msg_w, 3);
430 print(BORDER(B,L));
431 printm ((msg_w+2)/op.sch->display_width, BORDER(B,C));
432 print (BORDER(B,R));
433 fflush(stdout);
434
435 return getctrlseq();
436 }
437
438 void snake_append (struct snake** s, int row, int col) {
439 struct snake* new = malloc (sizeof(struct snake));
440 new->r = row;
441 new->c = col;
442 new->next = NULL;
443
444 if (*s) {
445 struct snake* p = *s;
446 while (p->next) p = p->next;
447 p->next = new;
448 } else {
449 *s = new;
450 }
451 }
452
453 void remove_bonus (struct item* i) {
454 if (i->next) i->next->prev = i->prev;
455 if (i->prev) i->prev->next = i->next;
456 else g.i = i->next;
457
458 draw_sprites (i->r, i->c); /* overwrite sprite */
459
460 free(i);
461 }
462
463 #define free_ll(head) do{ \
464 while (head) { \
465 void* tmp = head; \
466 head = head->next; \
467 free(tmp); \
468 } \
469 head = NULL; \
470 }while(0)
471
472 void init_snake() {
473 free_ll(g.s);
474 free_ll(g.i);
475
476 int direction = WEST;
477 int r = g.h/2;
478 int c = g.w/2;
479 int min_r = 0;
480 int max_r = g.h-1;
481 int min_c = 0;
482 int max_c = g.w-1;
483 for (int i = 0; i < op.l; i++) {
484 switch (direction) {
485 case NORTH: r--; if(r <= min_r){direction=EAST; min_r++;}break;
486 case EAST: c++; if(c >= max_c){direction=SOUTH;max_c--;}break;
487 case SOUTH: r++; if(r >= max_r){direction=WEST; max_r--;}break;
488 case WEST: c--; if(c <= min_c){direction=NORTH;min_c++;}break;
489 }
490
491 snake_append(&g.s, r, c);
492 }
493 }
494
495 void quit (void) {
496 screen_setup(0);
497 free_ll(g.s);
498 free_ll(g.i);
499 }
500
501 enum esc_states {
502 START,
503 ESC_SENT,
504 CSI_SENT,
505 MOUSE_EVENT,
506 };
507 int getctrlseq (void) {
508 int c;
509 int state = START;
510 while ((c = getchar()) != EOF) {
511 switch (state) {
512 case START:
513 switch (c) {
514 case '\033': state=ESC_SENT; break;
515 default: return c;
516 }
517 break;
518 case ESC_SENT:
519 switch (c) {
520 case '[': state=CSI_SENT; break;
521 default: return CTRSEQ_INVALID;
522 }
523 break;
524 case CSI_SENT:
525 switch (c) {
526 case 'A': return CTRSEQ_CURSOR_UP;
527 case 'B': return CTRSEQ_CURSOR_DOWN;
528 case 'C': return CTRSEQ_CURSOR_RIGHT;
529 case 'D': return CTRSEQ_CURSOR_LEFT;
530 default: return CTRSEQ_INVALID;
531 }
532 break;
533 default:
534 return CTRSEQ_INVALID;
535 }
536 }
537 return 2;
538 }
539
540 void append_movement (int dir) {
541 if (g.k.n > 15) return; /* no space in buffer */
542 if (g.k.n && g.k.c[(16+g.k.h-1)%16] == dir)
543 return; /* don't add the same direction twice */
544
545 g.k.c[g.k.h] = dir;
546 g.k.n++;
547 g.k.h = (g.k.h+1) % 16;
548 }
549
550 void move_ph (int line, int col) {
551 /* move printhead to zero-indexed position */
552 printf ("\033[%d;%dH", line+1, col+1);
553 }
554
555 void clamp_fieldsize (void) {
556 /* clamp field size to terminal size and mouse maximum: */
557 struct winsize w;
558 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
559
560 if (g.w < 10) g.w = 10;
561 if (g.h < 10) g.h = 10;
562
563 if (COL_OFFSET + g.w*CW + COL_OFFSET > w.ws_col)
564 g.w = (w.ws_col - 2*COL_OFFSET) / op.sch->display_width;
565 if (LINE_OFFSET + g.h + LINES_AFTER > w.ws_row)
566 g.h = w.ws_row - (LINE_OFFSET+LINES_AFTER);
567 }
568
569 void timer_setup (int enable) {
570 static struct itimerval tbuf;
571 tbuf.it_interval.tv_sec = 0;
572 tbuf.it_interval.tv_usec = (1000000/g.v)-1; /*WARN: 1 <= g.v <= 999999*/
573
574 if (enable) {
575 tbuf.it_value.tv_sec = tbuf.it_interval.tv_sec;
576 tbuf.it_value.tv_usec = tbuf.it_interval.tv_usec;
577 } else {
578 tbuf.it_value.tv_sec = 0;
579 tbuf.it_value.tv_usec = 0;
580 }
581
582 if ( setitimer(ITIMER_REAL, &tbuf, NULL) == -1 ) {
583 perror("setitimer");
584 exit(1);
585 }
586
587 }
588
589 void signal_setup (void) {
590 struct sigaction saction;
591
592 saction.sa_handler = signal_handler;
593 sigemptyset(&saction.sa_mask);
594 saction.sa_flags = 0;
595 if (sigaction(SIGALRM, &saction, NULL) < 0 ) {
596 perror("SIGALRM");
597 exit(1);
598 }
599
600 if (sigaction(SIGINT, &saction, NULL) < 0 ) {
601 perror ("SIGINT");
602 exit (1);
603 }
604
605 if (sigaction(SIGCONT, &saction, NULL) < 0 ) {
606 perror ("SIGCONT");
607 exit (1);
608 }
609 }
610
611 void signal_handler (int signum) {
612 switch (signum) {
613 case SIGALRM:
614 snake_advance();
615 spawn_bonus();
616 break;
617 case SIGINT:
618 exit(128+SIGINT);
619 case SIGCONT:
620 screen_setup(1);
621 show_playfield();
622 }
623 }
624
625 void screen_setup (int enable) {
626 if (enable) {
627 raw_mode(1);
628 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
629 printf ("\033[H\033[J"); /* reset cursor, clear screen */
630 printf ("\033[?25l"); /* hide cursor */
631 print (op.sch->init_seq); /* swich charset, if necessary */
632 } else {
633 print (op.sch->reset_seq); /* reset charset, if necessary */
634 printf ("\033[?25h"); /* show cursor */
635 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
636 raw_mode(0);
637 }
638 }
639
640 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
641 void raw_mode(int enable) {
642 static struct termios saved_term_mode;
643 struct termios raw_term_mode;
644
645 if (enable) {
646 tcgetattr(STDIN_FILENO, &saved_term_mode);
647 raw_term_mode = saved_term_mode;
648 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
649 raw_term_mode.c_cc[VMIN] = 1 ;
650 raw_term_mode.c_cc[VTIME] = 0;
651 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
652 } else {
653 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
654 }
655 }
Imprint / Impressum