summaryrefslogtreecommitdiff
path: root/ecs/examples/optional_component.rs
blob: bcc0c54164ab19ab89b65edba14a77df17664a0c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use ecs::phase::UPDATE as UPDATE_PHASE;
use ecs::{Component, Query, World};

#[derive(Debug, Component)]
struct PettingCapacity
{
    capacity_left: u32,
}

#[derive(Debug, Clone, Copy, Component)]
enum Aggressivity
{
    High,
    Medium,
    Low,
}

#[derive(Debug, Component)]
pub struct CatName
{
    name: String,
}

fn pet_cats(query: Query<(CatName, PettingCapacity, Option<Aggressivity>)>)
{
    for (cat_name, mut petting_capacity, aggressivity) in &query {
        let Some(aggressivity) = aggressivity else {
            println!("Aggressivity of cat {} is unknown. Skipping", cat_name.name);
            continue;
        };

        if let Aggressivity::High = *aggressivity {
            println!("Cat {} is aggressive. Skipping", cat_name.name);
            continue;
        }

        if petting_capacity.capacity_left == 0 {
            println!(
                "Cat {} have had enough of being petted. Skipping",
                cat_name.name
            );
            continue;
        }

        println!("Petting cat {}", cat_name.name);

        petting_capacity.capacity_left -= 1;
    }
}

fn main()
{
    let mut world = World::new();

    world.register_system(*UPDATE_PHASE, pet_cats);

    world.create_entity((
        CatName { name: "Jasper".to_string() },
        Aggressivity::Medium,
        PettingCapacity { capacity_left: 5 },
    ));

    world.create_entity((
        CatName { name: "Otto".to_string() },
        PettingCapacity { capacity_left: 9 },
    ));

    world.create_entity((
        CatName { name: "Carrie".to_string() },
        PettingCapacity { capacity_left: 2 },
        Aggressivity::High,
    ));

    world.create_entity((
        CatName { name: "Tommy".to_string() },
        PettingCapacity { capacity_left: 1 },
        Aggressivity::Low,
    ));

    world.step();
}