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