]> git.gir.st - VIper.git/blob - viiper.c
WIP: only redraw changed bits
[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 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 break;
158 }
159
160 // show_playfield ();//TODO: only redraw diff
161 }
162
163 }
164
165 void snake_advance (void) {
166 if (g.n) {/* new direction in the buffer */
167 int possible_new_dir = get_movement();
168 if (g.d != OPPOSITE(possible_new_dir))
169 g.d = possible_new_dir;
170 }
171
172 int new_row = g.s->r +(g.d==SOUTH) -(g.d==NORTH);
173 int new_col = g.s->c +(g.d==EAST) -(g.d==WEST);
174
175 /* detect food hit and spawn a new food */
176 for (struct item* i = g.i; i; i = i->next) {
177 if (i->r == new_row && i->c == new_col) {
178 consume_item (i);
179 spawn_item(FOOD, rand() % NUM_FOODS, i);
180 }
181 }
182
183 /* NOTE: we are drawing the snake 1 column too far to the left, so it
184 can directly touch the vertical walls. this also means that we essen-
185 tially extend the width by 1 cell, so we need to check against g.w+1. */
186 if (new_row >= g.h || new_col >= g.w+1 || 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/*<-will be the retval of setjmp*/);
195 int old_tail[2] = {new_tail->next->r, new_tail->next->c}; /* save it for erasing */
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;
217
218 struct item* new_item;
219 if (p_item) new_item = p_item;
220 else new_item = malloc (sizeof(struct item));
221
222 new_item->r = row;
223 new_item->c = col;
224 new_item->t = type;
225 new_item->v = value;
226 new_item->s = time(0);
227 if (g.i) g.i->prev = new_item;
228 new_item->next = g.i;
229 new_item->prev = NULL;
230
231 g.i = new_item;
232 }
233
234 void consume_item (struct item* i) {
235 switch (i->t) {
236 case FOOD:
237 switch (i->v) {
238 case FOOD_5: g.p += 5; break;
239 case FOOD_10: g.p += 10; break;
240 case FOOD_20: g.p += 20; break;
241 }
242 snake_append(&g.s, 0,0); /* position doesn't matter, as item */
243 break; /* will be reused as the head before it is drawn */
244 case BONUS:
245 //TODO: handle bonus
246 break;
247 }
248
249 if (i->next) i->next->prev = i->prev;
250 if (i->prev) i->prev->next = i->next;
251 else g.i = i->next;
252 }
253
254 void show_playfield (void) {
255 move_ph (0,0);
256
257 /* top border */
258 print(BORDER(T,L));
259 printm (g.w, BORDER(T,C));
260 printf ("%s\n", BORDER(T,R));
261
262 /* main area */
263 for (int row = 0; row < g.h; row++)
264 printf ("%s%*s%s\n", BORDER(C,L), CW*g.w, "", BORDER(C,R));
265
266 /* bottom border */
267 print(BORDER(B,L));
268 printm (g.w, BORDER(B,C));
269 print (BORDER(B,R));
270 }
271
272 void draw_sprites (int erase_r, int erase_c) {
273 /* erase old tail */
274 move_ph (erase_r+LINE_OFFSET, erase_c*CW+COL_OFFSET);
275 printm (CW, " ");
276
277 /* print snake */
278 struct snake* last = NULL;
279 int color = 2;
280 for (struct snake* s = g.s; s; s = s->next) {
281 move_ph (s->r+LINE_OFFSET, s->c*CW+COL_OFFSET); /*NOTE: all those are actually wrong; draws snake 1 col too far left*/
282
283 int predecessor = (last==NULL)?NONE:
284 (last->r < s->r) ? NORTH:
285 (last->r > s->r) ? SOUTH:
286 (last->c > s->c) ? EAST:
287 (last->c < s->c) ? WEST:NONE;
288 int successor = (s->next == NULL)?NONE:
289 (s->next->r < s->r) ? NORTH:
290 (s->next->r > s->r) ? SOUTH:
291 (s->next->c > s->c) ? EAST:
292 (s->next->c < s->c) ? WEST:NONE;
293
294 printf ("\033[%sm", op.scheme->color[color]);
295 print (op.scheme->snake[predecessor][successor]);
296 printf ("\033[0m");
297 last = s;
298 color = !color;
299 }
300
301 /* print item queue */
302 for (struct item* i = g.i; i; i = i->next) {
303 move_ph (i->r+LINE_OFFSET, i->c*CW+COL_OFFSET);
304 if (i->t == FOOD) print (op.scheme->item[i->v]);
305 else if (i->t==BONUS) /* TODO: print bonus */;
306 }
307
308 /* print score */
309 int score_width = g.p > 9999?6:4;
310 move_ph (0, (g.w*CW-score_width)/2);
311 printf ("%s %0*d %s", BORDER(S,L), score_width, g.p, BORDER(S,R));
312 }
313
314 void snake_append (struct snake** s, int row, int col) {
315 struct snake* new = malloc (sizeof(struct snake));
316 new->r = row;
317 new->c = col;
318 new->next = NULL;
319
320 if (*s) {
321 struct snake* p = *s;
322 while (p->next) p = p->next;
323 p->next = new;
324 } else {
325 *s = new;
326 }
327 }
328
329 void init_snake() {
330 for (int i = 0; i < op.l; i++) {
331 if (g.w/2-i < 0) break; /* stop if we hit left wall */
332 snake_append(&g.s, g.h/2, g.w/2-i);
333 }
334 }
335
336 #define free_ll(head) do{ \
337 while (head) { \
338 void* tmp = head; \
339 head = head->next; \
340 free(tmp); \
341 } \
342 }while(0)
343
344 void quit (void) {
345 screen_setup(0);
346 free_ll(g.s);
347 free_ll(g.i);
348 free_ll(g.n);
349 }
350
351 enum esc_states {
352 START,
353 ESC_SENT,
354 CSI_SENT,
355 MOUSE_EVENT,
356 };
357 int getctrlseq (void) {
358 int c;
359 int state = START;
360 int offset = 0x20; /* never sends control chars as data */
361 while ((c = getchar()) != EOF) {
362 switch (state) {
363 case START:
364 switch (c) {
365 case '\033': state=ESC_SENT; break;
366 default: return c;
367 }
368 break;
369 case ESC_SENT:
370 switch (c) {
371 case '[': state=CSI_SENT; break;
372 default: return CTRSEQ_INVALID;
373 }
374 break;
375 case CSI_SENT:
376 switch (c) {
377 case 'A': return CTRSEQ_CURSOR_UP;
378 case 'B': return CTRSEQ_CURSOR_DOWN;
379 case 'C': return CTRSEQ_CURSOR_RIGHT;
380 case 'D': return CTRSEQ_CURSOR_LEFT;
381 default: return CTRSEQ_INVALID;
382 }
383 break;
384 default:
385 return CTRSEQ_INVALID;
386 }
387 }
388 return 2;
389 }
390
391 void append_movement (int dir) {
392 struct directions* n;
393 for (n = g.n; n && n->next; n = n->next); /* advance to the end */
394 if (n && n->d == dir) return; /* don't add the same direction twice */
395 if (n && n->d == OPPOSITE(dir)) return; /* don't add impossible dir. */
396
397 struct directions* new_event = malloc (sizeof(struct directions));
398 new_event->d = dir;
399 new_event->next = NULL;
400
401 if (g.n == NULL)
402 g.n = new_event;
403 else
404 n->next = new_event;
405 }
406
407 int get_movement (void) {
408 if (g.n == NULL) return -1;
409
410 int retval = g.n->d;
411 struct directions* delet_this = g.n;
412 g.n = g.n->next;
413 free(delet_this);
414 return retval;
415 }
416
417 void move_ph (int line, int col) {
418 /* move printhead to zero-indexed position */
419 printf ("\033[%d;%dH", line+1, col+1);
420 }
421
422 void clamp_fieldsize (void) {
423 /* clamp field size to terminal size and mouse maximum: */
424 struct winsize w;
425 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
426
427 if (g.w < 10) g.w = 10;
428 if (g.h < 10) g.h = 10;
429
430 if (COL_OFFSET + g.w*CW + COL_OFFSET > w.ws_col)
431 g.w = (w.ws_col - COL_OFFSET - COL_OFFSET)/CW-1; //TODO: does not work in `-d' (in xterm)
432 if (LINE_OFFSET + g.h + LINES_AFTER > w.ws_row)
433 g.h = w.ws_row - (LINE_OFFSET+LINES_AFTER);
434 }
435
436 void timer_setup (int enable) {
437 static struct itimerval tbuf;
438 tbuf.it_interval.tv_sec = 0;//TODO: make it speed up automatically
439 tbuf.it_interval.tv_usec = (1000000/g.v)-1; /*WARN: 1 <= g.v <= 999999*/
440
441 if (enable) {
442 tbuf.it_value.tv_sec = tbuf.it_interval.tv_sec;
443 tbuf.it_value.tv_usec = tbuf.it_interval.tv_usec;
444 } else {
445 tbuf.it_value.tv_sec = 0;
446 tbuf.it_value.tv_usec = 0;
447 }
448
449 if ( setitimer(ITIMER_REAL, &tbuf, NULL) == -1 ) {
450 perror("setitimer");
451 exit(1);
452 }
453
454 }
455
456 void signal_setup (void) {
457 struct sigaction saction;
458
459 saction.sa_handler = signal_handler;
460 sigemptyset(&saction.sa_mask);
461 saction.sa_flags = 0;
462 if (sigaction(SIGALRM, &saction, NULL) < 0 ) {
463 perror("SIGALRM");
464 exit(1);
465 }
466
467 if (sigaction(SIGINT, &saction, NULL) < 0 ) {
468 perror ("SIGINT");
469 exit (1);
470 }
471 }
472
473 void signal_handler (int signum) {
474 switch (signum) {
475 case SIGALRM:
476 snake_advance();
477 break;
478 case SIGINT:
479 exit(128+SIGINT);
480 }
481 }
482
483 void screen_setup (int enable) {
484 if (enable) {
485 raw_mode(1);
486 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
487 printf ("\033[H\033[J"); /* reset cursor, clear screen */
488 printf ("\033[?25l"); /* hide cursor */
489 print (op.scheme->init_seq); /* swich charset, if necessary */
490 } else {
491 print (op.scheme->reset_seq); /* reset charset, if necessary */
492 printf ("\033[?25h"); /* show cursor */
493 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
494 raw_mode(0);
495 }
496 }
497
498 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
499 void raw_mode(int enable) {
500 static struct termios saved_term_mode;
501 struct termios raw_term_mode;
502
503 if (enable) {
504 tcgetattr(STDIN_FILENO, &saved_term_mode);
505 raw_term_mode = saved_term_mode;
506 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
507 raw_term_mode.c_cc[VMIN] = 1 ;
508 raw_term_mode.c_cc[VTIME] = 0;
509 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
510 } else {
511 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
512 }
513 }
Imprint / Impressum