pvjc23/du7/snake.c

105 lines
3.6 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)); // Dynamické prideľovanie pamäte pre novú hadiu hlavu
new_head->x = x;
new_head->y = y;
new_head->next = snake; // Nastaví ďalší ukazovateľ novej hlavy hada na aktuálnu hlavu hada
return new_head;
}
struct snake* remove_snake(struct snake* snake){ // Definujte funkciu na odstránenie posledného hadieho chvosta
if (snake == NULL) { // Ak je had prázdny, vráti NULL
return NULL;
}
struct snake* current = snake; // Nastaví aktuálny ukazovateľ na aktuálnu hlavu hada a ukazovateľ p na hodnotu NULL
struct snake* p = NULL;
while (current->next != NULL) { // Prejdite hadom, kým nedosiahnete posledný uzol
p = current;
current = current->next;
}
free(current); // Uvoľnite posledný uzol
if (p == NULL) { // Ak mal had iba jeden uzol, vráti hodnotu NULL
return NULL;
}
p->next = NULL; // Nastaví ďalší ukazovateľ nového posledného uzla na NULL a vráti hada
return snake;
}
void free_snake(struct snake* sn){ // Definujem funkciu na oslobodenie celého hada
struct snake* current = sn; // Nastaví aktuálny ukazovateľ na aktuálnu hlavu hada
while (current != NULL) { // Prejdem hadom a uvoľnite každý uzol
struct snake* next = current->next;
free(current);
current = next;
}
}
int is_snake(struct snake* snake,int x,int y){ // Definujem funkciu na kontrolu, či je bod v hadovi
struct snake* current = snake; // Nastaví aktuálny ukazovateľ na aktuálnu hlavu hada
while (current != NULL) { // Prejdite hadom a skontrolujte, či sa súradnice zhodujú
if (current->x == x && current->y == y) {
return 1;
}
current = current->next;
}
return 0; // Ak sa súradnice nezhodujú, vráti 0
}
int step_state(struct state* st){ // Definujem funkciu na aktualizáciu stavu hry po jednom kroku
int nx = (st->snake->x + st->sx); // Vypočítajem nové súradnice hlavy hada
int ny = (st->snake->y + st->sy);
if (nx < 0 || nx >= st->width || ny < 0 || ny >= st->height) { // Skontrolujem, či had narazí na stenu
return END_WALL;
}
// Check if snake hit itself
if (is_snake(st->snake, nx, ny)) { // Skontrolujem, či sa had zasiahne sám
return END_SNAKE;
}
// Check if snake ate food
int food_eaten = 0; // Skontrolujem, či had žerie jedlo
for (int a = 0; a < FOOD_COUNT; a++) {
if (st->foodx[a] >= 0 && st->foodx[a] == nx && st->foody[a] == ny) {
st->foodx[a] = -1;
st->foody[a] = -1;
st->snake = add_snake(st->snake, nx, ny);
food_eaten = 1;
break;
}
}
// Skontrolujem, či sa hra skončila
if (!food_eaten) {
int food_left = 0;
for (int a = 0; a < FOOD_COUNT; a++) {
if (st->foodx[a] >= 0) {
food_left = 1;
break;
}
}
if (!food_left) {
return END_FOOD;
}
// Odstráňym poslednú časť hada
st->snake = remove_snake(st->snake);
// Pridajem novú časť hada
st->snake = add_snake(st->snake, nx, ny);
}
return END_CONTINUE;
}