pvjc26/du4/snake.c
2026-04-16 20:44:38 +00:00

128 lines
2.7 KiB
C

#include <stdio.h>
#include <stdlib.h>
#define FOOD_COUNT 5
struct snake {
int x;
int y;
struct snake* next;
};
enum endgame {
END_CONTINUE = 0,
END_WALL,
END_SNAKE,
END_FOOD,
END_USER
};
struct state {
struct snake* snake;
int foodx[FOOD_COUNT];
int foody[FOOD_COUNT];
int sx;
int sy;
int width;
int height;
};
struct snake* add_snake(struct snake* snake, int x, int y);
struct snake* remove_snake(struct snake* snake);
int is_snake(struct snake* snake, int x, int y);
void free_snake(struct snake* sn);
int step_state(struct state* state);
struct snake* add_snake(struct snake* snake, int x, int y) {
struct snake* new_part = (struct snake*)malloc(sizeof(struct snake));
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 != NULL && current->next->next != NULL) {
current = current->next;
}
if (current->next != NULL) {
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* sn) {
while (sn != NULL) {
struct snake* temp = sn;
sn = sn->next;
free(temp);
}
}
int step_state(struct state* state) {
int newX = state->snake->x + state->sx;
int newY = state->snake->y + state->sy;
if (newX < 0 || newX >= state->width || newY < 0 || newY >= state->height) {
return END_WALL;
}
if (is_snake(state->snake->next, newX, newY)) {
return END_SNAKE;
}
int foodIdx = -1;
for (int i = 0; i < FOOD_COUNT; i++) {
if (state->foodx[i] == newX && state->foody[i] == newY) {
foodIdx = i;
break;
}
}
if (foodIdx != -1) {
state->foodx[foodIdx] = -1;
state->foody[foodIdx] = -1;
state->snake = add_snake(state->snake, newX, newY);
int foodLeft = 0;
for (int i = 0; i < FOOD_COUNT; i++) {
if (state->foodx[i] >= 0) {
foodLeft = 1;
break;
}
}
return foodLeft ? END_CONTINUE : END_FOOD;
}
state->snake = add_snake(state->snake, newX, newY);
state->snake = remove_snake(state->snake);
return END_CONTINUE;
}