-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGame.cpp
More file actions
92 lines (71 loc) · 1.9 KB
/
Game.cpp
File metadata and controls
92 lines (71 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#import "Game.h"
// TODO: Let user continue playing after win.
Game::Game() {
playGrid = Grid();
this->setup();
}
void Game::setup() {
loadScoreData();
}
void Game::start() {
srand((unsigned) time(0)); // Seed rand with this so it is more random
this->newGame();
while (true) {
int uInput = getch();
if ( interface.inputIsDirectional(uInput)) {
this->playGrid.shift( interface.uInputMap[uInput] );
} else if (uInput == 'q') {
this->finish();
return;
} else if (uInput == 'r') {
this->newGame();
continue;
} else {
continue;
}
this->interface.printBoard(this->highScore);
if ( this->gameOver() || this->reached2048() ) {
this->interface.printEndMessage( this->gameOver() );
while (true) {
uInput = getch();
if (uInput == 'r') {
this->newGame();
break;
} else if (uInput == 'q') {
this->finish();
return;
}
}
}
}
}
void Game::loadScoreData() {
f = fopen(".scores", "r");
if (f) {
char line[256];
if (fgets(line, sizeof(line), f)) {
highScore = atoi(line);
fclose(f);
f = NULL;
}
}
}
void Game::newGame() {
playGrid.clear();
playGrid.initializeFreeTile(2);
playGrid.initializeFreeTile(2);
interface.printBoard(highScore);
}
bool Game::gameOver() {
return playGrid.isFull() && !playGrid.tilePairsExist();
}
bool Game::reached2048() {
return playGrid.gridContains2048Tile();
}
void Game::finish() {
highScore = playGrid.getScore() > highScore ? playGrid.getScore() : highScore;
f = fopen(".scores", "w");
fprintf(f, "%i", highScore);
fclose(f);
interface.close();
}