-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSaveGridAction.cpp
86 lines (65 loc) · 2.43 KB
/
SaveGridAction.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
#include "SaveGridAction.h"
#include"GameObject.h"
#include"Ladder.h"
#include"Snake.h"
#include"Card.h"
#include"Grid.h"
#include"Cell.h"
SaveGridAction::SaveGridAction(ApplicationManager* pApp) :Action(pApp) {
}
void SaveGridAction::ReadActionParameters() {
Grid* pGrid = pManager->GetGrid();
Input* pIn = pGrid->GetInput();
Output* pOut = pGrid->GetOutput();
pOut->PrintMessage("Save Grid: Enter file name:");
Filename = pIn->GetString(pOut);
pOut->ClearStatusBar();
}
void SaveGridAction::Execute() {
ReadActionParameters();
saveGrid.open(Filename); //opens the file to save into
Grid* pGrid = pManager->GetGrid();
if (!saveGrid.is_open())
{
pGrid->PrintErrorMessage("Error: Can't open file ! Click to continue ...");
return;
}
Cell* pCell; //points on a cell in the grid
CellPosition objPos; // the object position
int ladderCells[99]; //stores the cells numbers that contain ladders
int SnakeCells [99]; //stores the cells numbers that contain Snakes
int CardCells [99]; //stores the cells numbers that contain Cards
int c = 0, l = 0, s = 0; //conters for number of cards,ladders, snakes
for (int i = NumVerticalCells - 1; i >= 0; i--) //loop on the grid cells and count the objects & store their cell numbers in the arrays
{
for (int j = 0; j < NumHorizontalCells; j++) {
pCell = pGrid->GetCell(i, j);
if (pCell->HasLadder())
ladderCells[l++] = pCell->HasLadder()->GetPosition().GetCellNum();
else if (pCell->HasSnake())
SnakeCells[s++] = pCell->HasSnake()->GetPosition().GetCellNum();
else if (pCell->HasCard())
CardCells[c++]= pCell->HasCard()->GetPosition().GetCellNum();
}
}
// the following is storing the information in the file grid.txt as in the project document
saveGrid << l << endl;
for (int i = 0; i < l; i++) {
objPos = CellPosition::GetCellPositionFromNum(ladderCells[i]);
pGrid->GetCell(objPos.VCell(),objPos.HCell())->GetGameObject()->Save(saveGrid);
}
saveGrid << s << endl;
for (int i = 0; i < s; i++) {
objPos = CellPosition::GetCellPositionFromNum(SnakeCells[i]);
pGrid->GetCell(objPos.VCell(),objPos.HCell())->GetGameObject()->Save(saveGrid);
}
saveGrid << c << endl;
for (int i = 0; i < c; i++) {
objPos = CellPosition::GetCellPositionFromNum(CardCells[i]);
pGrid->GetCell(objPos.VCell(),objPos.HCell())->GetGameObject()->Save(saveGrid);
}
saveGrid.close(); // close the file
pGrid->PrintErrorMessage("Saved!...");
}
SaveGridAction:: ~SaveGridAction() {
}