diff options
author | cflip <cflip@cflip.net> | 2022-03-21 21:48:11 -0600 |
---|---|---|
committer | cflip <cflip@cflip.net> | 2022-03-21 22:13:14 -0600 |
commit | 52a1ea81be11b8860e7f2b7141fcaf2329630b9f (patch) | |
tree | 45f70e7ec23837f520ae658f1e3cceba133f99f7 | |
parent | 0b7ad904f819293b5d5e6ab22d40f331ab94eea3 (diff) |
Implement simple level saving and loading
For now, it just reads and writes the width, height, and tile data to
'level.non'
-rw-r--r-- | src/level.cpp | 44 | ||||
-rw-r--r-- | src/level.h | 2 | ||||
-rw-r--r-- | src/main.cpp | 9 |
3 files changed, 55 insertions, 0 deletions
diff --git a/src/level.cpp b/src/level.cpp index e197d8e..bfbf6ae 100644 --- a/src/level.cpp +++ b/src/level.cpp @@ -1,4 +1,8 @@ #include "level.h" + +#include <fstream> +#include <iostream> + #include "train.h" #include "util.h" @@ -116,6 +120,46 @@ void Level::toggleTile(int x, int y) } } +static const char* DEFAULT_FILENAME = "level.non"; + +void Level::save() const +{ + std::ofstream outputStream(DEFAULT_FILENAME, std::ios::out | std::ios::binary); + if (!outputStream) { + std::cerr << "Failed to write level to " << DEFAULT_FILENAME << '\n'; + return; + } + + outputStream.write((char*)&m_width, 1); + outputStream.write((char*)&m_height, 1); + outputStream.write((char*)m_tiles, m_width * m_height); + outputStream.close(); + + std::cout << "Successfully saved level to " << DEFAULT_FILENAME << '\n'; +} + +void Level::load() +{ + std::ifstream inputStream(DEFAULT_FILENAME, std::ios::in | std::ios::binary); + if (!inputStream) { + std::cerr << "Failed to read level from " << DEFAULT_FILENAME << '\n'; + return; + } + + uint8_t width, height; + inputStream.read((char*)&width, 1); + inputStream.read((char*)&height, 1); + + int size = width * height; + inputStream.read((char*)m_tiles, size); + inputStream.close(); + + m_width = width; + m_height = height; + + printf("Successfully loaded %dx%d level from %s\n", width, height, DEFAULT_FILENAME); +} + TrackDirection ChooseDirection(Level& level, int x, int y) { if (!level.inBounds(x, y)) return NorthSouth; diff --git a/src/level.h b/src/level.h index 8c95f2f..39b5efd 100644 --- a/src/level.h +++ b/src/level.h @@ -41,6 +41,8 @@ public: void addVehicle(Train&); void toggleTile(int x, int y); + void save() const; + void load(); private: Bitmap& m_tileSprites; int m_width, m_height; diff --git a/src/main.cpp b/src/main.cpp index 9281b2c..152021e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -65,6 +65,15 @@ int main(int argc, char** argv) hoveredTile = ScreenToTile({ mx, my }); }); + window.onKeyDown([&](int keycode) { + if (keycode == 's') { + level.save(); + } + if (keycode == 'l') { + level.load(); + } + }); + while (!window.shouldClose()) { window.update(); bitmap.clear(0xff224466); |