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