105 lines
2.3 KiB
C
105 lines
2.3 KiB
C
#include "snake.h"
|
|
#include <stdlib.h>
|
|
|
|
struct snake* add_snake(struct snake* snake,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 = snake;
|
|
return new_head;
|
|
}
|
|
|
|
struct snake* remove_snake(struct snake* snake){
|
|
if (snake == NULL) {
|
|
return NULL;
|
|
}
|
|
|
|
struct snake* current = snake;
|
|
struct snake* p = NULL;
|
|
|
|
while (current->next != NULL) {
|
|
p = current;
|
|
current = current->next;
|
|
}
|
|
|
|
free(current);
|
|
|
|
if (p == NULL) {
|
|
return NULL;
|
|
}
|
|
|
|
p->next = NULL;
|
|
return snake;
|
|
}
|
|
|
|
|
|
void free_snake(struct snake* sn){
|
|
struct snake* current = sn;
|
|
while (current != NULL) {
|
|
struct snake* next = current->next;
|
|
free(current);
|
|
current = next;
|
|
}
|
|
}
|
|
|
|
|
|
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;
|
|
}
|
|
|
|
|
|
int step_state(struct state* st){
|
|
int nx = (st->snake->x + st->sx);
|
|
int ny = (st->snake->y + st->sy);
|
|
if (nx < 0 || nx >= st->width || ny < 0 || ny >= st->height) {
|
|
return END_WALL;
|
|
}
|
|
|
|
// Check if snake hit itself
|
|
if (is_snake(st->snake, nx, ny)) {
|
|
return END_SNAKE;
|
|
}
|
|
|
|
// Check if snake ate food
|
|
int food_eaten = 0;
|
|
for (int i = 0; i < FOOD_COUNT; i++) {
|
|
if (st->foodx[i] >= 0 && st->foodx[i] == nx && st->foody[i] == ny) {
|
|
st->foodx[i] = -1;
|
|
st->foody[i] = -1;
|
|
st->snake = add_snake(st->snake, nx, ny);
|
|
food_eaten = 1;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Check if game ended
|
|
if (!food_eaten) {
|
|
int food_left = 0;
|
|
for (int i = 0; i < FOOD_COUNT; i++) {
|
|
if (st->foodx[i] >= 0) {
|
|
food_left = 1;
|
|
break;
|
|
}
|
|
}
|
|
if (!food_left) {
|
|
return END_FOOD;
|
|
}
|
|
// Remove the last snake part
|
|
st->snake = remove_snake(st->snake);
|
|
// Add new snake part
|
|
st->snake = add_snake(st->snake, nx, ny);
|
|
}
|
|
|
|
return END_CONTINUE;
|
|
}
|
|
|