pvjc25/a3/snake.c

100 lines
2.2 KiB
C

#include "snake.h"
#include <stdlib.h>
struct snake* add_snake(struct snake* snake, int x, int y) {
struct snake* head = calloc(1, sizeof(struct snake));
if (head == NULL) {
return NULL; // Handle memory allocation failure
}
head->x = x;
head->y = y;
head->next = snake;
return head;
}
struct snake* remove_snake(struct snake* snake) {
if (snake == NULL) {
return NULL;
}
if (snake->next == NULL) {
free(snake);
return NULL;
}
struct snake* this = snake;
struct snake* prev = NULL;
while (this->next != NULL) {
prev = this;
this = this->next;
}
free(this);
prev->next = NULL;
return snake;
}
void free_snake(struct snake* sn) {
if (sn == NULL) {
return;
}
free_snake(sn->next);
free(sn);
}
int is_snake(struct snake* snake, int x, int y) {
for (struct snake* this = snake; this != NULL; this = this->next) {
if (this->x == x && this->y == y) {
return 1;
}
}
return 0;
}
int step_state(struct state* st) {
// Calculate new head position
int nx = st->snake->x + st->sx;
int ny = st->snake->y + st->sy;
// Check wall collision
if (nx < 0 || nx >= st->width || ny < 0 || ny >= st->height) {
return END_WALL;
}
// Check self collision
if (is_snake(st->snake, nx, ny)) {
return END_SNAKE;
}
// Check if food is eaten
int ate_food = 0;
int food_left = 0;
for (int i = 0; i < FOOD_COUNT; i++) {
if (st->foodx[i] >= 0 && st->foody[i] >= 0) {
food_left++;
if (st->foodx[i] == nx && st->foody[i] == ny) {
// Eat food
st->foodx[i] = -1;
st->foody[i] = -1;
ate_food = 1;
food_left--; // This food is now eaten
}
}
}
// Add new head
st->snake = add_snake(st->snake, nx, ny);
if (ate_food) {
// If all food eaten, end game
if (food_left == 0) {
return END_FOOD;
}
// Do not remove tail (snake grows)
} else {
// Remove tail (snake moves)
st->snake = remove_snake(st->snake);
}
return END_CONTINUE;
}