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