#include "snake.h" #include struct snake* add_snake(struct snake* snake,int x,int y){ struct snake* novyZaciatok = calloc(1, sizeof(struct snake)); //alokujem pamäť smerníka novyZaciatok->x = x; //nastavím súradnice hada novyZaciatok->y = y; if (snake != NULL) { //ak má had telo, novyZaciatok->next = snake; //tak mu iba pridám hlavu } else { novyZaciatok->next = NULL; //inak musím vytvoriť nové telo } return novyZaciatok; } struct snake* remove_snake(struct snake* snake){ if (snake == NULL) return NULL; //ak nezadám ako vstup hada, tak okamžite vrátim NULL else if (snake->next == NULL) { //ak had nemá pokračovanie, free(snake); //tak ho zruším return NULL; //a vrátim NULL } else { //inak prebehnem celého hada od začiatku struct snake* medzipamat = calloc(1, sizeof(struct snake)); //alokujem medzipamäť medzipamat = snake; //adresu hlavy hada uložím do medzipamäte while (snake->next->next != NULL) snake = snake->next; //hada budem prezerať dovtedy, kým nenájdem jeho koniec free(snake->next); //koniec hada zmažem snake->next = NULL; // nastavím nový koniec hada return medzipamat; //vrátim hlavu hada } } void free_snake(struct snake* sn){ //funkcia odstráni hada z hry struct snake* medzipamat = calloc(1, sizeof(struct snake)); //alokujem medzipamäť while (sn != NULL) { //v cykle vymažem každý jeden prvok hada medzipamat = sn->next; //hlavu hada uložím do medzipamäte free(sn); //ak odstránim ju sn = medzipamat; //nastavím novú hlavu hada } free(medzipamat); //nakoniec vyčistím aj medzipamäť } int is_snake(struct snake* snake,int x,int y){ if (snake == NULL) return 0; while (snake != NULL) { if (snake->x == x || snake->y == y) return 1; snake = snake->next; } return 0; } int step_state(struct state* st){ int nx = (st->snake->x + st->sx); int ny = (st->snake->y + st->sy); int i, pocetJedal = FOOD_COUNT; struct snake* had = calloc(1, sizeof(struct snake)); struct snake* hlava = calloc(1, sizeof(struct snake)); had = st->snake; hlava = st->snake; while (had != NULL) { if (snake->x == nx || snake->y == ny) return END_SNAKE; for (i = 0; i < FOOD_COUNT; i++) { if (foodx[i] == nx) { if (foody[i] == ny) { had = add_snake(had, foodx[i], foody[i]); foodx[i] = -1; foody[i] = -1; pocetJedal--; } } } if (pocetJedal == 0) return END_FOOD; } had = hlava; free(hlava); if (nx > 0 && nx < width) { if (ny > 0 && ny < height) { had = add_snake(had, nx, ny); had = remove_snake(had); } } return END_CONTINUE; }