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