]> git.gir.st - VIper.git/blob - viiper.c
update readme TODOs
[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 if (*s) {
290 struct snake* p = *s;
291 while (p->next) p = p->next;
292 p->next = new;
293 } else {
294 *s = new;
295 }
296 }
297
298 void init_snake() {
299 for (int i = 0; i < op.l; i++)
300 snake_append(&g.s, g.h/2, g.w/2-i);
301 }
302
303 #define free_ll(head) do{ \
304 while (head) { \
305 void* tmp = head; \
306 head = head->next; \
307 free(tmp); \
308 } \
309 }while(0)
310
311 void quit (void) {
312 screen_setup(0);
313 free_ll(g.s);
314 free_ll(g.i);
315 free_ll(g.n); //TODO: doesn't get free'd correctly
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* n;
360 for (n = g.n; n && n->next; n = n->next); /* advance to the end */
361 if (n && n->d == dir) return; /* don't add the same direction twice */
362
363 struct directions* new_event = malloc (sizeof(struct directions));
364 new_event->d = dir;
365 new_event->next = NULL;
366
367 if (g.n == NULL)
368 g.n = new_event;
369 else
370 n->next = new_event;
371 }
372
373 int get_movement (void) {
374 if (g.n == NULL) return -1;
375
376 int retval = g.n->d;
377 struct directions* delet_this = g.n;
378 g.n = g.n->next;
379 free(delet_this);
380 return retval;
381 }
382
383 void move_ph (int line, int col) {
384 /* move printhead to zero-indexed position */
385 printf ("\033[%d;%dH", line+1, col+1);
386 }
387
388 void clamp_fieldsize (void) { //TODO: use
389 /* clamp field size to terminal size and mouse maximum: */
390 struct winsize w;
391 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
392
393 if (g.w < 1) g.w = 1;
394 if (g.h < 1) g.h = 1;
395
396 if (COL_OFFSET + g.w*CW + COL_OFFSET > w.ws_col)
397 g.w = (w.ws_col - COL_OFFSET - COL_OFFSET)/CW; //TODO: does not work in `-d' (in xterm)
398 if (LINE_OFFSET + g.h + LINES_AFTER > w.ws_row)
399 g.h = w.ws_row - (LINE_OFFSET+LINES_AFTER);
400 }
401
402 void timer_setup (int enable) {
403 static struct itimerval tbuf;
404 tbuf.it_interval.tv_sec = 0;//TODO: make configurable, TODO: speed up
405 tbuf.it_interval.tv_usec = (1000000/g.f)-1; /*WARN: 1 <= g.f <= 999999*/
406
407 if (enable) {
408 g.t = time(NULL);//TODO: interferes with 'pause'
409 tbuf.it_value.tv_sec = tbuf.it_interval.tv_sec;
410 tbuf.it_value.tv_usec = tbuf.it_interval.tv_usec;
411 } else {
412 tbuf.it_value.tv_sec = 0;
413 tbuf.it_value.tv_usec = 0;
414 }
415
416 if ( setitimer(ITIMER_REAL, &tbuf, NULL) == -1 ) {
417 perror("setitimer");
418 exit(1);
419 }
420
421 }
422
423 void signal_setup (void) {
424 struct sigaction saction;
425
426 saction.sa_handler = signal_handler;
427 sigemptyset(&saction.sa_mask);
428 saction.sa_flags = 0;
429 if (sigaction(SIGALRM, &saction, NULL) < 0 ) {
430 perror("SIGALRM");
431 exit(1);
432 }
433
434 if (sigaction(SIGINT, &saction, NULL) < 0 ) {
435 perror ("SIGINT");
436 exit (1);
437 }
438 }
439
440 void signal_handler (int signum) {
441 //int dtime;
442 switch (signum) {
443 case SIGALRM:
444 //dtime = difftime (time(NULL), g.t);
445 //move_ph (1, g.w*CW-(CW%2)-3-(dtime>999));
446 //printf ("[%03d]", g.t?dtime:0);
447 snake_advance();
448 break;
449 case SIGINT:
450 exit(128+SIGINT);
451 }
452 }
453
454 void screen_setup (int enable) {
455 if (enable) {
456 raw_mode(1);
457 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
458 printf ("\033[H\033[J"); /* reset cursor, clear screen */
459 printf ("\033[?25l"); /* hide cursor */
460 print (op.scheme->init_seq); /* swich charset, if necessary */
461 } else {
462 print (op.scheme->reset_seq); /* reset charset, if necessary */
463 printf ("\033[?25h"); /* show cursor */
464 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
465 raw_mode(0);
466 }
467 }
468
469 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
470 void raw_mode(int enable) {
471 static struct termios saved_term_mode;
472 struct termios raw_term_mode;
473
474 if (enable) {
475 tcgetattr(STDIN_FILENO, &saved_term_mode);
476 raw_term_mode = saved_term_mode;
477 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
478 raw_term_mode.c_cc[VMIN] = 1 ;
479 raw_term_mode.c_cc[VTIME] = 0;
480 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
481 } else {
482 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
483 }
484 }
Imprint / Impressum