pvjc22/du7/snake.c

116 lines
2.1 KiB
C
Raw Permalink Normal View History

2022-04-29 09:20:39 +00:00
#include <stdlib.h>
2022-04-29 09:22:06 +00:00
#include "snake.h"
2022-04-29 09:14:44 +00:00
//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){
2022-04-29 09:46:14 +00:00
if(!snake)
2022-04-29 09:14:44 +00:00
return NULL;
2022-04-29 09:46:14 +00:00
if(!snake->next){
free(snake);
return NULL;
}
2022-04-29 09:14:44 +00:00
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;
//
2022-04-29 09:33:24 +00:00
if(nx<0||ny<0||nx>=st->width||ny>=st->height)
2022-04-29 09:14:44 +00:00
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;
}