This commit is contained in:
Roman Khaliavka 2025-04-23 14:39:01 +00:00
parent fb7f6cdc18
commit 380c0a5779

134
a3/main.c
View File

@ -1,108 +1,68 @@
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <ncurses.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "snake.h" #include "snake.h"
#include "world.h" #include "world.h"
#define HIGHSCORE_FILE "highscore.txt" void render(const struct state* state){
system("clear");
int read_highscore(){ for(int y = 0; y < state->height; y++){
FILE* file = fopen(HIGHSCORE_FILE, "r"); for(int x = 0; x < state->width; x++){
if (!file) return 0; if(is_snake(state->snake, x, y)){
int score; printf("O");
fscanf(file, "%d", &score); }else if(is_food_at(state, x, y)){
fclose(file); printf("@");
return score; }else{
printf(" ");
}
}
printf("\n");
}
} }
void write_highscore(int score){ int get_key(){
FILE* file = fopen(HIGHSCORE_FILE, "w"); int ch;
if (file){ if (scanf("%c", &ch) != 1){
fprintf(file, "%d\n", score); return -1;
fclose(file);
} }
return ch;
} }
int main(){ int main(){
srand(time(NULL));
initscr();
start_color();
init_pair(1, COLOR_GREEN, COLOR_BLACK);
init_pair(2, COLOR_RED, COLOR_BLACK);
cbreak();
noecho();
curs_set(0);
keypad(stdscr, TRUE);
nodelay(stdscr, TRUE);
struct state game; struct state game;
game.width = 40; init_game(&game);
game.height = 20; int ch;
game.sx = 1; while(1){
game.sy = 0;
game.snake = add_snake(NULL, game.width / 2, game.height / 2);
place_food(&game);
int score = 0;
int highscore = read_highscore();
int running = 1;
while(running){
int ch = getch();
switch(ch){
case KEY_UP:
if (game.sy != 1) { game.sx = 0; game.sy = -1; }
break;
case KEY_DOWN:
if (game.sy != -1) { game.sx = 0; game.sy = 1; }
break;
case KEY_LEFT:
if (game.sx != 1) { game.sx = -1; game.sy = 0; }
break;
case KEY_RIGHT:
if (game.sx != -1) { game.sx = 1; game.sy = 0; }
break;
case 'q':
running = 0;
continue;
}
int status = step_state(&game);
if(status == END_CONTINUE || status == END_FOOD){
struct snake* head = game.snake;
int length = 0;
while (head) {
length++;
head = head->next;
}
score = length - 1;
}
render(&game); render(&game);
mvprintw(game.height, 0, "Score: %d High Score: %d (q to quit)", score, highscore); ch = get_key();
refresh();
if(status != END_CONTINUE){ if(ch == 'q'){
if (score > highscore) {
write_highscore(score);
mvprintw(game.height + 1, 0, "New High Score! %d", score);
}else{
mvprintw(game.height + 1, 0, "Game Over! Score: %d", score);
}
mvprintw(game.height + 2, 0, "Press any key to exit...");
nodelay(stdscr, FALSE);
getch();
break; break;
} }
usleep(150000); 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);
} }
endwin(); printf("Game Over\n");
free_snake(game.snake);
return 0; return 0;
} }