commit
This commit is contained in:
parent
9a31fd09f8
commit
64578a9e8c
43
du4/snake.c
43
du4/snake.c
@ -1,14 +1,6 @@
|
|||||||
#include "snake.h"
|
#include "snake.h"
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
|
||||||
static struct snake* get_tail(struct snake* snake) {
|
|
||||||
struct snake* tail = snake;
|
|
||||||
while (tail != NULL && tail->next != NULL) {
|
|
||||||
tail = tail->next;
|
|
||||||
}
|
|
||||||
return tail;
|
|
||||||
}
|
|
||||||
|
|
||||||
struct snake* add_snake(struct snake* snake, int x, int y) {
|
struct snake* add_snake(struct snake* snake, int x, int y) {
|
||||||
struct snake* head = calloc(1, sizeof(struct snake));
|
struct snake* head = calloc(1, sizeof(struct snake));
|
||||||
if (head == NULL) {
|
if (head == NULL) {
|
||||||
@ -57,25 +49,38 @@ int is_snake(struct snake* snake, int x, int y) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int step_state(struct state* st) {
|
int step_state(struct state* st) {
|
||||||
|
if (st == NULL || st->snake == NULL) {
|
||||||
|
return END_USER;
|
||||||
|
}
|
||||||
int nx = st->snake->x + st->sx;
|
int nx = st->snake->x + st->sx;
|
||||||
int ny = st->snake->y + st->sy;
|
int ny = st->snake->y + st->sy;
|
||||||
int ate_food = nx == st->foodx && ny == st->foody;
|
int food_index = -1;
|
||||||
struct snake* tail = get_tail(st->snake);
|
|
||||||
|
|
||||||
if (nx < 0 || ny < 0 || nx >= st->width || ny >= st->height) {
|
if (nx < 0 || ny < 0 || nx >= st->width || ny >= st->height) {
|
||||||
return END_SNAKE;
|
return END_WALL;
|
||||||
}
|
}
|
||||||
if (is_snake(st->snake, nx, ny)) {
|
if (is_snake(st->snake, nx, ny)) {
|
||||||
if (ate_food || tail == NULL || tail->x != nx || tail->y != ny) {
|
return END_SNAKE;
|
||||||
return END_GAME;
|
}
|
||||||
|
for (int i = 0; i < FOOD_COUNT; i++) {
|
||||||
|
if (st->foodx[i] == nx && st->foody[i] == ny) {
|
||||||
|
food_index = i;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
st->snake = add_snake(st->snake, nx, ny);
|
st->snake = add_snake(st->snake, nx, ny);
|
||||||
if (st->snake == NULL) {
|
if (food_index >= 0) {
|
||||||
return END_GAME;
|
st->foodx[food_index] = -1;
|
||||||
}
|
st->foody[food_index] = -1;
|
||||||
if (!ate_food) {
|
|
||||||
st->snake = remove_snake(st->snake);
|
for (int i = 0; i < FOOD_COUNT; i++) {
|
||||||
}
|
if (st->foodx[i] >= 0 && st->foody[i] >= 0) {
|
||||||
|
return END_CONTINUE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return END_FOOD;
|
||||||
|
}
|
||||||
|
st->snake = remove_snake(st->snake);
|
||||||
return END_CONTINUE;
|
return END_CONTINUE;
|
||||||
}
|
}
|
||||||
Loading…
Reference in New Issue
Block a user