yaecs/
entity.rs

1use anymap::AnyMap;
2use std::collections::HashMap;
3
4/// An `Entity` is simply an identifier for a bag of components. In general, `System`s operate on
5/// a subset of all entities that posess components the `System` is interested in.
6#[derive(Debug)]
7pub struct Entity {
8    /// Bag of components
9    pub components: AnyMap,
10    /// Tags (metadata about this entity)
11    pub tags: HashMap<&'static str, String>,
12}
13
14impl Entity {
15    /// Creates a new `Entity` with an empty bag of components
16    pub fn new(label: String) -> Entity {
17        let mut tags = HashMap::new();
18        tags.insert("label", label);
19        Entity {
20            components: AnyMap::new(),
21            tags: tags,
22        }
23    }
24
25    pub fn label(&self) -> &str {
26        self.tags.get("label").unwrap()
27    }
28}
29
30impl PartialEq for Entity {
31    fn eq(&self, other: &Entity) -> bool {
32        self.label() == other.label()
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use ::EntityBuilder;
39
40    #[derive(Debug, PartialEq)]
41    struct TestComponent(pub u8);
42
43    #[derive(Debug, PartialEq)]
44    struct AnotherComponent;
45
46    #[test]
47    fn entity_can_contain_components() {
48        let entity = EntityBuilder::create_str("test")
49            .add(TestComponent(1))
50            .build();
51        assert_eq!(entity.tags.get("label"), Some(&String::from("test")));
52        assert_eq!(entity.components.get::<TestComponent>(),
53                   Some(&TestComponent(1)));
54    }
55
56    #[test]
57    fn entity_has_components_works() {
58        let entity = EntityBuilder::create_str("test")
59            .add(TestComponent(1))
60            .build();
61        assert!(entity.components.contains::<TestComponent>());
62        assert!(!entity.components.contains::<AnotherComponent>());
63
64        let entity = EntityBuilder::create_str("test")
65            .add(AnotherComponent)
66            .build();
67        assert!(!entity.components.contains::<TestComponent>());
68        assert!(entity.components.contains::<AnotherComponent>());
69    }
70}