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