pvjc22/du7/snake.c
2022-04-29 11:18:20 +02:00

113 lines
2.1 KiB
C

#include"snake.h"
#include<stdlib.h>
#include<curses.h>
//void freeAll(struct snake* prvok);
struct snake* add_snake(struct snake* snake,int x,int y){
struct snake* head = calloc(1,sizeof(struct snake));
head->x = x;
head->y = y;
head->next = snake;
return head;
}
struct snake* remove_snake(struct snake* snake){
if(!snake->next&&!snake)
return NULL;
struct snake* last = snake;
struct snake* secondLast = snake;
while(1){
if(!last->next){
free(last);
secondLast->next=NULL;
return snake;
}
secondLast=last;
last=last->next;
}
}
void free_snake(struct snake* sn){
struct snake* this = sn;
while(this){
struct snake* next = this->next;
free(this);
this = next;
}
}
/*
void freeAll(struct snake* prvok){
if(!prvok)
break;
else if(prvok->next)
freeAll(prvok->next);
free(prvok);
}*/
int is_snake(struct snake* snake,int x,int y){
struct snake* this = snake;
while(this){
if(this->x==x && this->y==y)
return 1;
this = this->next;
}
return 0;
}
//Spojkový zoznam =============================> celá hra
int step_state(struct state* st){
int nx = (st->snake->x + st->sx);
int ny = (st->snake->y + st->sy);
if(is_snake(st->snake,nx, ny))
return END_SNAKE;
//
for(int i = 0;i < FOOD_COUNT; i++){
if(nx==st->foodx[i]&&ny==st->foody[i]){
st->foody[i]=-1;
st->foodx[i]=-1;
add_snake(st->snake, nx, ny);
}
}
int is_all_eaten=1;
for(int i = 0;i < FOOD_COUNT; i++){
if(st->foodx[i]>=0){
is_all_eaten = 0;
break;
}
}
if(is_all_eaten)
return END_FOOD;
//
if(nx<0||ny<0||nx>=COLS||ny>=LINES)
return END_WALL;
//
if(st->snake->x != nx && st->snake->y != ny){
remove_snake(st->snake);
add_snake(st->snake, nx, ny);
}
return END_CONTINUE;
}