]>
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
52 int w
; /* field width */
53 int h
; /* field height */
54 int d
; /* direction the snake is looking */
55 int t
; /* time of game start */
57 float v
; /* velocity in moves per second */
58 struct snake
* s
; /* snek */
59 struct item
* i
; /* items (food, boni) */
61 int h
; /* write head */
62 int n
; /* number of elements */
64 } k
; /* ring buffer for direction events */
68 int l
; /* initial snake length */
69 int s
; /* initial snake speed */
75 int main (int argc
, char** argv
) {
77 g
.w
= 30; //two-char-width
84 opterr
= 0; /* don't print message on unrecognized option */
85 while ((optget
= getopt (argc
, argv
, "+s:l:dh")) != -1) {
90 fprintf (stderr
, "speed must be >= 1\n");
96 if (op
.s
< 2 || op
.s
> g
.w
*g
.h
-1) {
97 fprintf (stderr
, "length must be >= 2 and < W*H\n");
101 case 'd': op
.sch
= &vt220_charset
; break;
104 fprintf (stderr
, SHORTHELP LONGHELP
, argv
[0]);
105 return !(optget
=='h');
107 } if (optind
< argc
) { /* parse Fieldspec */
108 int n
= sscanf (argv
[optind
], "%dx%d", &g
.w
, &g
.h
);
111 fprintf(stderr
,"FIELDSIZE is WxH (width 'x' height)\n");
123 char* end_screen_msg
= "";
125 switch (sigsetjmp(game_over
, 1)) {
130 end_screen_msg
= " GAME OVER ";
133 end_screen_msg
= "CONGRATULATIONS!";
138 for (;;) switch (end_screen(end_screen_msg
)) {
139 case 'r': goto restart
;
164 spawn_item(FOOD
, rand() % NUM_FOODS
, NULL
); //TODO: shape distribution, so bigger values get selected less
167 switch (getctrlseq()) {
168 case CTRSEQ_CURSOR_LEFT
: case 'h':append_movement(WEST
); break;
169 case CTRSEQ_CURSOR_DOWN
: case 'j':append_movement(SOUTH
); break;
170 case CTRSEQ_CURSOR_UP
: case 'k':append_movement(NORTH
); break;
171 case CTRSEQ_CURSOR_RIGHT
:case 'l':append_movement(EAST
); break;
174 move_ph (g
.h
/2+LINE_OFFSET
, g
.w
*CW
/2);
175 printf ("\033[5mPAUSE\033[0m"); /* blinking text */
176 if (getchar() == 'q') exit(0);
180 case 'r': siglongjmp(game_over
, GAME_START
);
181 case 'q': siglongjmp(game_over
, GAME_EXIT
);
186 case 0x02: /* STX; gets sent when returning from SIGALRM */
193 #define pop_dir() (g.k.n? g.k.c[(16+g.k.h-g.k.n--)%16] : NONE)
194 void snake_advance (void) {
196 struct item
* i
; /*temporary item (defined here to respawn at the end) */
197 int new_dir
= pop_dir();
198 /* switch direction if new one is in the buffer and it won't kill us: */
199 if (new_dir
&& g
.d
!= OPPOSITE(new_dir
)) g
.d
= new_dir
;
201 int new_row
= g
.s
->r
+(g
.d
==SOUTH
) -(g
.d
==NORTH
);
202 int new_col
= g
.s
->c
+(g
.d
==EAST
) -(g
.d
==WEST
);
204 /* detect food hit and spawn a new food */
205 for (i
= g
.i
; i
; i
= i
->next
) {
206 if (i
->r
== new_row
&& i
->c
== new_col
) {
208 respawn
= 1; /* must respawn after advancing head */
213 if (new_row
>= g
.h
|| new_col
>= g
.w
|| new_row
< 0 || new_col
< 0)
214 siglongjmp(game_over
, GAME_OVER
);
216 struct snake
* new_head
;
217 struct snake
* new_tail
; /* former second-to-last element */
218 for (new_tail
= g
.s
; new_tail
->next
->next
; new_tail
= new_tail
->next
)
219 /*use the opportunity of looping to check if we eat ourselves:*/
220 if(new_tail
->next
->r
== new_row
&& new_tail
->next
->c
== new_col
)
221 siglongjmp(game_over
, GAME_OVER
);
222 int old_tail
[2] = {new_tail
->next
->r
, new_tail
->next
->c
};/*gets erased*/
223 new_head
= new_tail
->next
; /* reuse element instead of malloc() */
224 new_tail
->next
= NULL
;
226 new_head
->r
= new_row
;
227 new_head
->c
= new_col
;
228 new_head
->next
= g
.s
;
232 if (respawn
) spawn_item(FOOD
, rand() % NUM_FOODS
, i
);
233 draw_sprites (old_tail
[0], old_tail
[1]);
236 void spawn_item (int type
, int value
, struct item
* p_item
) {
238 char occupied
[g
.w
][g
.h
]; int snake_len
= 0;
239 memset(*occupied
, 0, g
.w
*g
.h
);
243 if (snake_len
>= g
.w
*g
.h
-1) siglongjmp(game_over
, GAME_WON
);
244 /* loop through snake to check if we aren't on it */
245 if (occupied
[row
][col
]) goto try_again
; /* shortcut */
246 for (struct snake
* s
= g
.s
; s
; s
= s
->next
)
247 if (s
->r
== row
&& s
->c
== col
) {
248 occupied
[s
->r
][s
->c
] = 1; snake_len
++;
252 /* if we got a item buffer reuse it, otherwise create a new one: */
253 struct item
* new_item
;
254 if (p_item
) new_item
= p_item
;
255 else new_item
= malloc (sizeof(struct item
));
261 new_item
->s
= time(0);
262 if (g
.i
) g
.i
->prev
= new_item
;
263 new_item
->next
= g
.i
;
264 new_item
->prev
= NULL
;
269 void consume_item (struct item
* i
) {
273 case FOOD_5
: g
.p
+= 5; break;
274 case FOOD_10
: g
.p
+= 10; break;
275 case FOOD_20
: g
.p
+= 20; break;
277 snake_append(&g
.s
, -1, -1);
278 break; /* will be reused as the head before it is drawn */
284 if (i
->next
) i
->next
->prev
= i
->prev
;
285 if (i
->prev
) i
->prev
->next
= i
->next
;
289 void show_playfield (void) {
294 printm (g
.w
, BORDER(T
,C
));
295 printf ("%s\n", BORDER(T
,R
));
298 for (int row
= 0; row
< g
.h
; row
++)
299 printf ("%s%*s%s\n", BORDER(C
,L
), CW
*g
.w
, "", BORDER(C
,R
));
303 printm (g
.w
, BORDER(B
,C
));
309 void draw_sprites (int erase_r
, int erase_c
) {
311 move_ph (erase_r
+LINE_OFFSET
, erase_c
*CW
+COL_OFFSET
);
315 struct snake
* last
= NULL
;
317 for (struct snake
* s
= g
.s
; s
; s
= s
->next
) {
318 if (s
->r
< 0 || s
->c
< 0) continue; /*can't draw outside term.*/
319 move_ph (s
->r
+LINE_OFFSET
, s
->c
*CW
+COL_OFFSET
);
321 int predecessor
= (last
==NULL
)?NONE
:
322 (last
->r
< s
->r
) ? NORTH
:
323 (last
->r
> s
->r
) ? SOUTH
:
324 (last
->c
> s
->c
) ? EAST
:
325 (last
->c
< s
->c
) ? WEST
:NONE
;
326 int successor
= (s
->next
== NULL
)?NONE
:
327 (s
->next
->r
< s
->r
) ? NORTH
:
328 (s
->next
->r
> s
->r
) ? SOUTH
:
329 (s
->next
->c
> s
->c
) ? EAST
:
330 (s
->next
->c
< s
->c
) ? WEST
:NONE
;
332 printf ("\033[%sm", op
.sch
->color
[color
]);
333 print (op
.sch
->snake
[predecessor
][successor
]);
339 /* print item queue */
340 for (struct item
* i
= g
.i
; i
; i
= i
->next
) {
341 move_ph (i
->r
+LINE_OFFSET
, i
->c
*CW
+COL_OFFSET
);
342 if (i
->t
== FOOD
) print (op
.sch
->item
[i
->v
]);
343 else if (i
->t
==BONUS
) /* TODO: print bonus */;
347 int score_width
= g
.p
> 9999?6:4;
348 move_ph (0, (g
.w
*CW
-score_width
)/2-COL_OFFSET
);
349 printf ("%s %0*d %s", BORDER(S
,L
), score_width
, g
.p
, BORDER(S
,R
));
352 #define MOVE_POPUP(WIDTH, LINE) \
353 move_ph(g.h/2+LINE_OFFSET-1+LINE,(g.w*op.sch->display_width-WIDTH)/2)
354 int end_screen(char* message
) {
355 int msg_w
= strlen(message
);
356 MOVE_POPUP(msg_w
, -1);
358 printm ((msg_w
+2)/op
.sch
->display_width
, BORDER(T
,C
));
361 MOVE_POPUP(msg_w
, 0);
362 printf("%s %s %s", BORDER(C
,L
), message
, BORDER(C
,R
));
363 MOVE_POPUP(msg_w
, 1);
364 printf("%s `r' restart%*s%s", BORDER(C
,L
), msg_w
-10, "", BORDER(C
,R
));
365 MOVE_POPUP(msg_w
, 2);
366 printf("%s `q' quit%*s%s", BORDER(C
,L
), msg_w
-7, "", BORDER(C
,R
));
368 MOVE_POPUP(msg_w
, 3);
370 printm ((msg_w
+2)/op
.sch
->display_width
, BORDER(B
,C
));
377 void snake_append (struct snake
** s
, int row
, int col
) {
378 struct snake
* new = malloc (sizeof(struct snake
));
384 struct snake
* p
= *s
;
385 while (p
->next
) p
= p
->next
;
392 #define free_ll(head) do{ \
405 int direction
= WEST
;
412 for (int i
= 0; i
< op
.l
; i
++) {
414 case NORTH
: r
--; if(r
<= min_r
){direction
=EAST
; min_r
++;}break;
415 case EAST
: c
++; if(c
>= max_c
){direction
=SOUTH
;max_c
--;}break;
416 case SOUTH
: r
++; if(r
>= max_r
){direction
=WEST
; max_r
--;}break;
417 case WEST
: c
--; if(c
<= min_c
){direction
=NORTH
;min_c
++;}break;
420 snake_append(&g
.s
, r
, c
);
436 int getctrlseq (void) {
439 while ((c
= getchar()) != EOF
) {
443 case '\033': state
=ESC_SENT
; break;
449 case '[': state
=CSI_SENT
; break;
450 default: return CTRSEQ_INVALID
;
455 case 'A': return CTRSEQ_CURSOR_UP
;
456 case 'B': return CTRSEQ_CURSOR_DOWN
;
457 case 'C': return CTRSEQ_CURSOR_RIGHT
;
458 case 'D': return CTRSEQ_CURSOR_LEFT
;
459 default: return CTRSEQ_INVALID
;
463 return CTRSEQ_INVALID
;
469 void append_movement (int dir
) {
470 if (g
.k
.n
> 15) return; /* no space in buffer */
471 if (g
.k
.n
&& g
.k
.c
[(16+g
.k
.h
-1)%16] == dir
)
472 return; /* don't add the same direction twice */
476 g
.k
.h
= ++g
.k
.h
% 16;
479 void move_ph (int line
, int col
) {
480 /* move printhead to zero-indexed position */
481 printf ("\033[%d;%dH", line
+1, col
+1);
484 void clamp_fieldsize (void) {
485 /* clamp field size to terminal size and mouse maximum: */
487 ioctl(STDOUT_FILENO
, TIOCGWINSZ
, &w
);
489 if (g
.w
< 10) g
.w
= 10;
490 if (g
.h
< 10) g
.h
= 10;
492 if (COL_OFFSET
+ g
.w
*CW
+ COL_OFFSET
> w
.ws_col
)
493 g
.w
= (w
.ws_col
- 2*COL_OFFSET
) / op
.sch
->display_width
;
494 if (LINE_OFFSET
+ g
.h
+ LINES_AFTER
> w
.ws_row
)
495 g
.h
= w
.ws_row
- (LINE_OFFSET
+LINES_AFTER
);
498 void timer_setup (int enable
) {
499 static struct itimerval tbuf
;
500 tbuf
.it_interval
.tv_sec
= 0;//TODO: make it speed up automatically
501 tbuf
.it_interval
.tv_usec
= (1000000/g
.v
)-1; /*WARN: 1 <= g.v <= 999999*/
504 tbuf
.it_value
.tv_sec
= tbuf
.it_interval
.tv_sec
;
505 tbuf
.it_value
.tv_usec
= tbuf
.it_interval
.tv_usec
;
507 tbuf
.it_value
.tv_sec
= 0;
508 tbuf
.it_value
.tv_usec
= 0;
511 if ( setitimer(ITIMER_REAL
, &tbuf
, NULL
) == -1 ) {
518 void signal_setup (void) {
519 struct sigaction saction
;
521 saction
.sa_handler
= signal_handler
;
522 sigemptyset(&saction
.sa_mask
);
523 saction
.sa_flags
= 0;
524 if (sigaction(SIGALRM
, &saction
, NULL
) < 0 ) {
529 if (sigaction(SIGINT
, &saction
, NULL
) < 0 ) {
534 if (sigaction(SIGCONT
, &saction
, NULL
) < 0 ) {
540 void signal_handler (int signum
) {
553 void screen_setup (int enable
) {
556 printf ("\033[s\033[?47h"); /* save cursor, alternate screen */
557 printf ("\033[H\033[J"); /* reset cursor, clear screen */
558 printf ("\033[?25l"); /* hide cursor */
559 print (op
.sch
->init_seq
); /* swich charset, if necessary */
561 print (op
.sch
->reset_seq
); /* reset charset, if necessary */
562 printf ("\033[?25h"); /* show cursor */
563 printf ("\033[?47l\033[u"); /* primary screen, restore cursor */
568 /* http://users.csc.calpoly.edu/~phatalsk/357/lectures/code/sigalrm.c */
569 void raw_mode(int enable
) {
570 static struct termios saved_term_mode
;
571 struct termios raw_term_mode
;
574 tcgetattr(STDIN_FILENO
, &saved_term_mode
);
575 raw_term_mode
= saved_term_mode
;
576 raw_term_mode
.c_lflag
&= ~(ICANON
| ECHO
);
577 raw_term_mode
.c_cc
[VMIN
] = 1 ;
578 raw_term_mode
.c_cc
[VTIME
] = 0;
579 tcsetattr(STDIN_FILENO
, TCSAFLUSH
, &raw_term_mode
);
581 tcsetattr(STDIN_FILENO
, TCSAFLUSH
, &saved_term_mode
);