a3
This commit is contained in:
parent
e6fcb27347
commit
673813d9d8
80
a3/main.c
80
a3/main.c
@ -1,68 +1,40 @@
|
||||
#include "world.h"
|
||||
#include "snake.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.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(){
|
||||
struct state game;
|
||||
init_game(&game);
|
||||
int ch;
|
||||
struct state game_world;
|
||||
|
||||
// Initialize the game world with dimensions 20x20
|
||||
init_world(&game_world, 20, 20);
|
||||
|
||||
// Run the game loop until the game ends
|
||||
while(1){
|
||||
render(&game);
|
||||
ch = get_key();
|
||||
print_world(&game_world);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
if(ch == 'w'){
|
||||
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);
|
||||
sleep(1);
|
||||
}
|
||||
|
||||
printf("Game Over\n");
|
||||
free_snake(game_world.snake);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user