]>
git.gir.st - VIper.git/blob - viiper.c
1 /*******************************************************************************
3 By Tobias Girstmair, 2018
6 (see ./viiper -h for full list of options)
8 KEYBINDINGS: - hjkl to move
9 - p to pause and resume
12 - (see `./minesviiper -h' for all keybindings)
14 GNU GPL v3, see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt
15 *******************************************************************************/
18 #define _POSIX_C_SOURCE 2 /*for getopt and sigaction in c99, sigsetjmp*/
24 #include <sys/ioctl.h>
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)
40 #define OPPOSITE(dir) ( \
41 dir == EAST ? WEST : \
42 dir == WEST ? EAST : \
43 dir == NORTH ? SOUTH : \
44 dir == SOUTH ? NORTH : -1)
49 #define CW op.sch->cell_width
50 #define DW op.sch->display_width
52 #define SPEEDUP_AFTER 100 /* increment speed every n points */
53 #define BONUS_INTERVAL 90 /* how often a bonus item is spawned */
54 #define BONUS_DURATION 15 /* how long one can catch the bonus */
55 #define BONUS_WARN 5 /* how long before the removal to warn */
58 int w
; /* field width */
59 int h
; /* field height */
60 int d
; /* direction the snake is looking */
62 float v
; /* velocity in moves per second */
63 time_t t
; /* time of game start */
64 struct snake
* s
; /* snek */
65 struct item
* i
; /* items (food, boni) */
67 int t
; /* bonus type (bitmask based on enum bonus_value) */
68 time_t n
; /* time of next bonus item spawn */
69 time_t w
; /* time of wall-wrap end */
70 } b
; /* bonus-related values */
72 int h
; /* write head */
73 int n
; /* number of elements */
75 } k
; /* ring buffer for direction events */
79 int l
; /* initial snake length */
80 int s
; /* initial snake speed */
86 int main (int argc
, char** argv
) {
95 opterr
= 0; /* don't print message on unrecognized option */
96 while ((optget
= getopt (argc
, argv
, "+s:l:dh")) != -1) {
101 fprintf (stderr
, "speed must be >= 1\n");
107 if (op
.s
< 2 || op
.s
> g
.w
*g
.h
-1) {
108 fprintf (stderr
, "length must be >= 2 and < W*H\n");
114 fprintf (stderr
, SHORTHELP LONGHELP
, argv
[0]);
115 return !(optget
=='h');
117 } if (optind
< argc
) { /* parse Fieldspec */
118 int n
= sscanf (argv
[optind
], "%dx%d", &g
.w
, &g
.h
);
121 fprintf(stderr
,"FIELDSIZE is WxH (width 'x' height)\n");
133 char* end_screen_msg
= "";
135 switch (sigsetjmp(game_over
, 1)) {
139 break; /* function doesn't return, but `-Wextra' complains */
141 end_screen_msg
= " GAME OVER ";
144 end_screen_msg
= "CONGRATULATIONS!";
149 for (;;) switch (end_screen(end_screen_msg
)) {
150 case 'r': goto restart
;
176 g
.b
.n
= time(NULL
) + BONUS_INTERVAL
;
179 spawn_item(FOOD
, rand() % NUM_FOODS
, NULL
);
182 switch (getctrlseq()) {
183 case 'h': case CTRSEQ_CURSOR_LEFT
: append_movement(WEST
); break;
184 case 'j': case CTRSEQ_CURSOR_DOWN
: append_movement(SOUTH
);break;
185 case 'k': case CTRSEQ_CURSOR_UP
: append_movement(NORTH
);break;
186 case 'l': case CTRSEQ_CURSOR_RIGHT
:append_movement(EAST
); break;
187 case 'p': pause_game(); break;
188 case 'r': siglongjmp(game_over
, GAME_START
);
189 case 'q': siglongjmp(game_over
, GAME_EXIT
);
194 case 0x02: /* STX; gets sent when returning from SIGALRM */
201 #define pop_dir() (g.k.n? g.k.c[(16+g.k.h-g.k.n--)%16] : NONE)
202 void snake_advance (void) {
204 struct item
* i
; /*temporary item (defined here to respawn at the end) */
205 int new_dir
= pop_dir();
206 /* switch direction if new one is in the buffer and it won't kill us: */
207 if (new_dir
&& g
.d
!= OPPOSITE(new_dir
)) g
.d
= new_dir
;
209 int new_row
= g
.s
->r
+(g
.d
==SOUTH
) -(g
.d
==NORTH
);
210 int new_col
= g
.s
->c
+(g
.d
==EAST
) -(g
.d
==WEST
);
212 /* detect food hit and spawn a new food */
213 for (i
= g
.i
; i
; i
= i
->next
) {
214 if (i
->r
== new_row
&& i
->c
== new_col
) {
218 case FOOD
: respawn
= 1; break;
219 case BONUS
: remove_bonus(i
); break;
225 if (g
.b
.t
& 1<<BONUS_WRAP
) {
226 if (new_row
>= g
.h
) new_row
= 0;
227 if (new_col
>= g
.w
) new_col
= 0;
228 if (new_row
< 0) new_row
= g
.h
-1;
229 if (new_col
< 0) new_col
= g
.w
-1;
231 if (new_row
>= g
.h
|| new_col
>= g
.w
|| new_row
< 0 || new_col
< 0)
232 siglongjmp(game_over
, GAME_OVER
);
235 struct snake
* new_head
;
236 struct snake
* new_tail
; /* former second-to-last element */
237 for (new_tail
= g
.s
; new_tail
->next
->next
; new_tail
= new_tail
->next
)
238 /*use the opportunity of looping to check if we eat ourselves:*/
239 if(new_tail
->next
->r
== new_row
&& new_tail
->next
->c
== new_col
)
240 siglongjmp(game_over
, GAME_OVER
);
241 int old_tail
[2] = {new_tail
->next
->r
, new_tail
->next
->c
};/*gets erased*/
242 new_head
= new_tail
->next
; /* reuse element instead of malloc() */
243 new_tail
->next
= NULL
;
245 new_head
->r
= new_row
;
246 new_head
->c
= new_col
;
247 new_head
->next
= g
.s
;
251 /* bonus mode(s) still active? */
252 if (g
.b
.t
&1<<BONUS_WRAP
&& g
.b
.w
< time(NULL
)) {
253 g
.b
.t
&= ~(1<<BONUS_WRAP
);
257 if (respawn
) spawn_item(FOOD
, rand() % NUM_FOODS
, i
);
258 draw_sprites (old_tail
[0], old_tail
[1]);
261 void spawn_item (int type
, int value
, struct item
* p_item
) {
263 char occupied
[g
.w
][g
.h
]; int snake_len
= 0;
264 memset(*occupied
, 0, g
.w
*g
.h
);
268 if (snake_len
>= g
.w
*g
.h
-1) siglongjmp(game_over
, GAME_WON
);
269 /* loop through snake to check if we aren't on it */
270 if (occupied
[row
][col
]) goto try_again
; /* shortcut */
271 for (struct snake
* s
= g
.s
; s
; s
= s
->next
)
272 if (s
->r
== row
&& s
->c
== col
) {
273 occupied
[s
->r
][s
->c
] = 1; snake_len
++;
277 /* if we got a item buffer reuse it, otherwise create a new one: */
278 struct item
* new_item
;
279 if (p_item
) new_item
= p_item
;
280 else new_item
= malloc (sizeof(struct item
));
286 new_item
->s
= time(0);
287 if (g
.i
) g
.i
->prev
= new_item
;
288 new_item
->next
= g
.i
;
289 new_item
->prev
= NULL
;
294 void consume_item (struct item
* i
) {
314 snake_append(&g
.s
, -1, -1);
315 break; /* will be reused as the head before it is drawn */
319 for (int i
= 5; i
&& g
.s
->next
->next
; i
--) {
320 struct snake
* p
= g
.s
;
321 while (p
->next
->next
) p
= p
->next
;
328 for (int i
= 5; i
; i
--) snake_append(&g
.s
, -1, -1);
339 g
.b
.w
= time(NULL
)+30;
340 g
.b
.t
|= 1<<BONUS_WRAP
;
344 g
.b
.n
= time(NULL
) + BONUS_INTERVAL
; /*next bonus in x seconds*/
348 if (i
->next
) i
->next
->prev
= i
->prev
;
349 if (i
->prev
) i
->prev
->next
= i
->next
;
352 /* snake speedup every 100 points: */
353 if (g
.p
/SPEEDUP_AFTER
- old_score
/SPEEDUP_AFTER
) g
.v
++, timer_setup(1);
356 void spawn_bonus(void) {
357 for (struct item
* i
= g
.i
; i
; i
= i
->next
)
358 if (i
->t
== BONUS
) { /* bonus already there */
359 if (((i
->s
+BONUS_DURATION
)-time(NULL
)) < 0) {
360 remove_bonus(i
); /* remove if over lifetime */
364 if (g
.b
.n
< time(NULL
)) { /* time to spawn item: */
365 spawn_item(BONUS
, rand() % NUM_BONI
, NULL
);
366 g
.b
.n
= time(NULL
) + BONUS_INTERVAL
+ BONUS_DURATION
;
370 void show_playfield (void) {
375 printm (g
.w
, BORDER(T
,C
));
376 printf ("%s\n", BORDER(T
,R
));
379 for (int row
= 0; row
< g
.h
; row
++)
380 printf ("%s%*s%s\n", BORDER(C
,L
), CW
*g
.w
, "", BORDER(C
,R
));
384 printm (g
.w
, BORDER(B
,C
));
387 draw_sprites (-1,-1);
390 void draw_sprites (int erase_r
, int erase_c
) {
391 /* erase old tail, if any */
392 if (erase_r
>= 0 && erase_c
>= 0) {
393 move_ph (erase_r
+LINE_OFFSET
, erase_c
*CW
+COL_OFFSET
);
398 struct snake
* last
= NULL
;
400 for (struct snake
* s
= g
.s
; s
; s
= s
->next
) {
401 if (s
->r
< 0 || s
->c
< 0) continue; /*can't draw outside term.*/
402 move_ph (s
->r
+LINE_OFFSET
, s
->c
*CW
+COL_OFFSET
);
404 int predecessor
= (last
==NULL
)?NONE
:
405 (last
->r
< s
->r
) ? NORTH
:
406 (last
->r
> s
->r
) ? SOUTH
:
407 (last
->c
> s
->c
) ? EAST
:
408 (last
->c
< s
->c
) ? WEST
:NONE
;
409 int successor
= (s
->next
== NULL
)?NONE
:
410 (s
->next
->r
< s
->r
) ? NORTH
:
411 (s
->next
->r
> s
->r
) ? SOUTH
:
412 (s
->next
->c
> s
->c
) ? EAST
:
413 (s
->next
->c
< s
->c
) ? WEST
:NONE
;
415 printf ("\033[%sm", op
.sch
->color
[color
]);
416 print (op
.sch
->snake
[predecessor
][successor
]);
422 /* print item queue */
423 for (struct item
* i
= g
.i
; i
; i
= i
->next
) {
424 move_ph (i
->r
+LINE_OFFSET
, i
->c
*CW
+COL_OFFSET
);
425 if (i
->t
== FOOD
) print(op
.sch
->food
[i
->v
]);
426 else if (i
->t
== BONUS
) {
427 if (i
->s
+ BONUS_DURATION
-BONUS_WARN
< time(NULL
))
428 printf("\033[5m%s\033[25m", op
.sch
->boni
[i
->v
]);
429 else print(op
.sch
->boni
[i
->v
]);
434 int score_width
= g
.p
> 9999?6:4;
435 move_ph (0, (g
.w
*CW
-score_width
)/2-COL_OFFSET
);
436 printf ("%s %0*d %s", BORDER(S
,L
), score_width
, g
.p
, BORDER(S
,R
));
439 void pause_game (void) {
440 time_t pause_start
= time(NULL
);
444 move_ph (g
.h
/2+LINE_OFFSET
, g
.w
*CW
/2);
445 printf ("\033[5;7m PAUSE \033[0m"); /* blinking reverse text */
446 if (getchar() == 'q')
447 siglongjmp(game_over
, GAME_EXIT
);
449 /* update all timers, so bonus items don't get out of sync: */
450 pause_diff
= time(NULL
) - pause_start
;
452 for (struct item
* i
= g
.i
; i
; i
= i
->next
)
459 #define MOVE_POPUP(WIDTH, LINE) \
460 move_ph(g.h/2+LINE_OFFSET-1+LINE,(g.w*DW-WIDTH)/2)
461 //TODO: macro does not correctly centre in DEC mode
462 int end_screen(char* message
) {
463 int msg_w
= strlen(message
);
464 MOVE_POPUP(msg_w
, -1);
466 printm ((msg_w
+2)/DW
, BORDER(T
,C
));
469 MOVE_POPUP(msg_w
, 0);
470 printf("%s %s %s", BORDER(C
,L
), message
, BORDER(C
,R
));
471 MOVE_POPUP(msg_w
, 1);
472 //TODO: requires shifting into ASCII/multilingual charset in DEC mode -- put graphics into upper/right charset?
473 printf("%s `r' restart%*s%s", BORDER(C
,L
), msg_w
-10, "", BORDER(C
,R
));
474 MOVE_POPUP(msg_w
, 2);
475 printf("%s `q' quit%*s%s", BORDER(C
,L
), msg_w
-7, "", BORDER(C
,R
));
477 MOVE_POPUP(msg_w
, 3);
479 printm ((msg_w
+2)/DW
, BORDER(B
,C
));
486 void snake_append (struct snake
** s
, int row
, int col
) {
487 struct snake
* new = malloc (sizeof(struct snake
));
493 struct snake
* p
= *s
;
494 while (p
->next
) p
= p
->next
;
501 void remove_bonus (struct item
* i
) {
502 if (i
->next
) i
->next
->prev
= i
->prev
;
503 if (i
->prev
) i
->prev
->next
= i
->next
;
506 draw_sprites (i
->r
, i
->c
); /* overwrite sprite */
511 #define free_ll(head) do{ \
524 int direction
= WEST
;
531 for (int i
= 0; i
< op
.l
; i
++) {
533 case NORTH
: r
--; if(r
<= min_r
){direction
=EAST
; min_r
++;}break;
534 case EAST
: c
++; if(c
>= max_c
){direction
=SOUTH
;max_c
--;}break;
535 case SOUTH
: r
++; if(r
>= max_r
){direction
=WEST
; max_r
--;}break;
536 case WEST
: c
--; if(c
<= min_c
){direction
=NORTH
;min_c
++;}break;
539 snake_append(&g
.s
, r
, c
);
555 int getctrlseq (void) {
558 while ((c
= getchar()) != EOF
) {
562 case '\033': state
=ESC_SENT
; break;
568 case '[': state
=CSI_SENT
; break;
569 default: return CTRSEQ_INVALID
;
574 case 'A': return CTRSEQ_CURSOR_UP
;
575 case 'B': return CTRSEQ_CURSOR_DOWN
;
576 case 'C': return CTRSEQ_CURSOR_RIGHT
;
577 case 'D': return CTRSEQ_CURSOR_LEFT
;
578 default: return CTRSEQ_INVALID
;
582 return CTRSEQ_INVALID
;
588 void append_movement (int dir
) {
589 if (g
.k
.n
> 15) return; /* no space in buffer */
590 if (g
.k
.n
&& g
.k
.c
[(16+g
.k
.h
-1)%16] == dir
)
591 return; /* don't add the same direction twice */
595 g
.k
.h
= (g
.k
.h
+1) % 16;
598 void move_ph (int line
, int col
) {
599 /* move printhead to zero-indexed position */
600 printf ("\033[%d;%dH", line
+1, col
+1);
603 void clamp_fieldsize (void) {
604 /* clamp field size to terminal size and mouse maximum: */
606 ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &w
);
608 if (g
.w
< 10) g
.w
= 10;
609 if (g
.h
< 10) g
.h
= 10;
611 if (COL_OFFSET
+ g
.w
*CW
+ COL_OFFSET
> w
.ws_col
)
612 g
.w
= (w
.ws_col
- 2*COL_OFFSET
) / DW
;
613 if (LINE_OFFSET
+ g
.h
+ LINES_AFTER
> w
.ws_row
)
614 g
.h
= w
.ws_row
- (LINE_OFFSET
+LINES_AFTER
);
617 void timer_setup (int enable
) {
618 static struct itimerval tbuf
;
619 tbuf
.it_interval
.tv_sec
= 0;
620 tbuf
.it_interval
.tv_usec
= (1000000/g
.v
)-1; /*WARN: 1 <= g.v <= 999999*/
623 tbuf
.it_value
.tv_sec
= tbuf
.it_interval
.tv_sec
;
624 tbuf
.it_value
.tv_usec
= tbuf
.it_interval
.tv_usec
;
626 tbuf
.it_value
.tv_sec
= 0;
627 tbuf
.it_value
.tv_usec
= 0;
630 if ( setitimer(ITIMER_REAL
, &tbuf
, NULL
) == -1 ) {
637 void signal_setup (void) {
638 struct sigaction saction
;
640 saction
.sa_handler
= signal_handler
;
641 sigemptyset(&saction
.sa_mask
);
642 saction
.sa_flags
= 0;
643 if (sigaction(SIGALRM
, &saction
, NULL
) < 0 ) {
648 if (sigaction(SIGINT
, &saction
, NULL
) < 0 ) {
653 if (sigaction(SIGCONT
, &saction
, NULL
) < 0 ) {
659 void signal_handler (int signum
) {
673 void screen_setup (int enable
) {
676 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
677 printf ("\033[H\033[J"); /* reset cursor, clear screen */
678 printf ("\033[?25l"); /* hide cursor */
680 printf ("\033[?25h"); /* show cursor */
681 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
686 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
687 void raw_mode(int enable
) {
688 static struct termios saved_term_mode
;
689 struct termios raw_term_mode
;
692 tcgetattr(STDIN_FILENO
, &saved_term_mode
);
693 raw_term_mode
= saved_term_mode
;
694 raw_term_mode
.c_lflag
&= ~(ICANON
| ECHO
);
695 raw_term_mode
.c_cc
[VMIN
] = 1 ;
696 raw_term_mode
.c_cc
[VTIME
] = 0;
697 tcsetattr(STDIN_FILENO
, TCSAFLUSH
, &raw_term_mode
);
699 tcsetattr(STDIN_FILENO
, TCSAFLUSH
, &saved_term_mode
);