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