-
Notifications
You must be signed in to change notification settings - Fork 0
/
SaveGame.cpp
97 lines (82 loc) · 2.12 KB
/
SaveGame.cpp
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
93
94
95
96
97
#include "ChessGame.h"
#include <fstream>
bool saveFileExists() {
ifstream file("savegame.txt");
return file.good();
}
void askSaveGame(char board[][8], char beatenPiecesBlack[16], char beatenPiecesWhite[16], Color color) {
while (true) {
system("cls");
string input;
cout << "Do you want to save the game? (y/n): ";
cin >> input;
if (input == "y") {
saveGame(board, beatenPiecesBlack, beatenPiecesWhite, color);
break;
}
else if (input == "n") {
break;
}
}
}
void askLoadGame(char board[][8], char beatenPiecesBlack[16], char beatenPiecesWhite[16], Color* color) {
if (!saveFileExists()) return;
while (true) {
system("cls");
string input;
cout << "Do you want to load the last game? (y/n): ";
cin >> input;
if (input == "y") {
loadGame(board, beatenPiecesBlack, beatenPiecesWhite, color);
break;
}
else if (input == "n") {
break;
}
}
}
void saveGame(char board[][8], char beatenPiecesBlack[16], char beatenPiecesWhite[16], Color color) {
fstream file;
file.open("savegame.txt", ios::out | ios::trunc);
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
file << board[i][j];
}
}
file << endl;
file << beatenPiecesBlack << endl;
file << beatenPiecesWhite << endl;
file << int(color);
file.close();
}
void loadGame(char board[][8], char beatenPiecesBlack[16], char beatenPiecesWhite[16], Color *color) {
fstream file;
file.open("savegame.txt", ios::in);
if (!file) {
return;
}
string boardLine, beatenPiecesBlackLine, beatenPiecesWhiteLine, colorLine;
Vector2D pos = { 0, 0 };
while (getline(file, boardLine) &&
getline(file, beatenPiecesBlackLine) &&
getline(file, beatenPiecesWhiteLine) &&
getline(file, colorLine)) {
for (char temp : boardLine) {
cout << temp;
board[pos.y][pos.x] = temp;
pos.x++;
if (pos.x >= 8) {
pos.y++;
pos.x = 0;
}
}
for (int i = 0; i < beatenPiecesBlackLine.length(); i++) {
beatenPiecesBlack[i] = beatenPiecesBlackLine[i];
}
for (int i = 0; i < beatenPiecesWhiteLine.length(); i++) {
beatenPiecesWhite[i] = beatenPiecesWhiteLine[i];
}
*color = (Color)stoi(colorLine);
}
file.close();
}