2024-04-15 20:31:53 +00:00
|
|
|
struct snake* add_snake(struct snake* old_head, int x, int y) {
|
|
|
|
struct snake* new_head = (struct snake*) malloc(sizeof(struct snake));
|
|
|
|
new_head->x = x;
|
|
|
|
new_head->y = y;
|
|
|
|
new_head->next = old_head;
|
|
|
|
return new_head;
|
|
|
|
}
|
2024-04-11 12:09:32 +00:00
|
|
|
|
2024-04-15 20:31:53 +00:00
|
|
|
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;
|
|
|
|
}
|
2024-04-11 12:09:32 +00:00
|
|
|
return 0;
|
2024-04-11 12:06:05 +00:00
|
|
|
}
|
|
|
|
|
2024-04-15 20:31:53 +00:00
|
|
|
void free_snake(struct snake* snake) {
|
|
|
|
while (snake != NULL) {
|
|
|
|
struct snake* next = snake->next;
|
|
|
|
free(snake);
|
|
|
|
snake = next;
|
2024-04-11 12:06:05 +00:00
|
|
|
}
|
2024-04-11 12:09:32 +00:00
|
|
|
}
|
2024-04-11 12:06:05 +00:00
|
|
|
|
2024-04-15 20:31:53 +00:00
|
|
|
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;
|
2024-04-11 12:06:05 +00:00
|
|
|
}
|
|
|
|
|
2024-04-15 20:31:53 +00:00
|
|
|
if (is_snake(state->snake->next, new_x, new_y)) {
|
|
|
|
return END_SNAKE;
|
2024-04-11 12:06:05 +00:00
|
|
|
}
|
|
|
|
|
2024-04-15 20:31:53 +00:00
|
|
|
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);
|
|
|
|
return END_FOOD;
|
2024-04-11 12:06:05 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-15 20:31:53 +00:00
|
|
|
state->snake = add_snake(state->snake, new_x, new_y);
|
|
|
|
struct snake* tail = state->snake;
|
|
|
|
while (tail->next->next != NULL) {
|
|
|
|
tail = tail->next;
|
|
|
|
}
|
|
|
|
free(tail->next);
|
|
|
|
tail->next = NULL;
|
|
|
|
|
|
|
|
return END_CONTINUE;
|
2024-04-11 12:06:05 +00:00
|
|
|
}
|