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