pvjc22/a2/snake.c

105 lines
2.7 KiB
C
Raw Normal View History

2022-04-28 12:27:28 +00:00
#include "snake.h"
#include <stdlib.h>
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 (had->x == nx || had->y == ny) return END_SNAKE;
for (i = 0; i < FOOD_COUNT; i++) {
if (st->foodx[i] == had->x) {
if (st->foody[i] == had->y) {
had = add_snake(had, st->foodx[i], st->foody[i]);
st->foodx[i] = -1;
st->foody[i] = -1;
pocetJedal--;
}
}
}
if (pocetJedal == 0) return END_FOOD;
had = had->next;
}
had = hlava;
free(hlava);
if (nx > 0 && nx < st->width) {
if (ny > 0 && ny < st->height) {
had = add_snake(had, nx, ny);
had = remove_snake(had);
}
}
return END_CONTINUE;
}