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