pvjc26/du4/game.c
mk570rp 10cc177646 a4:
git commit -m a4
git commit -m a4:
2026-05-10 19:30:35 +00:00

82 lines
1.5 KiB
C

#include <stdlib.h>
#include "game.h"
struct snake* add_snake(struct snake* snake, int x, int y) {
struct snake* h = calloc(1, sizeof(struct snake));
h->x = x;
h->y = y;
h->next = snake;
return h;
}
struct snake* remove_snake(struct snake* snake) {
if (!snake) return NULL;
if (!snake->next) {
free(snake);
return NULL;
}
struct snake* cur = snake;
while (cur->next->next)
cur = cur->next;
free(cur->next);
cur->next = NULL;
return snake;
}
int is_snake(struct snake* snake, int x, int y) {
while (snake) {
if (snake->x == x && snake->y == y)
return 1;
snake = snake->next;
}
return 0;
}
void free_snake(struct snake* sn) {
while (sn) {
struct snake* n = sn->next;
free(sn);
sn = n;
}
}
int step_state(struct state* s) {
int nx = s->snake->x + s->sx;
int ny = s->snake->y + s->sy;
if (nx < 0 || ny < 0 || nx >= s->width || ny >= s->height)
return END_WALL;
if (is_snake(s->snake, nx, ny))
return END_SNAKE;
int ate = 0;
for (int i = 0; i < FOOD_COUNT; i++) {
if (s->foodx[i] == nx && s->foody[i] == ny) {
s->foodx[i] = -1;
s->foody[i] = -1;
ate = 1;
break;
}
}
s->snake = add_snake(s->snake, nx, ny);
if (!ate) {
s->snake = remove_snake(s->snake);
}
for (int i = 0; i < FOOD_COUNT; i++) {
if (s->foodx[i] >= 0)
return END_CONTINUE;
}
return END_FOOD;
}