]> git.gir.st - VIper.git/blob - viiper.c
experiment with snake speeds (very ugly)
[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 struct snake* s; /* snek */ //TODO: rename to S
49 struct item* i; /* items (food, boni) */
50 int d; /* direction the snake is looking */
51 int n;/* direction to move on next tick */
52 int t; /* time of game start */
53 int p; /* score */ //TODO: rename?
54 float f; /* speed in moves per second */ //TODO: rename
55 } g;
56
57 struct opt {
58 struct scheme* scheme;
59 int l; /* initial snake length */
60 int s; /* initial snake speed */
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 = 2;
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 = g.n = 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;
107 case '#': if (g.f > 1) g.f--;timer_setup(1); break;
108 case 'h': if (g.d != EAST) g.n = WEST; break;
109 case 'j': if (g.d != NORTH) g.n = SOUTH; break;
110 case 'k': if (g.d != SOUTH) g.n = NORTH; break;
111 case 'l': if (g.d != WEST) g.n = EAST; break;
112 case 'p': /*TODO: pause*/ break;
113 case 'r': /*TODO:restart*/ return 0;
114 case 'q': return 0;
115 case CTRL_'L':
116 screen_setup(1);
117 show_playfield();
118 break;
119 }
120
121 print ("\033[H\033[J");
122 show_playfield ();//TODO: only redraw diff
123 }
124
125 }
126
127 void snake_advance (void) {
128 g.d = g.n;
129 int new_row = g.s->r +(g.d==SOUTH) -(g.d==NORTH);
130 int new_col = g.s->c +(g.d==EAST) -(g.d==WEST);
131
132 /* detect food hit and spawn a new food */
133 for (struct item* i = g.i; i; i = i->next) {
134 if (i->r == new_row && i->c == new_col) {
135 consume_item (i);
136 spawn_item(FOOD, rand() % NUM_FOODS);
137 }
138 }
139
140 if (new_row >= g.h || new_col >= g.w || new_row < 0 || new_col < 0)
141 exit(1); //TODO: longjump?
142
143 struct snake* new_head;
144 struct snake* new_tail; /* former second-to-last element */
145 for (new_tail = g.s; new_tail->next->next; new_tail = new_tail->next)
146 /* use the opportunity of looping to check if we eat ourselves*/
147 if(new_tail->next->r == new_row && new_tail->next->c == new_col)
148 exit(1);
149 new_head = new_tail->next; /* reuse element instead of malloc() */
150 new_tail->next = NULL;
151
152 new_head->r = new_row;
153 new_head->c = new_col;
154 new_head->next = g.s;
155
156 g.s = new_head;
157 }
158
159 void spawn_item (int type, int value) {
160 int row, col;
161 try_again:
162 row = rand() % g.h;
163 col = rand() % g.w;
164 /* loop through snake to check if we aren't on it */
165 //TODO: inefficient as snake gets longer; near impossible in the end
166 for (struct snake* s = g.s; s; s = s->next)
167 if (s->r == row && s->c == col) goto try_again;
168
169 //3. get item from category TODO
170 struct item* new_item = malloc (sizeof(struct item));
171 new_item->r = row;
172 new_item->c = col;
173 new_item->t = type;
174 new_item->v = value;
175 new_item->s = time(0);
176 if (g.i) g.i->prev = new_item;
177 new_item->next = g.i;
178
179 g.i = new_item;
180 }
181
182 void consume_item (struct item* i) {
183 struct item* predecessor = i->prev;
184 struct item* successor = i->next;
185
186 switch (i->t) {
187 case FOOD:
188 switch (i->v) {
189 case FOOD_5: g.p += 5; break;
190 case FOOD_10: g.p += 10; break;
191 case FOOD_20: g.p += 20; break;
192 }
193 snake_append(g.s, 0,0); /* position doesn't matter, as item */
194 break; /* will be reused as the head before it is drawn */
195 case BONUS:
196 //handle bonus
197 break;
198 }
199
200 if (predecessor == NULL) {
201 g.i = successor;
202 if (successor) successor->prev = NULL;
203 } else {
204 predecessor->next = successor;
205 successor->prev = predecessor;
206 }
207
208 free (i);
209 }
210
211 void show_playfield (void) {
212 //int score_width = g.p > 9999?6:4;
213 int score_width = 4; // v- = the -| spacer |-
214 float half_width = (g.w - score_width/CW - 2)/2.0; //TODO: this whole endavour is ugly
215 /* top border */
216 print(BORDER(T,L));
217 printm (half_width, BORDER(T,C)); //TODO: i bet this breaks in dec mode
218 printf ("%s %0*d %s", BORDER(S,L), score_width, g.p, BORDER(S,R));
219 printm ((int)(half_width+.5), BORDER(T,C));
220 printf ("%s\n", BORDER(T,R));
221
222 /* main area */
223 for (int row = 0; row < g.h; row++)
224 printf ("%s%*s%s\n", BORDER(C,L), CW*g.w, "", BORDER(C,R));
225
226 /* bottom border */
227 print(BORDER(B,L));
228 printm (g.w, BORDER(B,C));
229 print (BORDER(B,R));
230
231 /* print snake */
232 struct snake* last = NULL;
233 for (struct snake* s = g.s; s; s = s->next) {
234 move_ph (s->r+COL_OFFSET, s->c*CW+LINE_OFFSET);
235
236 int predecessor = (last==NULL)?NONE:
237 (last->r < s->r) ? NORTH:
238 (last->r > s->r) ? SOUTH:
239 (last->c > s->c) ? EAST:
240 (last->c < s->c) ? WEST:NONE;
241 int successor = (s->next == NULL)?NONE:
242 (s->next->r < s->r) ? NORTH:
243 (s->next->r > s->r) ? SOUTH:
244 (s->next->c > s->c) ? EAST:
245 (s->next->c < s->c) ? WEST:NONE;
246
247 print (op.scheme->snake[predecessor][successor]);
248 last = s;
249 }
250
251 /* print item queue */
252 for (struct item* i = g.i; i; i = i->next) {
253 move_ph (i->r+LINE_OFFSET, i->c*CW+COL_OFFSET);
254 if (i->t == FOOD) print (op.scheme->item[i->v]);
255 else if (i->t==BONUS) /* TODO: print bonus */;
256 }
257
258 //TODO: temporarily print speed
259 move_ph (g.h+LINE_OFFSET, g.w);
260 printf ("%f", g.f);
261 }
262
263 void snake_append (struct snake* s, int row, int col) {
264 struct snake* new = malloc (sizeof(struct snake));
265 new->r = row;
266 new->c = col;
267 new->next = NULL;
268
269 struct snake* p = s;
270 while (p->next) p = p->next;
271 p->next = new;
272 }
273
274 void init_snake() {
275 g.s = malloc (sizeof(struct snake));
276 g.s->r = g.h/2;
277 g.s->c = g.w/2;
278 g.s->next=NULL;
279
280 for (int i = 1; i < op.l; i++)
281 snake_append(g.s, g.h/2, g.w/2-i);
282 }
283
284 void quit (void) {
285 screen_setup(0);
286 for (struct snake* s = g.s; s;) {
287 struct snake* tmp = s->next;
288 free (s);
289 s = tmp;
290 }
291 for (struct item* i = g.i; i;) {
292 struct item* tmp = i->next;
293 free (i);
294 i = tmp;
295 }
296 }
297
298 enum esc_states {
299 START,
300 ESC_SENT,
301 CSI_SENT,
302 MOUSE_EVENT,
303 };
304 int getctrlseq (void) {
305 int c;
306 int state = START;
307 int offset = 0x20; /* never sends control chars as data */
308 while ((c = getchar()) != EOF) {
309 switch (state) {
310 case START:
311 switch (c) {
312 case '\033': state=ESC_SENT; break;
313 default: return c;
314 }
315 break;
316 case ESC_SENT:
317 switch (c) {
318 case '[': state=CSI_SENT; break;
319 default: return CTRSEQ_INVALID;
320 }
321 break;
322 case CSI_SENT:
323 switch (c) {
324 case 'A': return CTRSEQ_CURSOR_UP;
325 case 'B': return CTRSEQ_CURSOR_DOWN;
326 case 'C': return CTRSEQ_CURSOR_RIGHT;
327 case 'D': return CTRSEQ_CURSOR_LEFT;
328 default: return CTRSEQ_INVALID;
329 }
330 break;
331 default:
332 return CTRSEQ_INVALID;
333 }
334 }
335 return 2;
336 }
337
338 void move_ph (int line, int col) {
339 /* move printhead to zero-indexed position */
340 printf ("\033[%d;%dH", line+1, col+1);
341 }
342
343 void clamp_fieldsize (void) {
344 /* clamp field size to terminal size and mouse maximum: */
345 struct winsize w;
346 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
347
348 if (g.w < 1) g.w = 1;
349 if (g.h < 1) g.h = 1;
350
351 if (COL_OFFSET + g.w*CW + COL_OFFSET > w.ws_col)
352 g.w = (w.ws_col - COL_OFFSET - COL_OFFSET)/CW; //TODO: does not work in `-d' (in xterm)
353 if (LINE_OFFSET + g.h + LINES_AFTER > w.ws_row)
354 g.h = w.ws_row - (LINE_OFFSET+LINES_AFTER);
355 }
356
357 void timer_setup (int enable) {
358 static struct itimerval tbuf;
359 tbuf.it_interval.tv_sec = 0;//TODO: make configurable, TODO: speed up
360 tbuf.it_interval.tv_usec = (1000000/g.f)-1; /*WARN: 1 <= g.f <= 999999*/
361
362 if (enable) {
363 g.t = time(NULL);
364 tbuf.it_value.tv_sec = tbuf.it_interval.tv_sec;
365 tbuf.it_value.tv_usec = tbuf.it_interval.tv_usec;
366 if (setitimer(ITIMER_REAL, &tbuf, NULL) == -1) {
367 perror("setitimer");
368 exit(1);
369 }
370 } else {
371 tbuf.it_value.tv_sec = 0;
372 tbuf.it_value.tv_usec = 0;
373 if ( setitimer(ITIMER_REAL, &tbuf, NULL) == -1 ) {
374 perror("setitimer");
375 exit(1);
376 }
377 }
378
379 }
380
381 void signal_setup (void) {
382 struct sigaction saction;
383
384 saction.sa_handler = signal_handler;
385 sigemptyset(&saction.sa_mask);
386 saction.sa_flags = 0;
387 if (sigaction(SIGALRM, &saction, NULL) < 0 ) {
388 perror("SIGALRM");
389 exit(1);
390 }
391
392 if (sigaction(SIGINT, &saction, NULL) < 0 ) {
393 perror ("SIGINT");
394 exit (1);
395 }
396 }
397
398 void signal_handler (int signum) {
399 //int dtime;
400 switch (signum) {
401 case SIGALRM:
402 //dtime = difftime (time(NULL), g.t);
403 //move_ph (1, g.w*CW-(CW%2)-3-(dtime>999));
404 //printf ("[%03d]", g.t?dtime:0);
405 snake_advance();
406 break;
407 case SIGINT:
408 exit(128+SIGINT);
409 }
410 }
411
412 void screen_setup (int enable) {
413 if (enable) {
414 raw_mode(1);
415 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
416 printf ("\033[H\033[J"); /* reset cursor, clear screen */
417 printf ("\033[?25l"); /* hide cursor */
418 //print (op.scheme->init_seq); /* swich charset, if necessary */
419 } else {
420 //print (op.scheme->reset_seq); /* reset charset, if necessary */
421 printf ("\033[?25h"); /* show cursor */
422 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
423 raw_mode(0);
424 }
425 }
426
427 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
428 void raw_mode(int enable) {
429 static struct termios saved_term_mode;
430 struct termios raw_term_mode;
431
432 if (enable) {
433 tcgetattr(STDIN_FILENO, &saved_term_mode);
434 raw_term_mode = saved_term_mode;
435 raw_term_mode.c_lflag &= ~(ICANON | ECHO);
436 raw_term_mode.c_cc[VMIN] = 1 ;
437 raw_term_mode.c_cc[VTIME] = 0;
438 tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw_term_mode);
439 } else {
440 tcsetattr(STDIN_FILENO, TCSAFLUSH, &saved_term_mode);
441 }
442 }
Imprint / Impressum