97 lines
2.5 KiB
C
97 lines
2.5 KiB
C
#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 - (myY - temp->y);
|
||
temp->next->next = NULL;*/
|
||
|
||
return newHead;
|
||
}
|
||
|
||
struct snake* remove_snake(struct snake* snake){
|
||
struct snake* temp = snake;
|
||
|
||
while(temp->next->next != NULL){
|
||
temp = temp->next; // проход до последнего кусочка
|
||
}
|
||
|
||
temp->next = NULL;
|
||
|
||
return snake;
|
||
}
|
||
|
||
void free_snake(struct snake* sn){
|
||
struct snake* temp = sn;
|
||
|
||
while(sn != NULL){
|
||
temp = sn;
|
||
sn = sn->next;
|
||
temp->next = NULL;
|
||
}
|
||
}
|
||
|
||
int is_snake(struct snake* snake,int x,int y){
|
||
struct snake* temp = snake;
|
||
|
||
while(temp->next != 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->next; 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;
|
||
}
|
||
|