]> git.gir.st - VIper.git/blob - viiper.c
minor in-code cleanup, documentation
[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); //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 timer_setup(1);
149 break;
150 case 'r': /*TODO:restart*/ return 0;
151 case 'q': return 0;
152 case CTRL_'L':
153 screen_setup(1);
154 show_playfield();
155 break;
156 case 0x02: /* STX; gets sent when returning from SIGALRM */
157 }
158
159 show_playfield ();//TODO: only redraw diff
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);
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 new_head = new_tail->next; /* reuse element instead of malloc() */
195 new_tail->next = NULL;
196
197 new_head->r = new_row;
198 new_head->c = new_col;
199 new_head->next = g.s;
200
201 g.s = new_head;
202 }
203
204 void spawn_item (int type, int value) {
205 int row, col;
206 try_again:
207 row = rand() % g.h;
208 col = rand() % g.w;
209 /* loop through snake to check if we aren't on it */
210 //WARN: inefficient as snake gets longer; near impossible in the end
211 for (struct snake* s = g.s; s; s = s->next)
212 if (s->r == row && s->c == col) goto try_again;
213
214 struct item* new_item = malloc (sizeof(struct item));
215 new_item->r = row;
216 new_item->c = col;
217 new_item->t = type;
218 new_item->v = value;
219 new_item->s = time(0);
220 if (g.i) g.i->prev = new_item;
221 new_item->next = g.i;
222 new_item->prev = NULL;
223
224 g.i = new_item;
225 }
226
227 void consume_item (struct item* i) {
228 switch (i->t) {
229 case FOOD:
230 switch (i->v) {
231 case FOOD_5: g.p += 5; break;
232 case FOOD_10: g.p += 10; break;
233 case FOOD_20: g.p += 20; break;
234 }
235 snake_append(&g.s, 0,0); /* position doesn't matter, as item */
236 break; /* will be reused as the head before it is drawn */
237 case BONUS:
238 //TODO: handle bonus
239 break;
240 }
241
242 if (i->next) i->next->prev = i->prev;
243 if (i->prev) i->prev->next = i->next;
244 else g.i = i->next;
245
246 free (i); //TODO: pass to spawn_item() to save on allocations
247 }
248
249 void show_playfield (void) {
250 move_ph (0,0);
251
252 /* top border */
253 print(BORDER(T,L));
254 printm (g.w, BORDER(T,C));
255 printf ("%s\n", BORDER(T,R));
256
257 /* main area */
258 for (int row = 0; row < g.h; row++)
259 printf ("%s%*s%s\n", BORDER(C,L), CW*g.w, "", BORDER(C,R));
260
261 /* bottom border */
262 print(BORDER(B,L));
263 printm (g.w, BORDER(B,C));
264 print (BORDER(B,R));
265
266 /* print score */
267 int score_width = g.p > 9999?6:4;
268 move_ph (0, (g.w*CW-score_width)/2);
269 printf ("%s %0*d %s", BORDER(S,L), score_width, g.p, BORDER(S,R));
270
271 /* print snake */
272 struct snake* last = NULL;
273 int color = 2;
274 for (struct snake* s = g.s; s; s = s->next) {
275 move_ph (s->r+LINE_OFFSET, s->c*CW+COL_OFFSET);
276
277 int predecessor = (last==NULL)?NONE:
278 (last->r < s->r) ? NORTH:
279 (last->r > s->r) ? SOUTH:
280 (last->c > s->c) ? EAST:
281 (last->c < s->c) ? WEST:NONE;
282 int successor = (s->next == NULL)?NONE:
283 (s->next->r < s->r) ? NORTH:
284 (s->next->r > s->r) ? SOUTH:
285 (s->next->c > s->c) ? EAST:
286 (s->next->c < s->c) ? WEST:NONE;
287
288 printf ("\033[%sm", op.scheme->color[color]);
289 print (op.scheme->snake[predecessor][successor]);
290 printf ("\033[0m");
291 last = s;
292 color = !color;
293 }
294
295 /* print item queue */
296 for (struct item* i = g.i; i; i = i->next) {
297 move_ph (i->r+LINE_OFFSET, i->c*CW+COL_OFFSET);
298 if (i->t == FOOD) print (op.scheme->item[i->v]);
299 else if (i->t==BONUS) /* TODO: print bonus */;
300 }
301 }
302
303 void snake_append (struct snake** s, int row, int col) {
304 struct snake* new = malloc (sizeof(struct snake));
305 new->r = row;
306 new->c = col;
307 new->next = NULL;
308
309 if (*s) {
310 struct snake* p = *s;
311 while (p->next) p = p->next;
312 p->next = new;
313 } else {
314 *s = new;
315 }
316 }
317
318 void init_snake() {
319 for (int i = 0; i < op.l; i++) {
320 if (g.w/2-i < 0) break; /* stop if we hit left wall */
321 snake_append(&g.s, g.h/2, g.w/2-i);
322 }
323 }
324
325 #define free_ll(head) do{ \
326 while (head) { \
327 void* tmp = head; \
328 head = head->next; \
329 free(tmp); \
330 } \
331 }while(0)
332
333 void quit (void) {
334 screen_setup(0);
335 free_ll(g.s);
336 free_ll(g.i);
337 free_ll(g.n);
338 }
339
340 enum esc_states {
341 START,
342 ESC_SENT,
343 CSI_SENT,
344 MOUSE_EVENT,
345 };
346 int getctrlseq (void) {
347 int c;
348 int state = START;
349 int offset = 0x20; /* never sends control chars as data */
350 while ((c = getchar()) != EOF) {
351 switch (state) {
352 case START:
353 switch (c) {
354 case '\033': state=ESC_SENT; break;
355 default: return c;
356 }
357 break;
358 case ESC_SENT:
359 switch (c) {
360 case '[': state=CSI_SENT; break;
361 default: return CTRSEQ_INVALID;
362 }
363 break;
364 case CSI_SENT:
365 switch (c) {
366 case 'A': return CTRSEQ_CURSOR_UP;
367 case 'B': return CTRSEQ_CURSOR_DOWN;
368 case 'C': return CTRSEQ_CURSOR_RIGHT;
369 case 'D': return CTRSEQ_CURSOR_LEFT;
370 default: return CTRSEQ_INVALID;
371 }
372 break;
373 default:
374 return CTRSEQ_INVALID;
375 }
376 }
377 return 2;
378 }
379
380 void append_movement (int dir) {
381 struct directions* n;
382 for (n = g.n; n && n->next; n = n->next); /* advance to the end */
383 if (n && n->d == dir) return; /* don't add the same direction twice */
384 if (n && n->d == OPPOSITE(dir)) return; /* don't add impossible dir. */
385
386 struct directions* new_event = malloc (sizeof(struct directions));
387 new_event->d = dir;
388 new_event->next = NULL;
389
390 if (g.n == NULL)
391 g.n = new_event;
392 else
393 n->next = new_event;
394 }
395
396 int get_movement (void) {
397 if (g.n == NULL) return -1;
398
399 int retval = g.n->d;
400 struct directions* delet_this = g.n;
401 g.n = g.n->next;
402 free(delet_this);
403 return retval;
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