#define BUFFER_SIZE 100
#define UP 0
#define RIGHT 1
#define DOWN 2
#define LEFT 3
#define RING_NEXT(INDEX) ((INDEX+1)%BUFFER_SIZE)
/* Snake coordinate buffer */
int snake_x[BUFFER_SIZE];
int snake_y[BUFFER_SIZE];
/* Snake head and tail indices */
int head;
int tail;
/* Function prototypes */
/* Add a snake head to coordinates (x, y) */
void add_head(int x, int y);
/* Remove snake tail piece */
void remove_tail(void);
/* Move snake one step, 0 = up, 1 = right, 2 = down, 3 = left */
/* if grow = 0 the snake does not grow. Otherwise it grows one piece */
void move_snake(int direction, int grow);
/* Calculates the length of the snake */
int snake_size();
void
main(void)
{
head = -1;
tail = 0;
/* Initialize 5 piece long snake */
add_head(50,46);
move_snake(UP, 1);
move_snake(UP, 1);
move_snake(UP, 1);
move_snake(UP, 1);
while(1)
{
/* Now you can move the snake by calling the move_snake function */
move_snake(UP, 0);
/* This piece of code loops through the snake parts from tail to head */
for (int i = tail; i != RING_NEXT(head); i = RING_NEXT(i)){
/* x-coordinate */
snake_x[i];
/* y-coordinate */
snake_y[i];
}
}
}
/******************************************************************************/
void
add_head(int x, int y)
/* Add a snake head to coordinates (x, y) */
{
/* Make sure there is space in the buffer */
if (snake_size() >= BUFFER_SIZE){
return;
}
head = RING_NEXT(head);
snake_x[head] = x;
snake_y[head] = y;
}
/******************************************************************************/
void
remove_tail()
/* Remove snake tail piece */
{
/* If snake is only one piece long, we won't remove its head */
if (snake_size() <= 0){
return;
}
tail = RING_NEXT(tail);
}
/******************************************************************************/
void
move_snake(int direction, int grow)
/* Move snake one step, 0 = up, 1 = right, 2 = down, 3 = left */
{
/* Make sure we have enough space if the snake wants to grow */
if ((snake_size() >= BUFFER_SIZE) && grow){
return;
}
if(direction == UP) {
add_head(snake_x[head], snake_y[head]+1);
} else if (direction == RIGHT) {
add_head(snake_x[head]+1, snake_y[head]);
} else if (direction == DOWN) {
add_head(snake_x[head], snake_y[head]-1);
} else if (direction == LEFT) {
add_head(snake_x[head]-1, snake_y[head]);
}
if (!grow) {
remove_tail();
}
}
/******************************************************************************/
int
snake_size()
/* Calculates the length of the snake */
{
return (tail<head) ? ((head-tail)+1) : ((BUFFER_SIZE-head+tail)+1);
}
/******************************************************************************/