101 lines
2.2 KiB
C
101 lines
2.2 KiB
C
#include "snake.h"
|
|
#include <stdlib.h>
|
|
|
|
struct snake* add_snake(struct snake* snake, int x, int y){
|
|
struct snake* new_head = (struct snake*)malloc(sizeof(struct snake));
|
|
if (new_head == NULL) {
|
|
return snake;
|
|
}
|
|
new_head->x = x;
|
|
new_head->y = y;
|
|
new_head->next = snake;
|
|
return new_head;
|
|
}
|
|
|
|
struct snake* remove_snake(struct snake* snake){
|
|
if (snake == NULL) {
|
|
return NULL;
|
|
}
|
|
|
|
if (snake->next == NULL) {
|
|
free(snake);
|
|
return NULL;
|
|
}
|
|
|
|
struct snake* current = snake;
|
|
while (current->next->next != NULL) {
|
|
current = current->next;
|
|
}
|
|
|
|
free(current->next);
|
|
current->next = NULL;
|
|
|
|
return snake;
|
|
}
|
|
|
|
void free_snake(struct snake* sn){
|
|
while (sn != NULL) {
|
|
struct snake* temp = sn;
|
|
sn = sn->next;
|
|
free(temp);
|
|
}
|
|
}
|
|
|
|
int is_snake(struct snake* snake, int x, int y){
|
|
struct snake* current = snake;
|
|
while (current != NULL) {
|
|
if (current->x == x && current->y == y) {
|
|
return 1;
|
|
}
|
|
current = current->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;
|
|
}
|
|
|
|
struct snake* current = st->snake->next;
|
|
while (current != NULL) {
|
|
if (current->x == nx && current->y == ny) {
|
|
return END_SNAKE;
|
|
}
|
|
current = current->next;
|
|
}
|
|
|
|
int food_index = -1;
|
|
for (int i = 0; i < FOOD_COUNT; i++) {
|
|
if (st->foodx[i] == nx && st->foody[i] == ny) {
|
|
food_index = i;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (food_index != -1) {
|
|
st->foodx[food_index] = -1;
|
|
st->foody[food_index] = -1;
|
|
st->snake = add_snake(st->snake, nx, ny);
|
|
|
|
int food_left = 0;
|
|
for (int i = 0; i < FOOD_COUNT; i++) {
|
|
if (st->foodx[i] >= 0) {
|
|
food_left = 1;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (!food_left) {
|
|
return END_FOOD;
|
|
}
|
|
return END_CONTINUE;
|
|
}
|
|
|
|
st->snake = add_snake(st->snake, nx, ny);
|
|
st->snake = remove_snake(st->snake);
|
|
|
|
return END_CONTINUE;
|
|
} |