commit
This commit is contained in:
parent
cf990ceacb
commit
64ae1d86cf
81
du4/program.c
Normal file
81
du4/program.c
Normal file
@ -0,0 +1,81 @@
|
|||||||
|
#include "snake.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* head = calloc(1, sizeof(struct snake));
|
||||||
|
if (head == NULL) {
|
||||||
|
return snake;
|
||||||
|
}
|
||||||
|
head->x = x;
|
||||||
|
head->y = y;
|
||||||
|
head->next = snake;
|
||||||
|
return head;
|
||||||
|
}
|
||||||
|
|
||||||
|
struct snake* remove_snake(struct snake* snake) {
|
||||||
|
if (snake == NULL) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
if (snake->next == NULL) {
|
||||||
|
free(snake);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
struct snake* prev = snake;
|
||||||
|
struct snake* last = snake->next;
|
||||||
|
while (last->next != NULL) {
|
||||||
|
prev = last;
|
||||||
|
last = last->next;
|
||||||
|
}
|
||||||
|
prev->next = NULL;
|
||||||
|
free(last);
|
||||||
|
return snake;
|
||||||
|
}
|
||||||
|
|
||||||
|
void free_snake(struct snake* sn) {
|
||||||
|
while (sn != NULL) {
|
||||||
|
struct snake* next = sn->next;
|
||||||
|
free(sn);
|
||||||
|
sn = next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int is_snake(struct snake* snake, int x, int y) {
|
||||||
|
for (struct snake* node = snake; node != NULL; node = node->next) {
|
||||||
|
if (node->x == x && node->y == y) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int step_state(struct state* st) {
|
||||||
|
int nx = st->snake->x + st->sx;
|
||||||
|
int ny = st->snake->y + st->sy;
|
||||||
|
int ate_food = nx == st->food_x && ny == st->food_y;
|
||||||
|
struct snake* tail = get_tail(st->snake);
|
||||||
|
|
||||||
|
if (nx < 0 || ny < 0 || nx >= st->width || ny >= st->height) {
|
||||||
|
return END_GAME;
|
||||||
|
}
|
||||||
|
if (is_snake(st->snake, nx, ny)) {
|
||||||
|
if (ate_food || tail == NULL || tail->x != nx || tail->y != ny) {
|
||||||
|
return END_GAME;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
st->snake = add_snake(st->snake, nx, ny);
|
||||||
|
if (st->snake == NULL) {
|
||||||
|
return END_GAME;
|
||||||
|
}
|
||||||
|
if (!ate_food) {
|
||||||
|
st->snake = remove_snake(st->snake);
|
||||||
|
}
|
||||||
|
return END_CONTINUE;
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user