snake
This commit is contained in:
parent
1f8430869e
commit
7ac6c75676
82
cv9/snake.c
Normal file
82
cv9/snake.c
Normal file
@ -0,0 +1,82 @@
|
||||
#include "snake.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
|
||||
struct snake* add_snake(struct snake* snake, int x, int y) {
|
||||
struct snake* new_part = (struct snake*)malloc(sizeof(struct snake));
|
||||
if (!new_part) return NULL;
|
||||
new_part->x = x;
|
||||
new_part->y = y;
|
||||
new_part->next = snake;
|
||||
return new_part;
|
||||
}
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
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, 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] = state->foody[i] = -1;
|
||||
state->snake = add_snake(state->snake, new_x, new_y);
|
||||
|
||||
int all_eaten = 1;
|
||||
for (int j = 0; j < FOOD_COUNT; j++) {
|
||||
if (state->foodx[j] != -1 || state->foody[j] != -1) {
|
||||
all_eaten = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return all_eaten ? END_FOOD : END_CONTINUE;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
state->snake = add_snake(state->snake, new_x, new_y);
|
||||
state->snake = remove_snake(state->snake);
|
||||
return END_CONTINUE;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user