diff --git a/du7/snake.c b/du7/snake.c index 8a911c8..2431a7d 100644 --- a/du7/snake.c +++ b/du7/snake.c @@ -1,13 +1,13 @@ -nclude "snake.h" +#include "snake.h" #include struct snake* add_snake(struct snake* snake,int x,int y){ struct snake* newHead = (struct snake*) malloc(sizeof(struct snake)); - newHead-> = x; - newHead-> = y; + newHead->x = x; + newHead->y = y; newHead->next = snake; - struct snake* temp = snake; + /*struct snake* temp = snake; int myX, myY; while(temp->next != NULL){ @@ -21,7 +21,7 @@ struct snake* add_snake(struct snake* snake,int x,int y){ //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; + temp->next->next = NULL;*/ return newHead; } @@ -29,11 +29,22 @@ struct snake* add_snake(struct snake* snake,int x,int y){ 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; } @@ -46,12 +57,14 @@ void free_snake(struct snake* 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->next != NULL){ + while(temp != NULL){ if(x == temp->x && y == temp->y){ return 1; } @@ -66,8 +79,8 @@ int step_state(struct state* st){ int ny = (st->snake->y + st->sy); for(int i = 0; i < FOOD_COUNT; i++){ - if(st->snake-> == st->foodx && st->snake->y == st->food[i]){ - add_snake(st->snake, st->foodx[i], st->foody[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++){ @@ -78,18 +91,18 @@ int step_state(struct state* st){ return END_FOOD; } } + return END_CONTINUE; } } - for(struct snake* temp = st->snake->next != NULL; temp = temp->next){ - if(nx == temp->x && ny == temp->y){ + 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; } } - add_snake(st->snake, nx, ny); + st->snake = add_snake(st->snake, nx, ny); remove_snake(st->snake); return END_CONTINUE; } -