From 1181e89cac1254a57884586ddc301eaebcb4043a Mon Sep 17 00:00:00 2001 From: Roman Khaliavka Date: Wed, 23 Apr 2025 14:13:47 +0000 Subject: [PATCH] a3 --- a3/main.c | 108 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 a3/main.c diff --git a/a3/main.c b/a3/main.c new file mode 100644 index 0000000..e86d45d --- /dev/null +++ b/a3/main.c @@ -0,0 +1,108 @@ +#include +#include +#include +#include +#include +#include "snake.h" +#include "world.h" + +#define HIGHSCORE_FILE "highscore.txt" + +int read_highscore(){ + FILE* file = fopen(HIGHSCORE_FILE, "r"); + if (!file) return 0; + int score; + fscanf(file, "%d", &score); + fclose(file); + return score; +} + +void write_highscore(int score){ + FILE* file = fopen(HIGHSCORE_FILE, "w"); + if (file){ + fprintf(file, "%d\n", score); + fclose(file); + } +} + +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; + game.width = 40; + game.height = 20; + game.sx = 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); + mvprintw(game.height, 0, "Score: %d High Score: %d (q to quit)", score, highscore); + refresh(); + + if(status != END_CONTINUE){ + 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; + } + + usleep(150000); + } + + endwin(); + free_snake(game.snake); + return 0; +}