66 lines
1.6 KiB
C
66 lines
1.6 KiB
C
#include "snake.h"
|
|
#include <stdlib.h>
|
|
|
|
struct snake* add_snake(struct snake* snake, int x, int y){
|
|
struct snake* head = malloc(sizeof(struct snake));
|
|
head->x = x;
|
|
head->y = y;
|
|
head->next = snake;
|
|
return head;
|
|
}
|
|
|
|
struct snake* remove_snake(struct snake* snake){
|
|
if(snake == NULL) return NULL;
|
|
if(snake->next == NULL){
|
|
free(snake);
|
|
return NULL;
|
|
}
|
|
struct snake* cur = snake;
|
|
while(cur->next->next != NULL)
|
|
cur = cur->next;
|
|
free(cur->next);
|
|
cur->next = NULL;
|
|
return snake;
|
|
}
|
|
|
|
void free_snake(struct snake* sn){
|
|
while(sn != NULL){
|
|
struct snake* tmp = sn->next;
|
|
free(sn);
|
|
sn = tmp;
|
|
}
|
|
}
|
|
|
|
int is_snake(struct snake* snake, int x, int y){
|
|
while(snake != NULL){
|
|
if(snake->x == x && snake->y == y) return 1;
|
|
snake = snake->next;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
int step_state(struct state* st){
|
|
int nx = st->snake->x + st->sx;
|
|
int ny = st->snake->y + st->sy;
|
|
|
|
if(nx < 0 || nx >= st->width || ny < 0 || ny >= st->height)
|
|
return END_WALL;
|
|
|
|
if(is_snake(st->snake, nx, ny))
|
|
return END_SNAKE;
|
|
|
|
for(int i = 0; i < FOOD_COUNT; i++){
|
|
if(st->foodx[i] == nx && st->foody[i] == ny){
|
|
st->snake = add_snake(st->snake, nx, ny);
|
|
st->foodx[i] = -1;
|
|
st->foody[i] = -1;
|
|
for(int j = 0; j < FOOD_COUNT; j++)
|
|
if(st->foodx[j] >= 0) return END_CONTINUE;
|
|
return END_FOOD;
|
|
}
|
|
}
|
|
|
|
st->snake = add_snake(st->snake, nx, ny);
|
|
st->snake = remove_snake(st->snake);
|
|
return END_CONTINUE;
|
|
} |