I'm writing a map generator in Rust which will split the world into sections and then within those sections create rooms in order to connect these rooms. What I would normally do is have a list and then as I iterate through the list get the parent (if there is one) and then run some code to connect these rooms.
I'm struggling with the traversing through a list and getting the parent.
Here are the data structures I currently have:
struct MapSectionPosition {
x: f32,
y: f32,
}
struct MapSectionRect {
top_left: MapSectionPosition,
top_right: MapSectionPosition,
bottom_right: MapSectionPosition,
bottom_left: MapSectionPosition,
}
struct MapSection {
width: f32,
height: f32,
points: MapSectionRect,
}
struct RoomExit {
position: MapSectionPosition,
}
struct Room {
width: f32,
height: f32,
exit: RoomExit,
}
At the moment I'm using a linked list:
let mut rooms: LinkedList<Room> = LinkedList::new();
let room = Room {
width: section.width / 4.0,
height: section.height / 4.0,
exit: RoomExit {
position: MapSectionPosition { x: 20.0, y: 20.0 },
},
};
rooms.push_back(room);
I'm struggling to both iterate and get the parent, so I'm thinking this might not be the right data structure.
With some playing around I've found a hacky solution. Hopefully this will better illustrate what I'm trying to do and if there is something more elegant.
let mut previous_room: Option<&Room> = None;
for room in rooms.iter() {
match previous_room {
Some(p_room) => {
println!("previous {}", p_room.width);
println!("current {}", room.width);
println!("connected");
},
None => {
println!("no previous room");
}
}
previous_room = Some(room);
}
Something a little more elegant
If rooms are a slice, then we can use the windows
method to create an iterator to access the data in question.
let mut iter = rooms[..].windows(2);
while let Some([prev, next]) = iter.next() {
println!("prev - {}", prev.width);
println!("next - {}", next.width);
println!("done...")
}
This has been answered before in Are there equivalents to slice::chunks/windows for iterators to loop over pairs, triplets etc?