From 2aa6b69cbd8a717be83e9754a02439b312f461b7 Mon Sep 17 00:00:00 2001 From: Miloslav Macko Date: Thu, 11 Apr 2024 14:06:05 +0200 Subject: [PATCH] 1111 --- a2/snake.c | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 a2/snake.c diff --git a/a2/snake.c b/a2/snake.c new file mode 100644 index 0000000..5eccde1 --- /dev/null +++ b/a2/snake.c @@ -0,0 +1,78 @@ +#include "snake.h" +#include + +void place_food(struct state* state) { + for (int i = 0; i < FOOD_COUNT; i++) { + if (state->foodx[i] < 0 || state->foody[i] < 0) { + state->foodx[i] = rand() % state->width; + state->foody[i] = rand() % state->height; + } + } +} + +int step_state(struct state* state, int key) { + + 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_y = state->snake->y + state->sy; + + + if (new_x < 0 || new_x >= state->width || new_y < 0 || new_y >= state->height) { + return END_WALL; + } + + + if (is_snake(state->snake, new_x, new_y)) { + return END_SNAKE; + } + + + for (int i = 0; i < FOOD_COUNT; i++) { + if (state->foodx[i] == new_x && state->foody[i] == new_y) { + state->foodx[i] = -1; + state->foody[i] = -1; + state->snake = add_snake(state->snake, new_x, new_y); + for (int j = 0; j < FOOD_COUNT; j++) { + if (state->foodx[j] != -1) { + return END_CONTINUE; + } + } + return END_FOOD; + } + } + + + state->snake = add_snake(state->snake, new_x, new_y); + state->snake = remove_snake(state->snake); + + return END_CONTINUE; +}