Update 'du7/snake.c'
This commit is contained in:
parent
6ac496d421
commit
5ec0f07e6f
85
du7/snake.c
85
du7/snake.c
@ -2,22 +2,103 @@
|
||||
#include <stdlib.h>
|
||||
|
||||
struct snake* add_snake(struct snake* snake,int x,int y){
|
||||
return NULL;
|
||||
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){
|
||||
return NULL;
|
||||
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 = snake;
|
||||
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 (new_head_x < 0 || new_head_x >= state->width || new_head_y < 0 || new_head_y >= state->height) {
|
||||
return END_WALL;
|
||||
}
|
||||
|
||||
// Check if snake hit itself
|
||||
if (is_snake(state->snake, new_head_x, new_head_y)) {
|
||||
return END_SNAKE;
|
||||
}
|
||||
|
||||
// Check if snake ate food
|
||||
int food_eaten = 0;
|
||||
for (int i = 0; i < FOOD_COUNT; i++) {
|
||||
if (state->foodx[i] >= 0 && state->foodx[i] == new_head_x && state->foody[i] == new_head_y) {
|
||||
state->foodx[i] = -1;
|
||||
state->foody[i] = -1;
|
||||
state->snake = add_snake(state->snake, new_head_x, new_head_y);
|
||||
food_eaten = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if game ended
|
||||
if (!food_eaten) {
|
||||
int food_left = 0;
|
||||
for (int i = 0; i < FOOD_COUNT; i++) {
|
||||
if (state->foodx[i] >= 0) {
|
||||
food_left = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!food_left) {
|
||||
return END_FOOD;
|
||||
}
|
||||
// Remove the last snake part
|
||||
state->snake = remove_snake(state->snake);
|
||||
// Add new snake part
|
||||
state->snake = add_snake(state->snake, new_head_x, new_head_y);
|
||||
}
|
||||
|
||||
return END_CONTINUE;
|
||||
}
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user