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