90 lines
2.7 KiB
C
90 lines
2.7 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include "game.h"
|
|
|
|
struct snake* add_snake(struct snake* s, int x, int y) {
|
|
struct snake* n = malloc(sizeof(struct snake));
|
|
n->x = x; n->y = y; n->next = s;
|
|
return n;
|
|
}
|
|
|
|
struct snake* remove_snake(struct snake* s) {
|
|
if (!s || !s->next) { if (s) free(s); return NULL; }
|
|
struct snake* curr = s;
|
|
while (curr->next->next) curr = curr->next;
|
|
free(curr->next);
|
|
curr->next = NULL;
|
|
return s;
|
|
}
|
|
|
|
int is_snake(struct snake* s, int x, int y) {
|
|
for (; s; s = s->next) if (s->x == x && s->y == y) return 1;
|
|
return 0;
|
|
}
|
|
|
|
void free_snake(struct snake* s) {
|
|
while (s) { struct snake* t = s; s = s->next; free(t); }
|
|
}
|
|
|
|
int step_state(struct state* s) {
|
|
int nx = s->snake->x + s->sx;
|
|
int ny = s->snake->y + s->sy;
|
|
|
|
if (nx < 0 || nx >= s->width || ny < 0 || ny >= s->height) return END_WALL;
|
|
if (is_snake(s->snake, nx, ny)) return END_SNAKE;
|
|
|
|
for (int i = 0; i < FOOD_COUNT; i++) {
|
|
if (s->foodx[i] == nx && s->foody[i] == ny) {
|
|
s->foodx[i] = -1; s->foody[i] = -1;
|
|
s->snake = add_snake(s->snake, nx, ny);
|
|
for (int j = 0; j < FOOD_COUNT; j++) if (s->foodx[j] >= 0) return END_CONTINUE;
|
|
return END_FOOD;
|
|
}
|
|
}
|
|
|
|
s->snake = add_snake(s->snake, nx, ny);
|
|
s->snake = remove_snake(s->snake);
|
|
return END_CONTINUE;
|
|
}
|
|
|
|
void draw(struct state* s) {
|
|
printf("\033[H\033[J");
|
|
for (int y = 0; y < s->height; y++) {
|
|
for (int x = 0; x < s->width; x++) {
|
|
if (s->snake->x == x && s->snake->y == y) printf("O");
|
|
else if (is_snake(s->snake->next, x, y)) printf("o");
|
|
else {
|
|
int f = 0;
|
|
for (int i = 0; i < FOOD_COUNT; i++)
|
|
if (s->foodx[i] == x && s->foody[i] == y) { printf("*"); f = 1; break; }
|
|
if (!f) printf(".");
|
|
}
|
|
}
|
|
printf("\n");
|
|
}
|
|
printf("Controls: w/a/s/d + Enter. Quit: q\n");
|
|
}
|
|
|
|
int main() {
|
|
struct state s = {NULL, {2, 5, 10, 15, 18}, {2, 8, 3, 7, 1}, 1, 0, 20, 10};
|
|
s.snake = add_snake(NULL, 10, 5);
|
|
int res = END_CONTINUE;
|
|
char c;
|
|
|
|
while (res == END_CONTINUE) {
|
|
draw(&s);
|
|
if (scanf(" %c", &c) != 1 || c == 'q') break;
|
|
if (c == 'w') { s.sx = 0; s.sy = -1; }
|
|
else if (c == 's') { s.sx = 0; s.sy = 1; }
|
|
else if (c == 'a') { s.sx = -1; s.sy = 0; }
|
|
else if (c == 'd') { s.sx = 1; s.sy = 0; }
|
|
res = step_state(&s);
|
|
}
|
|
|
|
if (res == END_WALL) printf("Game Over: Wall hit!\n");
|
|
else if (res == END_SNAKE) printf("Game Over: Self bite!\n");
|
|
else if (res == END_FOOD) printf("Victory: All food eaten!\n");
|
|
|
|
free_snake(s.snake);
|
|
return 0;
|
|
} |