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