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