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