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