]> git.gir.st - VIper.git/blob - viiper.c
game loop (restartable), 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 <sys/ioctl.h>
24 #include <sys/time.h>
25 #include <termios.h>
26 #include <time.h>
27 #include <unistd.h>
28
29 #include "viiper.h"
30 #include "schemes.h"
31
32 #define MIN(a,b) (a>b?b:a)
33 #define MAX(a,b) (a>b?a:b)
34 #define CLAMP(a,m,M) (a<m?m:(a>M?M:a))
35 #define printm(n, s) for (int _loop = 0; _loop < n; _loop++) fputs (s, stdout)
36 #define print(str) fputs (str?str:"", stdout)
37 #define CTRL_ 0x1F &
38
39 #define OPPOSITE(dir) ( \
40 dir == EAST ? WEST : \
41 dir == WEST ? EAST : \
42 dir == NORTH ? SOUTH : \
43 dir == SOUTH ? NORTH : -1)
44
45 #define COL_OFFSET 1
46 #define LINE_OFFSET 1
47 #define LINES_AFTER 1
48 #define CW op.scheme->cell_width
49
50 struct game {
51 int w; /* field width */
52 int h; /* field height */
53 int d; /* direction the snake is looking */
54 int t; /* time of game start */
55 int p; /* score */
56 float v; /* velocity in moves per second */
57 struct snake* s; /* snek */
58 struct item* i; /* items (food, boni) */
59 struct directions {
60 int h; /* write head */
61 int n; /* number of elements */
62 int c[16];
63 } k; /* ring buffer for direction events */
64 } g;
65
66 struct opt {
67 int l; /* initial snake length */
68 int s; /* initial snake speed */
69 struct scheme* scheme;
70 } op;
71
72 jmp_buf game_over;
73
74 int main (int argc, char** argv) {
75 /* defaults: */
76 g.w = 30; //two-char-width
77 g.h = 20;
78 op.l = 10;
79 op.s = 8;
80 op.scheme = &unic0de;
81
82 int optget;
83 opterr = 0; /* don't print message on unrecognized option */
84 while ((optget = getopt (argc, argv, "+s:dh")) != -1) {
85 switch (optget) {
86 case 's':
87 op.s = atof(optarg);
88 if (op.s < 1) {
89 fprintf (stderr, "speed must be >= 1\n");
90 return 1;
91 }
92 break;
93 case 'd': op.scheme = &vt220_charset; break;
94 case 'h':
95 default:
96 fprintf (stderr, SHORTHELP LONGHELP, argv[0]);
97 return !(optget=='h');
98 }
99 } if (optind < argc) { /* parse Fieldspec */
100 int n = sscanf (argv[optind], "%dx%d", &g.w, &g.h);
101
102 if (n < 2) {
103 fprintf(stderr,"FIELDSIZE is WxH (width 'x' height)\n");
104 return 1;
105 }
106 }
107
108 clamp_fieldsize();
109
110 srand(time(0));
111 signal_setup();
112 screen_setup(1);
113 atexit (*quit);
114
115 switch (sigsetjmp(game_over, 1)) {
116 case GAME_INIT:
117 case GAME_START:
118 viiper();
119 case GAME_OVER:
120 timer_setup(0);
121 show_playfield();
122 move_ph (g.h/2+LINE_OFFSET, g.w);
123 printf ("snek ded :(");
124 fflush(stdout);
125 sleep(2);
126 case GAME_EXIT:
127 exit(0);
128 }
129
130 return 0;
131 }
132
133 int viiper(void) {
134 init_snake();
135 show_playfield ();
136 g.d = EAST;
137 g.v = op.s;
138
139 timer_setup(1);
140 g.t = time(NULL);
141
142 spawn_item(FOOD, rand() % NUM_FOODS, NULL); //TODO: shape distribution, so bigger values get selected less
143
144 for(;;) {
145 switch (getctrlseq()) {
146 case CTRSEQ_CURSOR_LEFT: case 'h':append_movement(WEST); break;
147 case CTRSEQ_CURSOR_DOWN: case 'j':append_movement(SOUTH); break;
148 case CTRSEQ_CURSOR_UP: case 'k':append_movement(NORTH); break;
149 case CTRSEQ_CURSOR_RIGHT:case 'l':append_movement(EAST); break;
150 case 'p':
151 timer_setup(0);
152 move_ph (g.h/2+LINE_OFFSET, g.w*CW/2);
153 printf ("\033[5mPAUSE\033[0m"); /* blinking text */
154 if (getchar() == 'q') exit(0);
155 show_playfield();
156 timer_setup(1);
157 break;
158 case 'r': siglongjmp(game_over, GAME_START);
159 case 'q': siglongjmp(game_over, GAME_EXIT);
160 case CTRL_'L':
161 screen_setup(1);
162 show_playfield();
163 break;
164 case 0x02: /* STX; gets sent when returning from SIGALRM */
165 continue;
166 }
167 }
168
169 }
170
171 #define pop_dir() (g.k.n? g.k.c[(16+g.k.h-g.k.n--)%16] : NONE)
172 void snake_advance (void) {
173 int respawn = 0;
174 struct item* i; /* temporary item (defined here to respawn at the end) */
175 int new_dir = pop_dir();
176 /* switch direction if new one is in the buffer and it won't kill us: */
177 if (new_dir && g.d != OPPOSITE(new_dir)) g.d = new_dir;
178
179 int new_row = g.s->r +(g.d==SOUTH) -(g.d==NORTH);
180 int new_col = g.s->c +(g.d==EAST) -(g.d==WEST);
181
182 /* detect food hit and spawn a new food */
183 for (i = g.i; i; i = i->next) {
184 if (i->r == new_row && i->c == new_col) {
185 consume_item (i);
186 respawn = 1; /* must respawn after advancing head */
187 break;
188 }
189 }
190
191 if (new_row >= g.h || new_col >= g.w || new_row < 0 || new_col < 0)
192 siglongjmp(game_over, GAME_OVER);
193
194 struct snake* new_head;
195 struct snake* new_tail; /* former second-to-last element */
196 for (new_tail = g.s; new_tail->next->next; new_tail = new_tail->next)
197 /*use the opportunity of looping to check if we eat ourselves:*/
198 if(new_tail->next->r == new_row && new_tail->next->c == new_col)
199 siglongjmp(game_over, GAME_OVER);
200 int old_tail[2] = {new_tail->next->r, new_tail->next->c};/*gets erased*/
201 new_head = new_tail->next; /* reuse element instead of malloc() */
202 new_tail->next = NULL;
203
204 new_head->r = new_row;
205 new_head->c = new_col;
206 new_head->next = g.s;
207
208 g.s = new_head;
209
210 if (respawn) spawn_item(FOOD, rand() % NUM_FOODS, i);
211 draw_sprites (old_tail[0], old_tail[1]);
212 }
213
214 void spawn_item (int type, int value, struct item* p_item) {
215 int row, col;
216 try_again:
217 row = rand() % g.h;
218 col = rand() % g.w;
219 /* loop through snake to check if we aren't on it */
220 //WARN: inefficient as snake gets longer; near impossible in the end
221 for (struct snake* s = g.s; s; s = s->next)
222 if (s->r == row && s->c == col) goto try_again;
223
224 /* if we got a item buffer reuse it, otherwise create a new one: */
225 struct item* new_item;
226 if (p_item) new_item = p_item;
227 else new_item = malloc (sizeof(struct item));
228
229 new_item->r = row;
230 new_item->c = col;
231 new_item->t = type;
232 new_item->v = value;
233 new_item->s = time(0);
234 if (g.i) g.i->prev = new_item;
235 new_item->next = g.i;
236 new_item->prev = NULL;
237
238 g.i = new_item;
239 }
240
241 void consume_item (struct item* i) {
242 switch (i->t) {
243 case FOOD:
244 switch (i->v) {
245 case FOOD_5: g.p += 5; break;
246 case FOOD_10: g.p += 10; break;
247 case FOOD_20: g.p += 20; break;
248 }
249 snake_append(&g.s, 0,0); /* position doesn't matter, as item */
250 break; /* will be reused as the head before it is drawn */
251 case BONUS:
252 //TODO: handle bonus
253 break;
254 }
255
256 if (i->next) i->next->prev = i->prev;
257 if (i->prev) i->prev->next = i->next;
258 else g.i = i->next;
259 }
260
261 void show_playfield (void) {
262 move_ph (0,0);
263
264 /* top border */
265 print(BORDER(T,L));
266 printm (g.w, BORDER(T,C));
267 printf ("%s\n", BORDER(T,R));
268
269 /* main area */
270 for (int row = 0; row < g.h; row++)
271 printf ("%s%*s%s\n", BORDER(C,L), CW*g.w, "", BORDER(C,R));
272
273 /* bottom border */
274 print(BORDER(B,L));
275 printm (g.w, BORDER(B,C));
276 print (BORDER(B,R));
277
278 draw_sprites (0,0);
279 }
280
281 void draw_sprites (int erase_r, int erase_c) {
282 /* erase old tail */
283 move_ph (erase_r+LINE_OFFSET, erase_c*CW+COL_OFFSET);
284 printm (CW, " ");
285
286 /* print snake */
287 struct snake* last = NULL;
288 int color = 2;
289 for (struct snake* s = g.s; s; s = s->next) {
290 move_ph (s->r+LINE_OFFSET, s->c*CW+COL_OFFSET); /*NOTE: all those are actually wrong; draws snake 1 col too far left*/
291
292 int predecessor = (last==NULL)?NONE:
293 (last->r < s->r) ? NORTH:
294 (last->r > s->r) ? SOUTH:
295 (last->c > s->c) ? EAST:
296 (last->c < s->c) ? WEST:NONE;
297 int successor = (s->next == NULL)?NONE:
298 (s->next->r < s->r) ? NORTH:
299 (s->next->r > s->r) ? SOUTH:
300 (s->next->c > s->c) ? EAST:
301 (s->next->c < s->c) ? WEST:NONE;
302
303 printf ("\033[%sm", op.scheme->color[color]);
304 print (op.scheme->snake[predecessor][successor]);
305 printf ("\033[0m");
306 last = s;
307 color = !color;
308 }
309
310 /* print item queue */
311 for (struct item* i = g.i; i; i = i->next) {
312 move_ph (i->r+LINE_OFFSET, i->c*CW+COL_OFFSET);
313 if (i->t == FOOD) print (op.scheme->item[i->v]);
314 else if (i->t==BONUS) /* TODO: print bonus */;
315 }
316
317 /* print score */
318 int score_width = g.p > 9999?6:4;
319 move_ph (0, (g.w*CW-score_width)/2-COL_OFFSET);
320 printf ("%s %0*d %s", BORDER(S,L), score_width, g.p, BORDER(S,R));
321 }
322
323 void snake_append (struct snake** s, int row, int col) {
324 struct snake* new = malloc (sizeof(struct snake));
325 new->r = row;
326 new->c = col;
327 new->next = NULL;
328
329 if (*s) {
330 struct snake* p = *s;
331 while (p->next) p = p->next;
332 p->next = new;
333 } else {
334 *s = new;
335 }
336 }
337
338 #define free_ll(head) do{ \
339 while (head) { \
340 void* tmp = head; \
341 head = head->next; \
342 free(tmp); \
343 } \
344 head = NULL; \
345 }while(0)
346
347 void init_snake() {
348 if (g.s)
349 free_ll(g.s);
350 if (g.i)
351 free_ll(g.i);
352 for (int i = 0; i < op.l; i++) {
353 if (g.w/2-i < 0) /* go upwards if we hit left wall */
354 snake_append(&g.s, g.h/2-(i-g.w/2), 0);
355 else /* normally just keep goint left */
356 snake_append(&g.s, g.h/2, g.w/2-i);
357 }
358 }
359
360 void quit (void) {
361 screen_setup(0);
362 free_ll(g.s);
363 free_ll(g.i);
364 }
365
366 enum esc_states {
367 START,
368 ESC_SENT,
369 CSI_SENT,
370 MOUSE_EVENT,
371 };
372 int getctrlseq (void) {
373 int c;
374 int state = START;
375 while ((c = getchar()) != EOF) {
376 switch (state) {
377 case START:
378 switch (c) {
379 case '\033': state=ESC_SENT; break;
380 default: return c;
381 }
382 break;
383 case ESC_SENT:
384 switch (c) {
385 case '[': state=CSI_SENT; break;
386 default: return CTRSEQ_INVALID;
387 }
388 break;
389 case CSI_SENT:
390 switch (c) {
391 case 'A': return CTRSEQ_CURSOR_UP;
392 case 'B': return CTRSEQ_CURSOR_DOWN;
393 case 'C': return CTRSEQ_CURSOR_RIGHT;
394 case 'D': return CTRSEQ_CURSOR_LEFT;
395 default: return CTRSEQ_INVALID;
396 }
397 break;
398 default:
399 return CTRSEQ_INVALID;
400 }
401 }
402 return 2;
403 }
404
405 void append_movement (int dir) {
406 if (g.k.n > 15) return; /* no space in buffer */
407 if (g.k.n && g.k.c[(16+g.k.h-1)%16] == dir)
408 return; /* don't add the same direction twice */
409
410 g.k.c[g.k.h] = dir;
411 g.k.n++;
412 g.k.h = ++g.k.h % 16;
413 }
414
415 void move_ph (int line, int col) {
416 /* move printhead to zero-indexed position */
417 printf ("\033[%d;%dH", line+1, col+1);
418 }
419
420 void clamp_fieldsize (void) {
421 /* clamp field size to terminal size and mouse maximum: */
422 struct winsize w;
423 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
424
425 if (g.w < 10) g.w = 10;
426 if (g.h < 10) g.h = 10;
427
428 if (COL_OFFSET + g.w*CW + COL_OFFSET > w.ws_col)
429 g.w = (w.ws_col - (COL_OFFSET+COL_OFFSET))/op.scheme->display_width;
430 if (LINE_OFFSET + g.h + LINES_AFTER > w.ws_row)
431 g.h = w.ws_row - (LINE_OFFSET+LINES_AFTER);
432 }
433
434 void timer_setup (int enable) {
435 static struct itimerval tbuf;
436 tbuf.it_interval.tv_sec = 0;//TODO: make it speed up automatically
437 tbuf.it_interval.tv_usec = (1000000/g.v)-1; /*WARN: 1 <= g.v <= 999999*/
438
439 if (enable) {
440 tbuf.it_value.tv_sec = tbuf.it_interval.tv_sec;
441 tbuf.it_value.tv_usec = tbuf.it_interval.tv_usec;
442 } else {
443 tbuf.it_value.tv_sec = 0;
444 tbuf.it_value.tv_usec = 0;
445 }
446
447 if ( setitimer(ITIMER_REAL, &tbuf, NULL) == -1 ) {
448 perror("setitimer");
449 exit(1);
450 }
451
452 }
453
454 void signal_setup (void) {
455 struct sigaction saction;
456
457 saction.sa_handler = signal_handler;
458 sigemptyset(&saction.sa_mask);
459 saction.sa_flags = 0;
460 if (sigaction(SIGALRM, &saction, NULL) < 0 ) {
461 perror("SIGALRM");
462 exit(1);
463 }
464
465 if (sigaction(SIGINT, &saction, NULL) < 0 ) {
466 perror ("SIGINT");
467 exit (1);
468 }
469
470 if (sigaction(SIGCONT, &saction, NULL) < 0 ) {
471 perror ("SIGCONT");
472 exit (1);
473 }
474 }
475
476 void signal_handler (int signum) {
477 switch (signum) {
478 case SIGALRM:
479 snake_advance();
480 break;
481 case SIGINT:
482 exit(128+SIGINT);
483 case SIGCONT:
484 siglongjmp(game_over, GAME_EXIT);/*TODO:returning from ^Z breaks input*/
485 }
486 }
487
488 void screen_setup (int enable) {
489 if (enable) {
490 raw_mode(1);
491 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
492 printf ("\033[H\033[J"); /* reset cursor, clear screen */
493 printf ("\033[?25l"); /* hide cursor */
494 print (op.scheme->init_seq); /* swich charset, if necessary */
495 } else {
496 print (op.scheme->reset_seq); /* reset charset, if necessary */
497 printf ("\033[?25h"); /* show cursor */
498 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
499 raw_mode(0);
500 }
501 }
502
503 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
504 void raw_mode(int enable) {
505 static struct termios saved_term_mode;
506 struct termios raw_term_mode;
507
508 if (enable) {
509 tcgetattr(STDIN_FILENO, &saved_term_mode);
510 raw_term_mode = saved_term_mode;
511 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
512 raw_term_mode.c_cc[VMIN] = 1 ;
513 raw_term_mode.c_cc[VTIME] = 0;
514 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
515 } else {
516 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
517 }
518 }
Imprint / Impressum