pvjc24/a2/snake.c

87 lines
2.2 KiB
C
Raw Normal View History

2024-04-08 13:32:31 +00:00
#include "snake.h"
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#define WIDTH 20
#define HEIGHT 10
2024-04-08 13:35:27 +00:00
#define INITIAL_SNAKE_LENGTH 5
#define FOOD_COUNT 20
2024-04-08 13:32:31 +00:00
2024-04-08 13:35:27 +00:00
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
2024-04-08 13:32:31 +00:00
srand(time(NULL));
for (int i = 0; i < FOOD_COUNT; i++) {
2024-04-08 13:35:27 +00:00
state->foodx[i] = rand() % WIDTH;
state->foody[i] = rand() % HEIGHT;
2024-04-08 13:32:31 +00:00
}
2024-04-08 13:35:27 +00:00
// Initialize state parameters
state->sx = 1;
state->sy = 0;
state->width = WIDTH;
state->height = HEIGHT;
2024-04-08 13:32:31 +00:00
}
2024-04-08 13:35:27 +00:00
void print_world(struct state *state) {
2024-04-08 13:32:31 +00:00
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
2024-04-08 13:35:27 +00:00
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) {
2024-04-08 13:32:31 +00:00
printf("x");
2024-04-08 13:35:27 +00:00
} else if (is_food) {
printf("*");
2024-04-08 13:32:31 +00:00
} else {
2024-04-08 13:35:27 +00:00
printf(" ");
2024-04-08 13:32:31 +00:00
}
}
printf("\n");
}
}
int main() {
struct state game_state;
2024-04-08 13:35:27 +00:00
initialize_world(&game_state);
2024-04-08 13:32:31 +00:00
while (1) {
2024-04-08 13:35:27 +00:00
system("clear");
2024-04-08 13:32:31 +00:00
print_world(&game_state);
2024-04-08 13:35:27 +00:00
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");
2024-04-08 13:32:31 +00:00
}
break;
}
}
free_snake(game_state.snake);
return EXIT_SUCCESS;
}