This commit is contained in:
Macko 2024-04-11 14:09:32 +02:00
parent 2aa6b69cbd
commit 7c29a6bd1c

View File

@ -1,61 +1,67 @@
#include "snake.h" #include "snake.h"
#include <stdlib.h> #include <stdlib.h>
void place_food(struct state* state) { #define FOOD_COUNT 20
for (int i = 0; i < FOOD_COUNT; i++) {
if (state->foodx[i] < 0 || state->foody[i] < 0) { struct state {
state->foodx[i] = rand() % state->width; struct snake* snake;
state->foody[i] = rand() % state->height; int sx, sy;
int width, height;
int foodx[FOOD_COUNT], foody[FOOD_COUNT];
};
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 || snake->next == NULL) {
return NULL;
}
struct snake* temp = snake;
while(temp->next->next != NULL) {
temp = temp->next;
}
free(temp->next);
temp->next = NULL;
return snake;
}
int is_snake(struct snake* snake, int x, int y) {
while(snake != NULL) {
if(snake->x == x && snake->y == y) {
return 1;
}
snake = snake->next;
}
return 0;
}
void free_snake(struct snake* snake) {
struct snake* temp;
while(snake != NULL) {
temp = snake;
snake = snake->next;
free(temp);
} }
} }
int step_state(struct state* state, int key) { int step_state(struct state* state) {
switch (key) {
case KEY_UP:
if (state->sy != 1) {
state->sx = 0;
state->sy = -1;
}
break;
case KEY_DOWN:
if (state->sy != -1) {
state->sx = 0;
state->sy = 1;
}
break;
case KEY_LEFT:
if (state->sx != 1) {
state->sx = -1;
state->sy = 0;
}
break;
case KEY_RIGHT:
if (state->sx != -1) {
state->sx = 1;
state->sy = 0;
}
break;
default:
break;
}
int new_x = state->snake->x + state->sx; int new_x = state->snake->x + state->sx;
int new_y = state->snake->y + state->sy; int new_y = state->snake->y + state->sy;
if(new_x < 0 || new_x >= state->width || new_y < 0 || new_y >= state->height) { if(new_x < 0 || new_x >= state->width || new_y < 0 || new_y >= state->height) {
return END_WALL; return END_WALL;
} }
if(is_snake(state->snake, new_x, new_y)) { if(is_snake(state->snake, new_x, new_y)) {
return END_SNAKE; return END_SNAKE;
} }
for(int i = 0; i < FOOD_COUNT; i++) { for(int i = 0; i < FOOD_COUNT; i++) {
if(state->foodx[i] == new_x && state->foody[i] == new_y) { if(state->foodx[i] == new_x && state->foody[i] == new_y) {
state->foodx[i] = -1; state->foodx[i] = -1;
@ -70,7 +76,6 @@ int step_state(struct state* state, int key) {
} }
} }
state->snake = add_snake(state->snake, new_x, new_y); state->snake = add_snake(state->snake, new_x, new_y);
state->snake = remove_snake(state->snake); state->snake = remove_snake(state->snake);