pvjc24/a2/snake.c
2024-04-08 15:35:27 +02:00

87 lines
2.2 KiB
C

#include "snake.h"
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#define WIDTH 20
#define HEIGHT 10
#define INITIAL_SNAKE_LENGTH 5
#define FOOD_COUNT 20
void initialize_world(struct state *state) {
// Initialize snake in the middle of the world
int initial_x = WIDTH / 2;
int initial_y = HEIGHT / 2;
state->snake = add_snake(NULL, initial_x, initial_y);
if (state->snake == NULL) {
fprintf(stderr, "Failed to initialize snake.\n");
exit(EXIT_FAILURE);
}
// Initialize food
srand(time(NULL));
for (int i = 0; i < FOOD_COUNT; i++) {
state->foodx[i] = rand() % WIDTH;
state->foody[i] = rand() % HEIGHT;
}
// Initialize state parameters
state->sx = 1;
state->sy = 0;
state->width = WIDTH;
state->height = HEIGHT;
}
void print_world(struct state *state) {
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
int is_snake_part = is_snake(state->snake, x, y);
int is_food = 0;
for (int i = 0; i < FOOD_COUNT; i++) {
if (state->foodx[i] == x && state->foody[i] == y) {
is_food = 1;
break;
}
}
if (is_snake_part) {
printf("x");
} else if (is_food) {
printf("*");
} else {
printf(" ");
}
}
printf("\n");
}
}
int main() {
struct state game_state;
initialize_world(&game_state);
while (1) {
system("clear");
print_world(&game_state);
usleep(200000);
// Move snake
int end_game_reason = step_state(&game_state);
if (end_game_reason != END_CONTINUE) {
if (end_game_reason == END_SNAKE) {
printf("Snake hit itself! Game over.\n");
} else if (end_game_reason == END_WALL) {
printf("Snake hit the wall! Game over.\n");
} else if (end_game_reason == END_FOOD) {
printf("All food eaten! You win!\n");
} else {
printf("Game over due to unknown reason.\n");
}
break;
}
}
free_snake(game_state.snake);
return EXIT_SUCCESS;
}