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