pvjc21/du7/snake.c

109 lines
2.7 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "snake.h"
#include <stdlib.h>
struct snake* add_snake(struct snake* snake,int x,int y){
struct snake* newHead = (struct snake*) malloc(sizeof(struct snake));
newHead->x = x;
newHead->y = y;
newHead->next = snake;
/*struct snake* temp = snake;
int myX, myY;
while(temp->next != NULL){
myX = temp->x; //
myY = temp->y;
temp->x = temp->next->x; //указатель на позицию следующего элемента по Х
temp->y = temp->next->y;//указатель на позицию следующего элемента по У
temp = temp->next;
}
//temp->next = (struct snake*) calloc(1, sizeof(struct snake));
temp->next->x = temp->x - (myX - temp->x);
temp->next->y = temp->y - (myX - temp->y);
temp->next->next = NULL;*/
return newHead;
}
struct snake* remove_snake(struct snake* snake){
struct snake* temp = snake;
if(snake == NULL){
return snake;
}
else if(snake->next == NULL){
free(snake);
snake = NULL;
return snake;
}
while(temp->next->next != NULL){
temp = temp->next; // проход до последнего кусочка
}
temp->next = NULL;
temp = temp->next;
free(temp);
return snake;
}
void free_snake(struct snake* sn){
struct snake* temp = sn;
while(sn != NULL){
temp = sn;
sn = sn->next;
temp->next = NULL;
}
free(sn);
}
int is_snake(struct snake* snake,int x,int y){
struct snake* temp = snake;
while(temp != NULL){
if(x == temp->x && y == temp->y){
return 1;
}
temp = temp->next;
}
return 0;
}
int step_state(struct state* st){
int nx = (st->snake->x + st->sx);
int ny = (st->snake->y + st->sy);
for(int i = 0; i < FOOD_COUNT; i++){
if(nx == st->foodx[i] && ny == st->foody[i]){
st->snake = add_snake(st->snake, st->foodx[i], st->foody[i]);
st->foodx[i] = -1;
st->foody[i] = -1;
for(int j = 0; j < FOOD_COUNT; j++){
if(st->foodx[i] != -1 || st->foody[i] != -1){
break;
}
else if(st->foodx[i] == -1 && st->foody[i] == -1 && j == FOOD_COUNT - 1){
return END_FOOD;
}
}
return END_CONTINUE;
}
}
for(struct snake* temp = st->snake; temp != NULL; temp = temp->next){
if((nx == temp->x && ny == temp->y) || (nx < 0 || nx >= st->width || ny < 0 || ny >= st->height)){
return END_SNAKE;
}
}
st->snake = add_snake(st->snake, nx, ny);
remove_snake(st->snake);
return END_CONTINUE;
}