58 lines
1.4 KiB
C
58 lines
1.4 KiB
C
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
void free_snake(struct snake* snake) {
|
|
while (snake != NULL) {
|
|
struct snake* next = snake->next;
|
|
free(snake);
|
|
snake = next;
|
|
}
|
|
}
|
|
|
|
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->next, 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);
|
|
return END_FOOD;
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|