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