underworld_core/components/worlds/
world.rs

1#[cfg(feature = "bevy_components")]
2use bevy_ecs::prelude::Component;
3#[cfg(feature = "serialization")]
4use serde::{Deserialize, Serialize};
5use uuid::Uuid;
6
7use crate::components::rooms::Room;
8
9#[derive(Clone, Debug)]
10#[cfg_attr(feature = "bevy_components", derive(Component))]
11#[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))]
12pub struct World {
13    pub rooms: Vec<Room>,
14    pub exit_graph: Vec<ExitMap>,
15}
16
17impl World {
18    pub fn add_room(&mut self, entrance_id: Uuid, room: Room) {
19        if let Some(exit_map) = self
20            .exit_graph
21            .iter_mut()
22            .find(|exit_map| exit_map.exit_id.eq(&entrance_id))
23        {
24            exit_map.set_room_id(room.id);
25
26            room.exits
27                .iter()
28                .filter(|exit| exit.id.ne(&entrance_id))
29                .map(|exit| ExitMap {
30                    exit_id: exit.id,
31                    left_room_id: Some(room.id),
32                    right_room_id: None,
33                })
34                .for_each(|exit_map| self.exit_graph.push(exit_map));
35            self.rooms.push(room);
36        }
37    }
38}
39
40#[derive(Clone, Debug)]
41#[cfg_attr(feature = "bevy_components", derive(Component))]
42#[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))]
43pub struct ExitMap {
44    pub exit_id: Uuid,
45    pub left_room_id: Option<Uuid>,
46    pub right_room_id: Option<Uuid>,
47}
48
49impl ExitMap {
50    pub fn other_room_id(&self, room_id: Uuid) -> Option<Uuid> {
51        if self.left_room_id.eq(&Some(room_id)) {
52            self.right_room_id
53        } else {
54            self.left_room_id
55        }
56    }
57
58    pub fn set_room_id(&mut self, room_id: Uuid) {
59        if self.left_room_id.is_none() {
60            self.left_room_id = Some(room_id);
61        } else if self.right_room_id.is_none() {
62            self.right_room_id = Some(room_id);
63        }
64    }
65}