This commit is contained in:
Vadym Afanasiev 2026-04-16 20:42:49 +00:00
parent ac44715755
commit 15e179b4c6

View File

@ -1,11 +1,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define FOOD_COUNT 5
#define WIDTH 20
#define HEIGHT 10
struct snake {
int x;
@ -37,9 +33,6 @@ int is_snake(struct snake* snake, int x, int y);
void free_snake(struct snake* sn);
int step_state(struct state* state);
void display_game(struct state* state);
void start_game(struct state* game);
struct snake* add_snake(struct snake* snake, int x, int y) {
struct snake* new_part = (struct snake*)malloc(sizeof(struct snake));
new_part->x = x;
@ -134,16 +127,10 @@ int step_state(struct state* state) {
}
void display_game(struct state* game) {
system("clear");
printf("SNAKE GAME - Simple Version\n");
printf("================================\n\n");
printf("SNAKE GAME\n");
for (int x = 0; x < WIDTH + 2; x++) printf("#");
printf("\n");
for (int y = 0; y < HEIGHT; y++) {
printf("#");
for (int x = 0; x < WIDTH; x++) {
for (int y = 0; y < 10; y++) {
for (int x = 0; x < 20; x++) {
int head = (game->snake->x == x && game->snake->y == y);
int body = is_snake(game->snake->next, x, y);
int food = 0;
@ -160,26 +147,22 @@ void display_game(struct state* game) {
else if (food) printf("F");
else printf(" ");
}
printf("#\n");
printf("\n");
}
for (int x = 0; x < WIDTH + 2; x++) printf("#");
printf("\n");
}
void start_game(struct state* game) {
game->snake = add_snake(NULL, WIDTH / 2, HEIGHT / 2);
game->snake = add_snake(game->snake, WIDTH / 2 - 1, HEIGHT / 2);
game->snake = add_snake(NULL, 10, 5);
game->snake = add_snake(game->snake, 9, 5);
game->sx = 1;
game->sy = 0;
game->width = WIDTH;
game->height = HEIGHT;
game->width = 20;
game->height = 10;
srand(time(NULL));
for (int i = 0; i < FOOD_COUNT; i++) {
game->foodx[i] = rand() % WIDTH;
game->foody[i] = rand() % HEIGHT;
game->foodx[i] = 5 + i * 2;
game->foody[i] = 3 + i;
}
}
@ -187,31 +170,11 @@ int main(void) {
struct state game;
start_game(&game);
int playing = 1;
int tick = 0;
display_game(&game);
while (playing) {
display_game(&game);
tick++;
if (tick >= 3) {
tick = 0;
int status = step_state(&game);
if (status == END_WALL) {
printf("CRASH into wall!\n");
playing = 0;
} else if (status == END_SNAKE) {
printf("CRASH into yourself!\n");
playing = 0;
} else if (status == END_FOOD) {
printf("You ate all food. Good job!\n");
playing = 0;
}
}
usleep(80000);
}
int status = step_state(&game);
printf("Game status: %d\n", status);
free_snake(game.snake);