-
Notifications
You must be signed in to change notification settings - Fork 0
/
Map.cpp
149 lines (115 loc) · 2.4 KB
/
Map.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include <fstream>
#include <iostream>
#include <sstream>
#include "Map.hpp"
#include "constants.hpp"
#include "default_files.hpp"
using namespace sf;
using std::max;
using std::ofstream;
using std::ifstream;
std::vector<uint32_t> Map::palette;
Map::Map()
{
}
Map::Map(const std::string& map_name)
: name(map_name)
{
std::cout << "Map: Loading map: " << map_name << std::endl;
if (!load()) {
std::cout << "Map: Failed to load map: " << map_name << std::endl;
}
}
void Map::render(RenderWindow& window)
{
for (Brick& b : bricks) {
b.draw(window);
}
}
bool Map::load()
{
ifstream map_file(name);
std::string line;
int y = 0;
int type = 0;
unsigned int color_index = 0;
bricks.clear();
padding_bricks.clear();
size = Vector2u();
if (!map_file) {
return false;
}
if (palette.size() == 0) {
loadPalette();
}
while (!map_file.eof()) {
std::getline(map_file, line);
std::istringstream stream(line);
int x = 0;
while (!stream.eof()) {
stream >> type;
stream >> color_index;
if (map_file.eof()) {
return true;
} else if (map_file.fail()) {
return false;
}
Color color;
if (color_index < palette.size()) {
color = Color(palette[color_index]);
} else {
color = Color::Red; // best color
}
Brick b(Color(color), Vector2f(x, y), Brick::Type(type));
if (type == 0) {
padding_bricks.push_back(b);
} else {
bricks.push_back(b);
}
x += SIZE_X;
}
y += SIZE_Y;
}
return true;
}
Vector2u Map::getSize()
{
float x = 0, y = 0;
if (size == Vector2u()) {
for (const Brick& b : bricks) {
x = std::max(x, b.x);
y = std::max(y, b.y);
}
for (const Brick& b : padding_bricks) {
x = std::max(x, b.x);
y = std::max(y, b.y);
}
// The coordinates are the position of the top-left corner of each brick
x += SIZE_X;
y += SIZE_Y;
size = Vector2u(int(x), int(y) + VOID_SIZE);
}
return size;
}
void Map::loadPalette() {
ifstream palette_file("palette.list");
if (!palette_file) {
ofstream npalette("palette.list", ofstream::out | ofstream::trunc);
npalette << default_palette_str;
npalette.close();
palette_file.open("palette.list");
}
std::string line;
uint32_t color;
while (true) {
std::getline(palette_file, line);
if (line.empty()) {
break;
}
line = line.substr(0, line.find(" "));
line += "FF";
std::stringstream stream(line);
stream >> std::hex >> color;
palette.push_back(color);
}
}