pvjc24/a2/snake.c
2024-04-08 15:46:50 +02:00

85 lines
2.5 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "snake.h"
// Global variables to store the direction of the snake
int sx = 0; // Horizontal speed
int sy = 0; // Vertical speed
// Function to move the snake based on the direction
void move_snake(struct snake* head) {
// Update the position of the head based on the current speed
head->x += sx;
head->y += sy;
}
// Function to update the direction of the snake based on user input
void update_direction(int direction) {
switch(direction) {
case KEY_UP:
sx = 0;
sy = -1;
break;
case KEY_DOWN:
sx = 0;
sy = 1;
break;
case KEY_LEFT:
sx = -1;
sy = 0;
break;
case KEY_RIGHT:
sx = 1;
sy = 0;
break;
default:
break;
}
}
// Function to handle collision detection and game logic
int handle_collision(struct state* state) {
// Check if the new head position is within the bounds of the game area
if (state->snake->x < 0 || state->snake->x >= state->width || state->snake->y < 0 || state->snake->y >= state->height) {
return END_WALL; // End game if the head hits the wall
}
// Check if the new head position overlaps with the snake's body
if (is_snake(state->snake, state->snake->x, state->snake->y)) {
return END_SNAKE; // End game if the head collides with the snake's body
}
// Check if the new head position overlaps with any food item
for (int i = 0; i < FOOD_COUNT; i++) {
if (state->foodx[i] == state->snake->x && state->foody[i] == state->snake->y) {
// Mark the food item as eaten
state->foodx[i] = -1;
state->foody[i] = -1;
return END_CONTINUE; // Continue game if the snake eats food
}
}
// If none of the above conditions are met, continue the game
return END_CONTINUE;
}
// Function to initialize the game world
void initialize_world(struct state* state) {
// Initialize random seed
srand(time(NULL));
// Place the snake in the center of the game area
state->snake = malloc(sizeof(struct snake));
state->snake->x = state->width / 2;
state->snake->y = state->height / 2;
state->snake->next = NULL;
// Place 20 food items randomly in the game area
for (int i = 0; i < FOOD_COUNT; i++) {
state->foodx[i] = rand() % state->width;
state->foody[i] = rand() % state->height;
}
}