a3
This commit is contained in:
parent
6bfac49484
commit
1181e89cac
108
a3/main.c
Normal file
108
a3/main.c
Normal file
@ -0,0 +1,108 @@
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include <ncurses.h>
|
||||
#include <stdio.h>
|
||||
#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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user