]> git.gir.st - VIper.git/blob - viiper.c
simple pause mode
[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 COL_OFFSET 1
40 #define LINE_OFFSET 1
41 #define LINES_AFTER 1
42 #define CW op.scheme->cell_width
43
44 struct game {
45 int w; /* field width */
46 int h; /* field height */
47 int d; /* direction the snake is looking */
48 int t; /* time of game start */
49 int p; /* score */
50 float v; /* velocity in moves per second */
51 struct snake* s; /* snek */
52 struct item* i; /* items (food, boni) */
53 struct directions* n;/* next direction events to process */
54 } g;
55
56 struct opt {
57 int l; /* initial snake length */
58 int s; /* initial snake speed */
59 struct scheme* scheme;
60 } op;
61
62 jmp_buf game_over;
63
64 int main (int argc, char** argv) {
65 /* defaults: */
66 g.w = 30; //two-char-width
67 g.h = 20;
68 op.l = 10;
69 op.s = 8;
70 op.scheme = &unic0de;
71
72 int optget;
73 opterr = 0; /* don't print message on unrecognized option */
74 while ((optget = getopt (argc, argv, "+s:dh")) != -1) {
75 switch (optget) {
76 case 's':
77 op.s = atof(optarg);
78 if (op.s < 1) {
79 fprintf (stderr, SHORTHELP "speed must be >= 1\n", argv[0]);
80 return 1;
81 }
82 break;
83 case 'd': op.scheme = &vt220_charset; break;
84 case 'h':
85 default:
86 fprintf (stderr, SHORTHELP LONGHELP, argv[0]);
87 return !(optget=='h');
88 }
89 } if (optind < argc) { /* parse Fieldspec */
90 int n = sscanf (argv[optind], "%dx%d", &g.w, &g.h);
91
92 if (n < 2) {
93 fprintf (stderr, SHORTHELP "FIELDSIZE is WxH (width 'x' height)\n", argv[0]);
94 return 1;
95 }
96 }
97
98 clamp_fieldsize();
99
100 srand(time(0));
101 signal_setup();
102 screen_setup(1);
103 atexit (*quit);
104
105 if (sigsetjmp(game_over, 1)) {
106 timer_setup(0);
107 move_ph (g.h/2+LINE_OFFSET, g.w);
108 printf ("you died :(");
109 fflush(stdout);
110 sleep(5);
111 exit(0);
112 }
113
114 //TODO: call viiper() in a game loop
115 viiper();
116 quit:
117 return 0;
118 }
119
120 int viiper(void) {
121 init_snake();
122 show_playfield ();
123 g.d = EAST;
124 g.v = op.s;
125
126 timer_setup(1);
127 g.t = time(NULL);
128
129 spawn_item(FOOD, rand() % NUM_FOODS); //TODO: shape distribution, so bigger values get selected less
130
131 for(;;) {
132 switch (getctrlseq()) {
133 case CTRSEQ_CURSOR_LEFT: case 'h':append_movement(WEST); break;
134 case CTRSEQ_CURSOR_DOWN: case 'j':append_movement(SOUTH); break;
135 case CTRSEQ_CURSOR_UP: case 'k':append_movement(NORTH); break;
136 case CTRSEQ_CURSOR_RIGHT:case 'l':append_movement(EAST); break;
137 case 'p':
138 timer_setup(0);
139 move_ph (g.h/2+LINE_OFFSET, g.w*CW/2);
140 printf ("PAUSE");
141 if (getchar() == 'q') exit(0);
142 timer_setup(1);
143 break;
144 case 'r': /*TODO:restart*/ return 0;
145 case 'q': return 0;
146 case CTRL_'L':
147 screen_setup(1);
148 show_playfield();
149 break;
150 }
151
152 print ("\033[H\033[J");
153 show_playfield ();//TODO: only redraw diff
154 }
155
156 }
157
158 void snake_advance (void) {
159 if (g.n) {/* new direction in the buffer */
160 int possible_new_dir = get_movement();
161 if (g.d == EAST && possible_new_dir == WEST) goto ignore_new;
162 if (g.d == WEST && possible_new_dir == EAST) goto ignore_new;
163 if (g.d == NORTH && possible_new_dir == SOUTH) goto ignore_new;
164 if (g.d == SOUTH && possible_new_dir == NORTH) goto ignore_new;
165 g.d = possible_new_dir; /*pop off a new direction if available*/
166 ignore_new:
167 1;
168 }
169
170 int new_row = g.s->r +(g.d==SOUTH) -(g.d==NORTH);
171 int new_col = g.s->c +(g.d==EAST) -(g.d==WEST);
172
173 /* detect food hit and spawn a new food */
174 for (struct item* i = g.i; i; i = i->next) {
175 if (i->r == new_row && i->c == new_col) {
176 consume_item (i);
177 spawn_item(FOOD, rand() % NUM_FOODS);
178 }
179 }
180
181 /*NOTE:no idea why I have to use g.w+1, but otherwise we die too early*/
182 if (new_row >= g.h || new_col >= g.w+1 || new_row < 0 || new_col < 0)
183 siglongjmp(game_over, 1/*<-will be the retval of setjmp*/);
184
185 struct snake* new_head;
186 struct snake* new_tail; /* former second-to-last element */
187 for (new_tail = g.s; new_tail->next->next; new_tail = new_tail->next)
188 /* use the opportunity of looping to check if we eat ourselves*/
189 if(new_tail->next->r == new_row && new_tail->next->c == new_col)
190 siglongjmp(game_over, 1/*<-will be the retval of setjmp*/);
191 new_head = new_tail->next; /* reuse element instead of malloc() */
192 new_tail->next = NULL;
193
194 new_head->r = new_row;
195 new_head->c = new_col;
196 new_head->next = g.s;
197
198 g.s = new_head;
199 }
200
201 void spawn_item (int type, int value) {
202 int row, col;
203 try_again:
204 row = rand() % g.h;
205 col = rand() % g.w;
206 /* loop through snake to check if we aren't on it */
207 //WARN: inefficient as snake gets longer; near impossible in the end
208 for (struct snake* s = g.s; s; s = s->next)
209 if (s->r == row && s->c == col) goto try_again;
210
211 struct item* new_item = malloc (sizeof(struct item));
212 new_item->r = row;
213 new_item->c = col;
214 new_item->t = type;
215 new_item->v = value;
216 new_item->s = time(0);
217 if (g.i) g.i->prev = new_item;
218 new_item->next = g.i;
219 new_item->prev = NULL;
220
221 g.i = new_item;
222 }
223
224 void consume_item (struct item* i) {
225 switch (i->t) {
226 case FOOD:
227 switch (i->v) {
228 case FOOD_5: g.p += 5; break;
229 case FOOD_10: g.p += 10; break;
230 case FOOD_20: g.p += 20; break;
231 }
232 snake_append(&g.s, 0,0); /* position doesn't matter, as item */
233 break; /* will be reused as the head before it is drawn */
234 case BONUS:
235 //TODO: handle bonus
236 break;
237 }
238
239 if (i->next) i->next->prev = i->prev;
240 if (i->prev) i->prev->next = i->next;
241 else g.i = i->next;
242
243 free (i);
244 }
245
246 void show_playfield (void) {
247 /* top border */
248 print(BORDER(T,L));
249 printm (g.w, BORDER(T,C));
250 printf ("%s\n", BORDER(T,R));
251
252 /* main area */
253 for (int row = 0; row < g.h; row++)
254 printf ("%s%*s%s\n", BORDER(C,L), CW*g.w, "", BORDER(C,R));
255
256 /* bottom border */
257 print(BORDER(B,L));
258 printm (g.w, BORDER(B,C));
259 print (BORDER(B,R));
260
261 /* print score */
262 int score_width = g.p > 9999?6:4;
263 move_ph (0, (g.w*CW-score_width)/2);
264 printf ("%s %0*d %s", BORDER(S,L), score_width, g.p, BORDER(S,R));
265
266 /* print snake */
267 struct snake* last = NULL;
268 int color = -1; //TODO: that's a hack
269 for (struct snake* s = g.s; s; s = s->next) {
270 move_ph (s->r+COL_OFFSET, s->c*CW+LINE_OFFSET);
271
272 int predecessor = (last==NULL)?NONE:
273 (last->r < s->r) ? NORTH:
274 (last->r > s->r) ? SOUTH:
275 (last->c > s->c) ? EAST:
276 (last->c < s->c) ? WEST:NONE;
277 int successor = (s->next == NULL)?NONE:
278 (s->next->r < s->r) ? NORTH:
279 (s->next->r > s->r) ? SOUTH:
280 (s->next->c > s->c) ? EAST:
281 (s->next->c < s->c) ? WEST:NONE;
282
283 printf ("\033[%sm", color==-1?"92;1":color?"92":"32"); //TODO: clean this up
284 print (op.scheme->snake[predecessor][successor]);
285 printf ("\033[0m");
286 last = s;
287 color = (color+1) % 2;
288 }
289
290 /* print item queue */
291 for (struct item* i = g.i; i; i = i->next) {
292 move_ph (i->r+LINE_OFFSET, i->c*CW+COL_OFFSET);
293 if (i->t == FOOD) print (op.scheme->item[i->v]);
294 else if (i->t==BONUS) /* TODO: print bonus */;
295 }
296 }
297
298 void snake_append (struct snake** s, int row, int col) {
299 struct snake* new = malloc (sizeof(struct snake));
300 new->r = row;
301 new->c = col;
302 new->next = NULL;
303
304 if (*s) {
305 struct snake* p = *s;
306 while (p->next) p = p->next;
307 p->next = new;
308 } else {
309 *s = new;
310 }
311 }
312
313 void init_snake() {
314 for (int i = 0; i < op.l; i++)
315 snake_append(&g.s, g.h/2, g.w/2-i);
316 }
317
318 #define free_ll(head) do{ \
319 while (head) { \
320 void* tmp = head; \
321 head = head->next; \
322 free(tmp); \
323 } \
324 }while(0)
325
326 void quit (void) {
327 screen_setup(0);
328 free_ll(g.s);
329 free_ll(g.i);
330 free_ll(g.n);
331 }
332
333 enum esc_states {
334 START,
335 ESC_SENT,
336 CSI_SENT,
337 MOUSE_EVENT,
338 };
339 int getctrlseq (void) {
340 int c;
341 int state = START;
342 int offset = 0x20; /* never sends control chars as data */
343 while ((c = getchar()) != EOF) {
344 switch (state) {
345 case START:
346 switch (c) {
347 case '\033': state=ESC_SENT; break;
348 default: return c;
349 }
350 break;
351 case ESC_SENT:
352 switch (c) {
353 case '[': state=CSI_SENT; break;
354 default: return CTRSEQ_INVALID;
355 }
356 break;
357 case CSI_SENT:
358 switch (c) {
359 case 'A': return CTRSEQ_CURSOR_UP;
360 case 'B': return CTRSEQ_CURSOR_DOWN;
361 case 'C': return CTRSEQ_CURSOR_RIGHT;
362 case 'D': return CTRSEQ_CURSOR_LEFT;
363 default: return CTRSEQ_INVALID;
364 }
365 break;
366 default:
367 return CTRSEQ_INVALID;
368 }
369 }
370 return 2;
371 }
372
373 void append_movement (int dir) {
374 struct directions* n;
375 for (n = g.n; n && n->next; n = n->next); /* advance to the end */
376 if (n && n->d == dir) return; /* don't add the same direction twice */
377
378 struct directions* new_event = malloc (sizeof(struct directions));
379 new_event->d = dir;
380 new_event->next = NULL;
381
382 if (g.n == NULL)
383 g.n = new_event;
384 else
385 n->next = new_event;
386 }
387
388 int get_movement (void) {
389 if (g.n == NULL) return -1;
390
391 int retval = g.n->d;
392 struct directions* delet_this = g.n;
393 g.n = g.n->next;
394 free(delet_this);
395 return retval;
396 }
397
398 void move_ph (int line, int col) {
399 /* move printhead to zero-indexed position */
400 printf ("\033[%d;%dH", line+1, col+1);
401 }
402
403 void clamp_fieldsize (void) { //TODO: use
404 /* clamp field size to terminal size and mouse maximum: */
405 struct winsize w;
406 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
407
408 if (g.w < 1) g.w = 1; //TODO. sensible minimum
409 if (g.h < 1) g.h = 1;
410
411 if (COL_OFFSET + g.w*CW + COL_OFFSET > w.ws_col)
412 g.w = (w.ws_col - COL_OFFSET - COL_OFFSET)/CW-1; //TODO: does not work in `-d' (in xterm)
413 if (LINE_OFFSET + g.h + LINES_AFTER > w.ws_row)
414 g.h = w.ws_row - (LINE_OFFSET+LINES_AFTER);
415 }
416
417 void timer_setup (int enable) {
418 static struct itimerval tbuf;
419 tbuf.it_interval.tv_sec = 0;//TODO: make it speed up automatically
420 tbuf.it_interval.tv_usec = (1000000/g.v)-1; /*WARN: 1 <= g.v <= 999999*/
421
422 if (enable) {
423 tbuf.it_value.tv_sec = tbuf.it_interval.tv_sec;
424 tbuf.it_value.tv_usec = tbuf.it_interval.tv_usec;
425 } else {
426 tbuf.it_value.tv_sec = 0;
427 tbuf.it_value.tv_usec = 0;
428 }
429
430 if ( setitimer(ITIMER_REAL, &tbuf, NULL) == -1 ) {
431 perror("setitimer");
432 exit(1);
433 }
434
435 }
436
437 void signal_setup (void) {
438 struct sigaction saction;
439
440 saction.sa_handler = signal_handler;
441 sigemptyset(&saction.sa_mask);
442 saction.sa_flags = 0;
443 if (sigaction(SIGALRM, &saction, NULL) < 0 ) {
444 perror("SIGALRM");
445 exit(1);
446 }
447
448 if (sigaction(SIGINT, &saction, NULL) < 0 ) {
449 perror ("SIGINT");
450 exit (1);
451 }
452 }
453
454 void signal_handler (int signum) {
455 //int dtime;
456 switch (signum) {
457 case SIGALRM:
458 //dtime = difftime (time(NULL), g.t);
459 //move_ph (1, g.w*CW-(CW%2)-3-(dtime>999));
460 //printf ("[%03d]", g.t?dtime:0);
461 snake_advance();
462 break;
463 case SIGINT:
464 exit(128+SIGINT);
465 }
466 }
467
468 void screen_setup (int enable) {
469 if (enable) {
470 raw_mode(1);
471 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
472 printf ("\033[H\033[J"); /* reset cursor, clear screen */
473 printf ("\033[?25l"); /* hide cursor */
474 print (op.scheme->init_seq); /* swich charset, if necessary */
475 } else {
476 print (op.scheme->reset_seq); /* reset charset, if necessary */
477 printf ("\033[?25h"); /* show cursor */
478 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
479 raw_mode(0);
480 }
481 }
482
483 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
484 void raw_mode(int enable) {
485 static struct termios saved_term_mode;
486 struct termios raw_term_mode;
487
488 if (enable) {
489 tcgetattr(STDIN_FILENO, &saved_term_mode);
490 raw_term_mode = saved_term_mode;
491 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
492 raw_term_mode.c_cc[VMIN] = 1 ;
493 raw_term_mode.c_cc[VTIME] = 0;
494 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
495 } else {
496 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
497 }
498 }
Imprint / Impressum