Skip to content

Commit

Permalink
Added load/saving on opening/closing
Browse files Browse the repository at this point in the history
  • Loading branch information
Zac8668 committed Jan 4, 2024
1 parent fd918df commit 6bde5e0
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
35 changes: 34 additions & 1 deletion src/chunk_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub struct ChunkManager {
}

//If true the direction is 1, if false the direction is -1
#[derive(Debug)]
pub enum MoveDir {
X(i32),
Y(i32),
Expand Down Expand Up @@ -111,6 +112,29 @@ impl ChunkManager {
}
}

impl Drop for ChunkManager {
fn drop(&mut self) {
let file = fs::read("assets/worlds/world").unwrap_or_default();
let mut file_chunks: HashMap<IVec2, Chunk> =
bincode::deserialize(&file).unwrap_or_default();

for (pos, chunk) in &self.chunks {
if let Some(file_chunk) = file_chunks.get_mut(pos) {
*file_chunk = chunk.clone();
} else {
file_chunks.insert(*pos, chunk.clone());
}
}

let data = bincode::serialize(&file_chunks).unwrap();
//Save file
let _ = File::create("assets/worlds/world")
.unwrap()
.write(&data)
.unwrap();
}
}

impl std::ops::Index<ChunkPos> for ChunkManager {
type Output = Atom;
#[track_caller]
Expand Down Expand Up @@ -215,11 +239,20 @@ pub fn manager_setup(

let mut images_vec = vec![];
chunk_manager.pos = ivec2(-16, -16);

let file = fs::read("assets/worlds/world").unwrap_or_default();
let file_chunks: HashMap<IVec2, Chunk> = bincode::deserialize(&file).unwrap_or_default();

for (x, y) in (chunk_manager.pos.x..chunk_manager.pos.x + width)
.cartesian_product(chunk_manager.pos.y..chunk_manager.pos.y + height)
{
let index = ivec2(x, y);
let chunk = Chunk::new(Handle::default(), index);
let chunk;
if let Some(file_chunk) = file_chunks.get(&index) {
chunk = file_chunk.clone();
} else {
chunk = Chunk::new(Handle::default(), index);
}

let ent = add_chunk(&mut commands, &mut images, &mut chunk_manager, chunk, index);
images_vec.push(ent);
Expand Down
1 change: 0 additions & 1 deletion src/player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,6 @@ impl Plugin for PlayerPlugin {
(
update_player.after(chunk_manager_update),
update_player_sprite.after(update_actors),
update_manager_pos,
),
)
.insert_resource(SavingTask::default())
Expand Down

0 comments on commit 6bde5e0

Please sign in to comment.