cirno-puzzle/src/level.cpp

112 lines
2.6 KiB
C++
Raw Normal View History

2020-02-19 12:50:09 -05:00
#include "level.h"
2020-03-15 17:57:39 -04:00
#include <fstream>
#include <cstring>
2020-02-20 13:34:41 -05:00
2020-03-15 17:57:39 -04:00
void Level::prepareCellInstances()
2020-02-20 13:34:41 -05:00
{
2020-03-15 17:57:39 -04:00
default_cells[PASSABLE_CELL] = new PassableCell();
default_cells[WATER_CELL] = new WaterCell();
default_cells[WALL_CELL] = new WallCell();
default_cells[CHARGE_CELL] = new ChargeCell();
default_cells[EXIT_CELL] = new ExitCell();
default_cells[TELEPORT_CELL] = new TeleportCell();
default_cells[TRIGGER_CELL] = new TriggerCell();
2020-02-20 13:34:41 -05:00
}
2020-03-15 17:57:39 -04:00
void Level::readMap(std::ifstream &file)
2020-02-20 13:34:41 -05:00
{
2020-03-15 17:57:39 -04:00
int i;
for (coordinate j = 0; j < map.size(); ++j)
{
for (coordinate k = 0; k < map[j].size(); ++k)
{
file >> i;
2020-03-16 10:30:30 -04:00
map[j][k].reset(default_cells[i]);
2020-03-15 17:57:39 -04:00
map[j][k]->setPosition(j, k);
}
}
}
2020-03-16 10:30:30 -04:00
template<typename D, typename B> // [D]erived - [B]ase
unique_ptr<D> static_unique_pointer_cast (unique_ptr<B>&& old)
{
return unique_ptr<D>{static_cast<D*>(old.release())};
}
2020-03-15 17:57:39 -04:00
Level::Level(const std::string &map_file)
{
prepareCellInstances();
std::ifstream file;
file.open(map_file);
std::string cur_line;
while (getline(file, cur_line))
{
// need fix; see std::string.compare
if (strstr(cur_line.data(), "size") != NULL)
{
file >> level_width >> level_height;
map.resize(level_height);
for (Row &row : map)
row.resize(level_width);
}
else if (strstr(cur_line.data(), "map") != NULL)
{
readMap(file);
}
else if (strstr(cur_line.data(), "teleport") != NULL)
{
coordinate src_row, src_col;
coordinate dest_row, dest_col;
file >> src_row >> src_col >> dest_row >> dest_col;
2020-03-16 10:30:30 -04:00
auto teleport_cell = static_unique_pointer_cast<TeleportCell>(std::move(map[src_row][src_col]));
teleport_cell->setDestination(dest_row, dest_col);
map[src_row][src_col] = std::move(teleport_cell);
2020-03-15 17:57:39 -04:00
}
}
}
Level::~Level()
{
for (Cell *cell : default_cells)
delete cell;
}
size_t Level::width() const
{
return level_width;
}
size_t Level::height() const
{
return level_height;
}
void Level::placeBridge(coordinate row, coordinate col)
{
2020-03-16 10:30:30 -04:00
map[row][col] = std::make_unique<PassableCell>(row, col, palette::Black);
2020-03-15 17:57:39 -04:00
}
void Level::removeCharge(coordinate row, coordinate col)
{
2020-03-16 10:30:30 -04:00
map[row][col] = std::make_unique<PassableCell>(row, col, color_ground);
2020-02-19 12:50:09 -05:00
}
2020-02-21 16:55:13 -05:00
Map& Level::mapArray()
{
return map;
}
2020-03-15 11:02:37 -04:00
sf::Color Level::defaultGroundColor()
{
return color_ground;
}
void Level::setDefaultGroundColor(const sf::Color &color)
{
color_ground = color;
}