106 lines
2.4 KiB
C
106 lines
2.4 KiB
C
#include <stdio.h>
|
|
#include "snake.h"
|
|
#include <stdlib.h>
|
|
|
|
struct snake* add_snake (struct snake* snake, int x, int y) {
|
|
struct snake* head = NULL;
|
|
|
|
head = malloc(sizeof(struct snake));
|
|
|
|
if (!head) {
|
|
return snake;
|
|
}
|
|
head->x = x;
|
|
head->y = y;
|
|
|
|
head->next = NULL;
|
|
|
|
if (snake !=NULL) {
|
|
head->next = snake;
|
|
}
|
|
return head;
|
|
}
|
|
|
|
struct snake* remove_snake(struct snake* snake) {
|
|
if(snake == NULL || snake-> next == NULL) {
|
|
free(snake);
|
|
return NULL;
|
|
}
|
|
|
|
struct snake* previous = NULL;
|
|
struct snake* current = NULL;
|
|
while (current->next !=NULL) {
|
|
previous = current;
|
|
current = current->next;
|
|
}
|
|
|
|
if (previous !=NULL) {
|
|
free(current->next);
|
|
previous->next = NULL;
|
|
}
|
|
|
|
return snake;
|
|
}
|
|
|
|
void free_snake(struct snake* sn) {
|
|
struct snake* walker = sn;
|
|
struct snake* next_part = NULL;
|
|
while (walker !=NULL) {
|
|
next_part = walker->next;
|
|
free(walker);
|
|
walker = next_part;
|
|
}
|
|
}
|
|
|
|
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* state) {
|
|
int new_x = state->snake->x + state->sx;
|
|
int new_y = state->snake->y + state->sy;
|
|
|
|
if (new_x < 0 || new_x >= state-> width || new_y < 0 || new_y >= state->height) {
|
|
return END_WALL;
|
|
}
|
|
|
|
if (is_snake(state->snake, new_x, new_y)) {
|
|
return END_SNAKE;
|
|
}
|
|
|
|
for (int i = 0; i < FOOD_COUNT; i++) {
|
|
if (state->foodx[i] == new_x && state->foody[i] == new_y) {
|
|
state->foodx[i] = -1;
|
|
state->foody[i] = -1;
|
|
|
|
state->snake = add_snake(state->snake, new_x, new_y);
|
|
|
|
int any_food_left = 0;
|
|
for (int j = 0; j < FOOD_COUNT; j++) {
|
|
if (state->foodx[j] >= 0 && state->foody[j] >= 0) {
|
|
any_food_left = 1;
|
|
break;
|
|
}
|
|
}
|
|
if (any_food_left) {
|
|
return END_CONTINUE;
|
|
} else {
|
|
return END_FOOD;
|
|
}
|
|
}
|
|
}
|
|
state->snake = add_snake(state->snake, new_x, new_y);
|
|
state->snake = remove_snake(state->snake);
|
|
return END_CONTINUE;
|
|
}
|
|
|
|
|