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