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