]>
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 */
56 #define BONUS_STOP_NUM 5 /* how many steps the time freezes */
59 int w
; /* field width */
60 int h
; /* field height */
61 int d
; /* direction the snake is looking */
63 float v
; /* velocity in moves per second */
64 time_t t
; /* time of game start */
65 struct snake
* s
; /* snek */
66 struct item
* i
; /* items (food, boni) */
68 int t
; /* bonus type (bitmask based on enum bonus_value) */
69 int s
; /* steps left of time freeze bonus */
70 time_t n
; /* time of next bonus item spawn */
71 time_t w
; /* time of wall-wrap end */
72 } b
; /* bonus-related values */
74 int h
; /* write head */
75 int n
; /* number of elements */
77 } k
; /* ring buffer for direction events */
81 int l
; /* initial snake length */
82 int s
; /* initial snake speed */
88 int main (int argc
, char** argv
) {
97 opterr
= 0; /* don't print message on unrecognized option */
98 while ((optget
= getopt (argc
, argv
, "+s:l:dh")) != -1) {
103 fprintf (stderr
, "speed must be >= 1\n");
109 if (op
.s
< 2 || op
.s
> g
.w
*g
.h
-1) {
110 fprintf (stderr
, "length must be >= 2 and < W*H\n");
116 fprintf (stderr
, SHORTHELP LONGHELP
, argv
[0]);
117 return !(optget
=='h');
119 } if (optind
< argc
) { /* parse Fieldspec */
120 int n
= sscanf (argv
[optind
], "%dx%d", &g
.w
, &g
.h
);
123 fprintf(stderr
,"FIELDSIZE is WxH (width 'x' height)\n");
135 char* end_screen_msg
= "";
137 switch (sigsetjmp(game_over
, 1)) {
141 break; /* function doesn't return, but `-Wextra' complains */
143 end_screen_msg
= " GAME OVER ";
146 end_screen_msg
= "CONGRATULATIONS!";
151 for (;;) switch (end_screen(end_screen_msg
)) {
152 case 'r': goto restart
;
178 g
.b
.n
= time(NULL
) + BONUS_INTERVAL
;
182 spawn_item(FOOD
, rand() % NUM_FOODS
, NULL
);
185 switch (getctrlseq()) {
186 case 'h': case CTRSEQ_CURSOR_LEFT
: append_movement(WEST
); break;
187 case 'j': case CTRSEQ_CURSOR_DOWN
: append_movement(SOUTH
);break;
188 case 'k': case CTRSEQ_CURSOR_UP
: append_movement(NORTH
);break;
189 case 'l': case CTRSEQ_CURSOR_RIGHT
:append_movement(EAST
); break;
190 case 'p': pause_game(); break;
191 case 'r': siglongjmp(game_over
, GAME_START
);
192 case 'q': siglongjmp(game_over
, GAME_EXIT
);
194 spawn_item(BONUS
, BONUS_STOP
, NULL
);
200 case 0x02: /* STX; gets sent when returning from SIGALRM */
204 if (g
.b
.s
) { /* highjack keyboard function for time freeze */
206 if (!--g
.b
.s
) timer_setup(1);/*turn back on afterwards*/
212 #define pop_dir() (g.k.n? g.k.c[(16+g.k.h-g.k.n--)%16] : NONE)
213 void snake_advance (void) {
215 struct item
* i
; /*temporary item (defined here to respawn at the end) */
216 int new_dir
= pop_dir();
217 /* switch direction if new one is in the buffer and it won't kill us: */
218 if (new_dir
&& g
.d
!= OPPOSITE(new_dir
)) g
.d
= new_dir
;
220 int new_row
= g
.s
->r
+(g
.d
==SOUTH
) -(g
.d
==NORTH
);
221 int new_col
= g
.s
->c
+(g
.d
==EAST
) -(g
.d
==WEST
);
223 /* detect food hit and spawn a new food */
224 for (i
= g
.i
; i
; i
= i
->next
) {
225 if (i
->r
== new_row
&& i
->c
== new_col
) {
229 case FOOD
: respawn
= 1; break;
230 case BONUS
: remove_bonus(i
); break;
236 if (g
.b
.t
& 1<<BONUS_WRAP
) {
237 if (new_row
>= g
.h
) new_row
= 0;
238 if (new_col
>= g
.w
) new_col
= 0;
239 if (new_row
< 0) new_row
= g
.h
-1;
240 if (new_col
< 0) new_col
= g
.w
-1;
242 if (new_row
>= g
.h
|| new_col
>= g
.w
|| new_row
< 0 || new_col
< 0)
243 siglongjmp(game_over
, GAME_OVER
);
246 struct snake
* new_head
;
247 struct snake
* new_tail
; /* former second-to-last element */
248 for (new_tail
= g
.s
; new_tail
->next
->next
; new_tail
= new_tail
->next
)
249 /*use the opportunity of looping to check if we eat ourselves:*/
250 if(new_tail
->next
->r
== new_row
&& new_tail
->next
->c
== new_col
)
251 siglongjmp(game_over
, GAME_OVER
);
252 int old_tail
[2] = {new_tail
->next
->r
, new_tail
->next
->c
};/*gets erased*/
253 new_head
= new_tail
->next
; /* reuse element instead of malloc() */
254 new_tail
->next
= NULL
;
256 new_head
->r
= new_row
;
257 new_head
->c
= new_col
;
258 new_head
->next
= g
.s
;
262 /* bonus mode(s) still active? */
263 if (g
.b
.t
&1<<BONUS_WRAP
&& g
.b
.w
< time(NULL
)) {
264 g
.b
.t
&= ~(1<<BONUS_WRAP
);
268 if (respawn
) spawn_item(FOOD
, rand() % NUM_FOODS
, i
);
269 draw_sprites (old_tail
[0], old_tail
[1]);
272 void spawn_item (int type
, int value
, struct item
* p_item
) {
274 char occupied
[g
.w
][g
.h
]; int snake_len
= 0;
275 memset(*occupied
, 0, g
.w
*g
.h
);
279 if (snake_len
>= g
.w
*g
.h
-1) siglongjmp(game_over
, GAME_WON
);
280 /* loop through snake to check if we aren't on it */
281 if (occupied
[row
][col
]) goto try_again
; /* shortcut */
282 for (struct snake
* s
= g
.s
; s
; s
= s
->next
)
283 if (s
->r
== row
&& s
->c
== col
) {
284 occupied
[s
->r
][s
->c
] = 1; snake_len
++;
288 /* if we got a item buffer reuse it, otherwise create a new one: */
289 struct item
* new_item
;
290 if (p_item
) new_item
= p_item
;
291 else new_item
= malloc (sizeof(struct item
));
297 new_item
->s
= time(0);
298 if (g
.i
) g
.i
->prev
= new_item
;
299 new_item
->next
= g
.i
;
300 new_item
->prev
= NULL
;
305 void consume_item (struct item
* i
) {
325 snake_append(&g
.s
, -1, -1);
326 break; /* will be reused as the head before it is drawn */
330 for (int i
= 5; i
&& g
.s
->next
->next
; i
--) {
331 struct snake
* p
= g
.s
;
332 while (p
->next
->next
) p
= p
->next
;
339 for (int i
= 5; i
; i
--) snake_append(&g
.s
, -1, -1);
350 g
.b
.w
= time(NULL
)+30;
351 g
.b
.t
|= 1<<BONUS_WRAP
;
355 g
.b
.s
= BONUS_STOP_NUM
; /* stop the time for 5 steps */
359 g
.b
.n
= time(NULL
) + BONUS_INTERVAL
; /*next bonus in x seconds*/
363 if (i
->next
) i
->next
->prev
= i
->prev
;
364 if (i
->prev
) i
->prev
->next
= i
->next
;
367 /* snake speedup every 100 points: */
368 if (g
.p
/SPEEDUP_AFTER
- old_score
/SPEEDUP_AFTER
) g
.v
++, timer_setup(1);
371 void spawn_bonus(void) {
372 for (struct item
* i
= g
.i
; i
; i
= i
->next
)
373 if (i
->t
== BONUS
) { /* bonus already there */
374 if (((i
->s
+BONUS_DURATION
)-time(NULL
)) < 0) {
375 remove_bonus(i
); /* remove if over lifetime */
379 if (g
.b
.n
< time(NULL
)) { /* time to spawn item: */
380 spawn_item(BONUS
, rand() % NUM_BONI
, NULL
);
381 g
.b
.n
= time(NULL
) + BONUS_INTERVAL
+ BONUS_DURATION
;
385 void show_playfield (void) {
390 printm (g
.w
, BORDER(T
,C
));
391 printf ("%s\n", BORDER(T
,R
));
394 for (int row
= 0; row
< g
.h
; row
++)
395 printf ("%s%*s%s\n", BORDER(C
,L
), CW
*g
.w
, "", BORDER(C
,R
));
399 printm (g
.w
, BORDER(B
,C
));
402 draw_sprites (-1,-1);
405 void draw_sprites (int erase_r
, int erase_c
) {
406 /* erase old tail, if any */
407 if (erase_r
>= 0 && erase_c
>= 0) {
408 move_ph (erase_r
+LINE_OFFSET
, erase_c
*CW
+COL_OFFSET
);
413 struct snake
* last
= NULL
;
415 for (struct snake
* s
= g
.s
; s
; s
= s
->next
) {
416 if (s
->r
< 0 || s
->c
< 0) continue; /*can't draw outside term.*/
417 move_ph (s
->r
+LINE_OFFSET
, s
->c
*CW
+COL_OFFSET
);
419 int predecessor
= (last
==NULL
)?NONE
:
420 (last
->r
< s
->r
) ? NORTH
:
421 (last
->r
> s
->r
) ? SOUTH
:
422 (last
->c
> s
->c
) ? EAST
:
423 (last
->c
< s
->c
) ? WEST
:NONE
;
424 int successor
= (s
->next
== NULL
)?NONE
:
425 (s
->next
->r
< s
->r
) ? NORTH
:
426 (s
->next
->r
> s
->r
) ? SOUTH
:
427 (s
->next
->c
> s
->c
) ? EAST
:
428 (s
->next
->c
< s
->c
) ? WEST
:NONE
;
430 printf ("\033[%sm", op
.sch
->color
[color
]);
431 print (op
.sch
->snake
[predecessor
][successor
]);
437 /* print item queue */
438 for (struct item
* i
= g
.i
; i
; i
= i
->next
) {
439 move_ph (i
->r
+LINE_OFFSET
, i
->c
*CW
+COL_OFFSET
);
440 if (i
->t
== FOOD
) print(op
.sch
->food
[i
->v
]);
441 else if (i
->t
== BONUS
) {
442 if (i
->s
+ BONUS_DURATION
-BONUS_WARN
< time(NULL
))
443 printf("\033[5m%s\033[25m", op
.sch
->boni
[i
->v
]);
444 else print(op
.sch
->boni
[i
->v
]);
449 int score_width
= g
.p
> 9999?6:4;
450 move_ph (0, (g
.w
*CW
-score_width
)/2-COL_OFFSET
);
451 printf ("%s %0*d %s", BORDER(S
,L
), score_width
, g
.p
, BORDER(S
,R
));
454 void pause_game (void) {
455 time_t pause_start
= time(NULL
);
459 move_ph (g
.h
/2+LINE_OFFSET
, g
.w
*CW
/2);
460 printf ("\033[5;7m PAUSE \033[0m"); /* blinking reverse text */
461 if (getchar() == 'q')
462 siglongjmp(game_over
, GAME_EXIT
);
464 /* update all timers, so bonus items don't get out of sync: */
465 pause_diff
= time(NULL
) - pause_start
;
467 for (struct item
* i
= g
.i
; i
; i
= i
->next
)
474 #define MOVE_POPUP(WIDTH, LINE) \
475 move_ph(g.h/2+LINE_OFFSET-1+LINE,(g.w*DW-WIDTH)/2)
476 //TODO: macro does not correctly centre in DEC mode
477 int end_screen(char* message
) {
478 int msg_w
= strlen(message
);
479 MOVE_POPUP(msg_w
, -1);
481 printm ((msg_w
+2)/DW
, BORDER(T
,C
));
484 MOVE_POPUP(msg_w
, 0);
485 printf("%s %s %s", BORDER(C
,L
), message
, BORDER(C
,R
));
486 MOVE_POPUP(msg_w
, 1);
487 //TODO: requires shifting into ASCII/multilingual charset in DEC mode -- put graphics into upper/right charset?
488 printf("%s `r' restart%*s%s", BORDER(C
,L
), msg_w
-10, "", BORDER(C
,R
));
489 MOVE_POPUP(msg_w
, 2);
490 printf("%s `q' quit%*s%s", BORDER(C
,L
), msg_w
-7, "", BORDER(C
,R
));
492 MOVE_POPUP(msg_w
, 3);
494 printm ((msg_w
+2)/DW
, BORDER(B
,C
));
501 void snake_append (struct snake
** s
, int row
, int col
) {
502 struct snake
* new = malloc (sizeof(struct snake
));
508 struct snake
* p
= *s
;
509 while (p
->next
) p
= p
->next
;
516 void remove_bonus (struct item
* i
) {
517 if (i
->next
) i
->next
->prev
= i
->prev
;
518 if (i
->prev
) i
->prev
->next
= i
->next
;
521 draw_sprites (i
->r
, i
->c
); /* overwrite sprite */
526 #define free_ll(head) do{ \
539 int direction
= WEST
;
546 for (int i
= 0; i
< op
.l
; i
++) {
548 case NORTH
: r
--; if(r
<= min_r
){direction
=EAST
; min_r
++;}break;
549 case EAST
: c
++; if(c
>= max_c
){direction
=SOUTH
;max_c
--;}break;
550 case SOUTH
: r
++; if(r
>= max_r
){direction
=WEST
; max_r
--;}break;
551 case WEST
: c
--; if(c
<= min_c
){direction
=NORTH
;min_c
++;}break;
554 snake_append(&g
.s
, r
, c
);
570 int getctrlseq (void) {
573 while ((c
= getchar()) != EOF
) {
577 case '\033': state
=ESC_SENT
; break;
583 case '[': state
=CSI_SENT
; break;
584 default: return CTRSEQ_INVALID
;
589 case 'A': return CTRSEQ_CURSOR_UP
;
590 case 'B': return CTRSEQ_CURSOR_DOWN
;
591 case 'C': return CTRSEQ_CURSOR_RIGHT
;
592 case 'D': return CTRSEQ_CURSOR_LEFT
;
593 default: return CTRSEQ_INVALID
;
597 return CTRSEQ_INVALID
;
603 void append_movement (int dir
) {
604 if (g
.k
.n
> 15) return; /* no space in buffer */
605 if (g
.k
.n
&& g
.k
.c
[(16+g
.k
.h
-1)%16] == dir
)
606 return; /* don't add the same direction twice */
610 g
.k
.h
= (g
.k
.h
+1) % 16;
613 void move_ph (int line
, int col
) {
614 /* move printhead to zero-indexed position */
615 printf ("\033[%d;%dH", line
+1, col
+1);
618 void clamp_fieldsize (void) {
619 /* clamp field size to terminal size and mouse maximum: */
621 ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &w
);
623 if (g
.w
< 10) g
.w
= 10;
624 if (g
.h
< 10) g
.h
= 10;
626 if (COL_OFFSET
+ g
.w
*CW
+ COL_OFFSET
> w
.ws_col
)
627 g
.w
= (w
.ws_col
- 2*COL_OFFSET
) / DW
;
628 if (LINE_OFFSET
+ g
.h
+ LINES_AFTER
> w
.ws_row
)
629 g
.h
= w
.ws_row
- (LINE_OFFSET
+LINES_AFTER
);
632 void timer_setup (int enable
) {
633 static struct itimerval tbuf
;
634 tbuf
.it_interval
.tv_sec
= 0;
635 tbuf
.it_interval
.tv_usec
= (1000000/g
.v
)-1; /*WARN: 1 <= g.v <= 999999*/
638 tbuf
.it_value
.tv_sec
= tbuf
.it_interval
.tv_sec
;
639 tbuf
.it_value
.tv_usec
= tbuf
.it_interval
.tv_usec
;
641 tbuf
.it_value
.tv_sec
= 0;
642 tbuf
.it_value
.tv_usec
= 0;
645 if ( setitimer(ITIMER_REAL
, &tbuf
, NULL
) == -1 ) {
652 void signal_setup (void) {
653 struct sigaction saction
;
655 saction
.sa_handler
= signal_handler
;
656 sigemptyset(&saction
.sa_mask
);
657 saction
.sa_flags
= 0;
658 if (sigaction(SIGALRM
, &saction
, NULL
) < 0 ) {
663 if (sigaction(SIGINT
, &saction
, NULL
) < 0 ) {
668 if (sigaction(SIGCONT
, &saction
, NULL
) < 0 ) {
674 void signal_handler (int signum
) {
688 void screen_setup (int enable
) {
691 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
692 printf ("\033[H\033[J"); /* reset cursor, clear screen */
693 printf ("\033[?25l"); /* hide cursor */
695 printf ("\033[?25h"); /* show cursor */
696 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
701 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
702 void raw_mode(int enable
) {
703 static struct termios saved_term_mode
;
704 struct termios raw_term_mode
;
707 tcgetattr(STDIN_FILENO
, &saved_term_mode
);
708 raw_term_mode
= saved_term_mode
;
709 raw_term_mode
.c_lflag
&= ~(ICANON
| ECHO
);
710 raw_term_mode
.c_cc
[VMIN
] = 1 ;
711 raw_term_mode
.c_cc
[VTIME
] = 0;
712 tcsetattr(STDIN_FILENO
, TCSAFLUSH
, &raw_term_mode
);
714 tcsetattr(STDIN_FILENO
, TCSAFLUSH
, &saved_term_mode
);