111 lines
2.3 KiB
C
111 lines
2.3 KiB
C
#include <stdio.h>
|
|
#include "snake.h"
|
|
#include <stdlib.h>
|
|
|
|
struct snake* add_snake (struct snake* snake, int x, int y) {
|
|
struct snake* head = NULL;
|
|
|
|
head = malloc(sizeof(struct snake));
|
|
|
|
if (!head) {
|
|
return snake;
|
|
}
|
|
head->x = x;
|
|
head->y = y;
|
|
|
|
head->next = NULL;
|
|
|
|
if (snake !=NULL) {
|
|
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* temp = snake;
|
|
while (temp->next->next != NULL) {
|
|
temp = temp->next;
|
|
}
|
|
|
|
free(temp->next);
|
|
temp->next = NULL;
|
|
|
|
return snake;
|
|
}
|
|
|
|
void free_snake(struct snake* sn) {
|
|
struct snake* walker = sn;
|
|
struct snake* next_part = NULL;
|
|
while (walker !=NULL) {
|
|
next_part = walker->next;
|
|
free(walker);
|
|
walker = next_part;
|
|
}
|
|
}
|
|
|
|
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* state) {
|
|
int x = state->snake->x + state->sx;
|
|
int y = state->snake->y + state->sy;
|
|
|
|
if (x < 0) return END_WALL;
|
|
if (x >= state->width) return END_WALL;
|
|
if (y < 0) return END_WALL;
|
|
if (y >= state->height) return END_WALL;
|
|
|
|
if (is_snake(state->snake, x, y)) {
|
|
return END_SNAKE;
|
|
}
|
|
|
|
int food_found = -1;
|
|
for (int idx = 0; idx < FOOD_COUNT; idx++) {
|
|
if (state->foodx[idx] == x && state->foody[idx] == y) {
|
|
food_found = idx;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (food_found != -1) {
|
|
state->foodx[food_found] = -1;
|
|
state->foody[food_found] = -1;
|
|
state->snake = add_snake(state->snake, x, y);
|
|
|
|
int remaining = 0;
|
|
for (int k = 0; k < FOOD_COUNT; ++k) {
|
|
remaining += (state->foodx[k] >= 0 && state->foody[k] >= 0);
|
|
}
|
|
|
|
if (remaining == 0) {
|
|
return END_FOOD;
|
|
}
|
|
return END_CONTINUE;
|
|
}
|
|
|
|
state->snake = add_snake(state->snake, x, y);
|
|
state->snake = remove_snake(state->snake);
|
|
|
|
return END_CONTINUE;
|
|
}
|
|
|
|
|