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