]>
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
51 #define SPEEDUP_AFTER 100 /* increment speed every n points */
54 int w
; /* field width */
55 int h
; /* field height */
56 int d
; /* direction the snake is looking */
57 int t
; /* time of game start */
59 float v
; /* velocity in moves per second */
60 struct snake
* s
; /* snek */
61 struct item
* i
; /* items (food, boni) */
63 int h
; /* write head */
64 int n
; /* number of elements */
66 } k
; /* ring buffer for direction events */
70 int l
; /* initial snake length */
71 int s
; /* initial snake speed */
77 int main (int argc
, char** argv
) {
79 g
.w
= 30; //two-char-width
86 opterr
= 0; /* don't print message on unrecognized option */
87 while ((optget
= getopt (argc
, argv
, "+s:l:dh")) != -1) {
92 fprintf (stderr
, "speed must be >= 1\n");
98 if (op
.s
< 2 || op
.s
> g
.w
*g
.h
-1) {
99 fprintf (stderr
, "length must be >= 2 and < W*H\n");
103 case 'd': op
.sch
= &vt220_charset
; break;
106 fprintf (stderr
, SHORTHELP LONGHELP
, argv
[0]);
107 return !(optget
=='h');
109 } if (optind
< argc
) { /* parse Fieldspec */
110 int n
= sscanf (argv
[optind
], "%dx%d", &g
.w
, &g
.h
);
113 fprintf(stderr
,"FIELDSIZE is WxH (width 'x' height)\n");
125 char* end_screen_msg
= "";
127 switch (sigsetjmp(game_over
, 1)) {
132 end_screen_msg
= " GAME OVER ";
135 end_screen_msg
= "CONGRATULATIONS!";
140 for (;;) switch (end_screen(end_screen_msg
)) {
141 case 'r': goto restart
;
168 spawn_item(FOOD
, rand() % NUM_FOODS
, NULL
); //TODO: shape distribution, so bigger values get selected less
171 switch (getctrlseq()) {
172 case '#': spawn_item(BONUS
, BONUS_SNIP
, NULL
);
173 case CTRSEQ_CURSOR_LEFT
: case 'h':append_movement(WEST
); break;
174 case CTRSEQ_CURSOR_DOWN
: case 'j':append_movement(SOUTH
); break;
175 case CTRSEQ_CURSOR_UP
: case 'k':append_movement(NORTH
); break;
176 case CTRSEQ_CURSOR_RIGHT
:case 'l':append_movement(EAST
); break;
179 move_ph (g
.h
/2+LINE_OFFSET
, g
.w
*CW
/2);
180 printf ("\033[5mPAUSE\033[0m"); /* blinking text */
181 if (getchar() == 'q') exit(0);
185 case 'r': siglongjmp(game_over
, GAME_START
);
186 case 'q': siglongjmp(game_over
, GAME_EXIT
);
191 case 0x02: /* STX; gets sent when returning from SIGALRM */
198 #define pop_dir() (g.k.n? g.k.c[(16+g.k.h-g.k.n--)%16] : NONE)
199 void snake_advance (void) {
201 struct item
* i
; /*temporary item (defined here to respawn at the end) */
202 int new_dir
= pop_dir();
203 /* switch direction if new one is in the buffer and it won't kill us: */
204 if (new_dir
&& g
.d
!= OPPOSITE(new_dir
)) g
.d
= new_dir
;
206 int new_row
= g
.s
->r
+(g
.d
==SOUTH
) -(g
.d
==NORTH
);
207 int new_col
= g
.s
->c
+(g
.d
==EAST
) -(g
.d
==WEST
);
209 /* detect food hit and spawn a new food */
210 for (i
= g
.i
; i
; i
= i
->next
) {
211 if (i
->r
== new_row
&& i
->c
== new_col
) {
212 respawn
= (i
->t
== FOOD
); /* only respawn when we ate a FOOD; must respawn after advancing head */
218 if (new_row
>= g
.h
|| new_col
>= g
.w
|| new_row
< 0 || new_col
< 0)
219 siglongjmp(game_over
, GAME_OVER
);
221 struct snake
* new_head
;
222 struct snake
* new_tail
; /* former second-to-last element */
223 for (new_tail
= g
.s
; new_tail
->next
->next
; new_tail
= new_tail
->next
)
224 /*use the opportunity of looping to check if we eat ourselves:*/
225 if(new_tail
->next
->r
== new_row
&& new_tail
->next
->c
== new_col
)
226 siglongjmp(game_over
, GAME_OVER
);
227 int old_tail
[2] = {new_tail
->next
->r
, new_tail
->next
->c
};/*gets erased*/
228 new_head
= new_tail
->next
; /* reuse element instead of malloc() */
229 new_tail
->next
= NULL
;
231 new_head
->r
= new_row
;
232 new_head
->c
= new_col
;
233 new_head
->next
= g
.s
;
237 if (respawn
) spawn_item(FOOD
, rand() % NUM_FOODS
, i
);
238 draw_sprites (old_tail
[0], old_tail
[1]);
241 void spawn_item (int type
, int value
, struct item
* p_item
) {
243 char occupied
[g
.w
][g
.h
]; int snake_len
= 0;
244 memset(*occupied
, 0, g
.w
*g
.h
);
248 if (snake_len
>= g
.w
*g
.h
-1) siglongjmp(game_over
, GAME_WON
);
249 /* loop through snake to check if we aren't on it */
250 if (occupied
[row
][col
]) goto try_again
; /* shortcut */
251 for (struct snake
* s
= g
.s
; s
; s
= s
->next
)
252 if (s
->r
== row
&& s
->c
== col
) {
253 occupied
[s
->r
][s
->c
] = 1; snake_len
++;
257 /* if we got a item buffer reuse it, otherwise create a new one: */
258 struct item
* new_item
;
259 if (p_item
) new_item
= p_item
;
260 else new_item
= malloc (sizeof(struct item
));
266 new_item
->s
= time(0);
267 if (g
.i
) g
.i
->prev
= new_item
;
268 new_item
->next
= g
.i
;
269 new_item
->prev
= NULL
;
274 void consume_item (struct item
* i
) {
280 case FOOD_5
: g
.p
+= 5; break;
281 case FOOD_10
: g
.p
+= 10; break;
282 case FOOD_20
: g
.p
+= 20; break;
284 snake_append(&g
.s
, -1, -1);
285 break; /* will be reused as the head before it is drawn */
289 for (int i
= 10; i
&& g
.s
->next
->next
; i
--) { /* must have at least 2 elements, otherwise segfault during snake drawing */
290 struct snake
* old_head
= g
.s
;
301 if (i
->next
) i
->next
->prev
= i
->prev
;
302 if (i
->prev
) i
->prev
->next
= i
->next
;
305 /* snake speedup every 100 points: */
306 if (g
.p
/SPEEDUP_AFTER
- old_score
/SPEEDUP_AFTER
) g
.v
++;
309 void show_playfield (void) {
314 printm (g
.w
, BORDER(T
,C
));
315 printf ("%s\n", BORDER(T
,R
));
318 for (int row
= 0; row
< g
.h
; row
++)
319 printf ("%s%*s%s\n", BORDER(C
,L
), CW
*g
.w
, "", BORDER(C
,R
));
323 printm (g
.w
, BORDER(B
,C
));
329 void draw_sprites (int erase_r
, int erase_c
) {
330 /* erase old tail, if any */
331 if (erase_r
>= 0 && erase_c
>= 0) {
332 move_ph (erase_r
+LINE_OFFSET
, erase_c
*CW
+COL_OFFSET
);
337 struct snake
* last
= NULL
;
339 for (struct snake
* s
= g
.s
; s
; s
= s
->next
) {
340 if (s
->r
< 0 || s
->c
< 0) continue; /*can't draw outside term.*/
341 move_ph (s
->r
+LINE_OFFSET
, s
->c
*CW
+COL_OFFSET
);
343 int predecessor
= (last
==NULL
)?NONE
:
344 (last
->r
< s
->r
) ? NORTH
:
345 (last
->r
> s
->r
) ? SOUTH
:
346 (last
->c
> s
->c
) ? EAST
:
347 (last
->c
< s
->c
) ? WEST
:NONE
;
348 int successor
= (s
->next
== NULL
)?NONE
:
349 (s
->next
->r
< s
->r
) ? NORTH
:
350 (s
->next
->r
> s
->r
) ? SOUTH
:
351 (s
->next
->c
> s
->c
) ? EAST
:
352 (s
->next
->c
< s
->c
) ? WEST
:NONE
;
354 printf ("\033[%sm", op
.sch
->color
[color
]);
355 print (op
.sch
->snake
[predecessor
][successor
]);
361 /* print item queue */
362 for (struct item
* i
= g
.i
; i
; i
= i
->next
) {
363 move_ph (i
->r
+LINE_OFFSET
, i
->c
*CW
+COL_OFFSET
);
364 if (i
->t
== FOOD
) print(op
.sch
->food
[i
->v
]);
365 else if (i
->t
== BONUS
) print(op
.sch
->boni
[i
->v
]);
369 int score_width
= g
.p
> 9999?6:4;
370 move_ph (0, (g
.w
*CW
-score_width
)/2-COL_OFFSET
);
371 printf ("%s %0*d %s", BORDER(S
,L
), score_width
, g
.p
, BORDER(S
,R
));
374 #define MOVE_POPUP(WIDTH, LINE) \
375 move_ph(g.h/2+LINE_OFFSET-1+LINE,(g.w*op.sch->display_width-WIDTH)/2)
376 int end_screen(char* message
) {
377 int msg_w
= strlen(message
);
378 MOVE_POPUP(msg_w
, -1);
380 printm ((msg_w
+2)/op
.sch
->display_width
, BORDER(T
,C
));
383 MOVE_POPUP(msg_w
, 0);
384 printf("%s %s %s", BORDER(C
,L
), message
, BORDER(C
,R
));
385 MOVE_POPUP(msg_w
, 1);
386 printf("%s `r' restart%*s%s", BORDER(C
,L
), msg_w
-10, "", BORDER(C
,R
));
387 MOVE_POPUP(msg_w
, 2);
388 printf("%s `q' quit%*s%s", BORDER(C
,L
), msg_w
-7, "", BORDER(C
,R
));
390 MOVE_POPUP(msg_w
, 3);
392 printm ((msg_w
+2)/op
.sch
->display_width
, BORDER(B
,C
));
399 void snake_append (struct snake
** s
, int row
, int col
) {
400 struct snake
* new = malloc (sizeof(struct snake
));
406 struct snake
* p
= *s
;
407 while (p
->next
) p
= p
->next
;
414 #define free_ll(head) do{ \
427 int direction
= WEST
;
434 for (int i
= 0; i
< op
.l
; i
++) {
436 case NORTH
: r
--; if(r
<= min_r
){direction
=EAST
; min_r
++;}break;
437 case EAST
: c
++; if(c
>= max_c
){direction
=SOUTH
;max_c
--;}break;
438 case SOUTH
: r
++; if(r
>= max_r
){direction
=WEST
; max_r
--;}break;
439 case WEST
: c
--; if(c
<= min_c
){direction
=NORTH
;min_c
++;}break;
442 snake_append(&g
.s
, r
, c
);
458 int getctrlseq (void) {
461 while ((c
= getchar()) != EOF
) {
465 case '\033': state
=ESC_SENT
; break;
471 case '[': state
=CSI_SENT
; break;
472 default: return CTRSEQ_INVALID
;
477 case 'A': return CTRSEQ_CURSOR_UP
;
478 case 'B': return CTRSEQ_CURSOR_DOWN
;
479 case 'C': return CTRSEQ_CURSOR_RIGHT
;
480 case 'D': return CTRSEQ_CURSOR_LEFT
;
481 default: return CTRSEQ_INVALID
;
485 return CTRSEQ_INVALID
;
491 void append_movement (int dir
) {
492 if (g
.k
.n
> 15) return; /* no space in buffer */
493 if (g
.k
.n
&& g
.k
.c
[(16+g
.k
.h
-1)%16] == dir
)
494 return; /* don't add the same direction twice */
498 g
.k
.h
= ++g
.k
.h
% 16;
501 void move_ph (int line
, int col
) {
502 /* move printhead to zero-indexed position */
503 printf ("\033[%d;%dH", line
+1, col
+1);
506 void clamp_fieldsize (void) {
507 /* clamp field size to terminal size and mouse maximum: */
509 ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &w
);
511 if (g
.w
< 10) g
.w
= 10;
512 if (g
.h
< 10) g
.h
= 10;
514 if (COL_OFFSET
+ g
.w
*CW
+ COL_OFFSET
> w
.ws_col
)
515 g
.w
= (w
.ws_col
- 2*COL_OFFSET
) / op
.sch
->display_width
;
516 if (LINE_OFFSET
+ g
.h
+ LINES_AFTER
> w
.ws_row
)
517 g
.h
= w
.ws_row
- (LINE_OFFSET
+LINES_AFTER
);
520 void timer_setup (int enable
) {
521 static struct itimerval tbuf
;
522 tbuf
.it_interval
.tv_sec
= 0;
523 tbuf
.it_interval
.tv_usec
= (1000000/g
.v
)-1; /*WARN: 1 <= g.v <= 999999*/
526 tbuf
.it_value
.tv_sec
= tbuf
.it_interval
.tv_sec
;
527 tbuf
.it_value
.tv_usec
= tbuf
.it_interval
.tv_usec
;
529 tbuf
.it_value
.tv_sec
= 0;
530 tbuf
.it_value
.tv_usec
= 0;
533 if ( setitimer(ITIMER_REAL
, &tbuf
, NULL
) == -1 ) {
540 void signal_setup (void) {
541 struct sigaction saction
;
543 saction
.sa_handler
= signal_handler
;
544 sigemptyset(&saction
.sa_mask
);
545 saction
.sa_flags
= 0;
546 if (sigaction(SIGALRM
, &saction
, NULL
) < 0 ) {
551 if (sigaction(SIGINT
, &saction
, NULL
) < 0 ) {
556 if (sigaction(SIGCONT
, &saction
, NULL
) < 0 ) {
562 void signal_handler (int signum
) {
575 void screen_setup (int enable
) {
578 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
579 printf ("\033[H\033[J"); /* reset cursor, clear screen */
580 printf ("\033[?25l"); /* hide cursor */
581 print (op
.sch
->init_seq
); /* swich charset, if necessary */
583 print (op
.sch
->reset_seq
); /* reset charset, if necessary */
584 printf ("\033[?25h"); /* show cursor */
585 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
590 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
591 void raw_mode(int enable
) {
592 static struct termios saved_term_mode
;
593 struct termios raw_term_mode
;
596 tcgetattr(STDIN_FILENO
, &saved_term_mode
);
597 raw_term_mode
= saved_term_mode
;
598 raw_term_mode
.c_lflag
&= ~(ICANON
| ECHO
);
599 raw_term_mode
.c_cc
[VMIN
] = 1 ;
600 raw_term_mode
.c_cc
[VTIME
] = 0;
601 tcsetattr(STDIN_FILENO
, TCSAFLUSH
, &raw_term_mode
);
603 tcsetattr(STDIN_FILENO
, TCSAFLUSH
, &saved_term_mode
);