pvjc26/du4/snake.c
2026-04-14 15:46:28 +00:00

69 lines
2.1 KiB
C

#include "snake.h"
#include <stdlib.h>
struct snake* add_snake(struct snake* snake,int x,int y){
struct snake* nova_hlava = malloc(sizeof(struct snake)); //vytvorim novu hlavu na ktoru nalinkujem staru hlavu ako telo
nova_hlava -> x = x;
nova_hlava -> y = y; //zapisem suradnice novej hlavy do novej struktury
nova_hlava -> next = snake; //dalsi segment (next) je stara hlava zo vstupu funkcie
return nova_hlava;
}
struct snake* remove_snake(struct snake* snake){
if (snake == NULL) return NULL; // valgrind chce na tento test reisenie
struct snake* clanok = snake;
if (snake -> next == NULL) {
free(snake);
return NULL;
}
while (clanok -> next -> next != NULL) { // posuvam sa po hadovi kym nenajdem koniec chvosta ktory odmazem
clanok = clanok -> next;
}
free (clanok -> next); //po tom co som nasiel kde je koniec, odmazem koniec chvosta a korunujem nasledujuci clanok novym koncom
clanok -> next = NULL;
return snake; //kedze som menil snaka podla referenciam v pamati, mozem vratit noveho stareho hada
}
void free_snake(struct snake* sn){
if (sn == NULL) return;
struct snake* clanok = sn; //idem pozerat kde su clanky
do {
clanok = sn;//nacitam aktualny clanok
sn = sn -> next;//posuniem sa o clanok
free(clanok);//vycistim staru ulozenu poziciu
} while (sn -> next != NULL);
free(clanok -> next);
}
int is_snake(struct snake* snake,int x,int y){
struct snake* clanok = snake;//zase idem pozerat po clankoch ci som na hadovi v koordinatoch
while (clanok != NULL) { // usetrim si podmienku ci nahodou nedostanem NULL hada
if (clanok -> x == x && clanok -> y == y) {
return 1; // mam vratit true/false, ale dostal som int funkciu, bool true false je aj tak iba jeden bit 1 alebo 0
}
clanok = clanok -> next;
}
return 0; //defaultne vratim 0 ked nenajdem hada
}
int step_state(struct state* st){
int nx = (st->snake->x + st->sx);
int ny = (st->snake->y + st->sy);
return END_CONTINUE;
}