This commit is contained in:
Roman Khaliavka 2025-04-23 15:38:33 +00:00
parent e6fcb27347
commit 673813d9d8

View File

@ -1,68 +1,40 @@
#include "world.h"
#include "snake.h"
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h> #include <unistd.h>
#include "snake.h"
#include "world.h"
void render(const struct state* state){
system("clear");
for(int y = 0; y < state->height; y++){
for(int x = 0; x < state->width; x++){
if(is_snake(state->snake, x, y)){
printf("O");
}else if(is_food_at(state, x, y)){
printf("@");
}else{
printf(" ");
}
}
printf("\n");
}
}
int get_key(){
int ch;
if (scanf("%c", &ch) != 1){
return -1;
}
return ch;
}
int main(){ int main(){
struct state game; struct state game_world;
init_game(&game);
int ch; // Initialize the game world with dimensions 20x20
init_world(&game_world, 20, 20);
// Run the game loop until the game ends
while(1){ while(1){
render(&game); print_world(&game_world);
ch = get_key();
if(ch == 'q'){ // Update the game state based on snake movement
int game_status = step_state(&game_world);
// Check the result of the move
if (game_status == END_WALL) {
printf("Game Over: Hit the Wall!\n");
break;
}
if (game_status == END_SNAKE) {
printf("Game Over: Snake hit itself!\n");
break;
}
if (game_status == END_FOOD) {
printf("Congratulations! You ate all the food!\n");
break; break;
} }
if(ch == 'w'){ sleep(1);
game.sy = -1;
game.sx = 0;
}else if(ch == 's'){
game.sy = 1;
game.sx = 0;
}else if(ch == 'a'){
game.sx = -1;
game.sy = 0;
}else if(ch == 'd'){
game.sx = 1;
game.sy = 0;
}
int result = step_state(&game);
if (result != END_CONTINUE) {
break;
}
usleep(100000);
} }
printf("Game Over\n"); free_snake(game_world.snake);
return 0; return 0;
} }