pvjc24/a2/snake.c
2024-04-08 15:32:31 +02:00

133 lines
3.7 KiB
C

#include "snake.h"
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#define WIDTH 20
#define HEIGHT 10
void initialize_food(int foodx[], int foody[]) {
srand(time(NULL));
for (int i = 0; i < FOOD_COUNT; i++) {
foodx[i] = rand() % WIDTH;
foody[i] = rand() % HEIGHT;
}
}
void print_world(struct state* state) {
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
if (is_snake(state->snake, x, y)) {
printf("x");
} else {
int food_found = 0;
for (int i = 0; i < FOOD_COUNT; i++) {
if (state->foodx[i] == x && state->foody[i] == y) {
if (state->foodx[i] >= 0 && state->foody[i] >= 0) {
printf("*");
} else {
printf(" ");
}
food_found = 1;
break;
}
}
if (!food_found) {
printf(" ");
}
}
}
printf("\n");
}
}
void move_snake(struct state* state, int dx, int dy) {
// Update snake position according to the direction
int new_x = state->snake->x + dx;
int new_y = state->snake->y + dy;
// Check if the new position is out of bounds
if (new_x < 0 || new_x >= WIDTH || new_y < 0 || new_y >= HEIGHT) {
printf("Snake hit the wall!\n");
exit(EXIT_SUCCESS);
}
// Check if the new position is on the snake
if (is_snake(state->snake, new_x, new_y)) {
printf("Snake hit itself!\n");
exit(EXIT_SUCCESS);
}
// Check if the new position is on food
for (int i = 0; i < FOOD_COUNT; i++) {
if (state->foodx[i] == new_x && state->foody[i] == new_y) {
state->foodx[i] = -1;
state->foody[i] = -1;
// Grow the snake
struct snake* new_head = add_snake(state->snake, new_x, new_y);
if (new_head == NULL) {
printf("Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
state->snake = new_head;
return;
}
}
// Move the snake
struct snake* new_head = add_snake(state->snake, new_x, new_y);
if (new_head == NULL) {
printf("Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
state->snake = new_head;
remove_snake(state->snake);
}
int main() {
// Initialize game state
struct state game_state;
game_state.snake = add_snake(NULL, WIDTH / 2, HEIGHT / 2);
if (game_state.snake == NULL) {
printf("Memory allocation failed!\n");
return EXIT_FAILURE;
}
game_state.width = WIDTH;
game_state.height = HEIGHT;
game_state.sx = 1;
game_state.sy = 0;
initialize_food(game_state.foodx, game_state.foody);
// Main game loop
while (1) {
system("clear"); // Clear the console
print_world(&game_state);
// Check if all food is eaten
int food_eaten = 1;
for (int i = 0; i < FOOD_COUNT; i++) {
if (game_state.foodx[i] >= 0 && game_state.foody[i] >= 0) {
food_eaten = 0;
break;
}
}
if (food_eaten) {
printf("All food eaten! You win!\n");
break;
}
// Move the snake according to the direction
move_snake(&game_state, game_state.sx, game_state.sy);
// Delay for a short time to slow down the game
// Adjust this value to change the game speed
usleep(200000); // 200 milliseconds
}
// Free memory
free_snake(game_state.snake);
return EXIT_SUCCESS;
}