basic/
basic.rs

1use checs::component::ComponentVec;
2use checs::iter::LendingIterator;
3use checs::query::IntoQuery;
4use checs::world;
5use checs::Storage;
6
7struct Position {
8    x: u32,
9    y: u32,
10}
11struct Health(i32);
12#[derive(Debug)]
13struct Visible;
14
15#[derive(Default, Storage)]
16struct Storage {
17    positions: ComponentVec<Position>,
18    healths: ComponentVec<Health>,
19    visibles: ComponentVec<Visible>,
20}
21
22fn main() {
23    let mut world = world::World::<Storage>::new();
24
25    // Create entities with initial components.
26    // Either manually...
27    let player = world.spawn();
28    world.insert(player, Position { x: 0, y: 0 });
29    world.insert(player, Visible);
30    world.insert(player, Health(80));
31
32    // ...or by using the `spawn` macro...
33    let _obstacle = checs::spawn!(world, Position { x: 1, y: 1 }, Visible);
34    let _trap = checs::spawn!(world, Position { x: 2, y: 1 });
35
36    // ...or by using `spawn_with`.
37    let _enemy = world.spawn_with((Position { x: 1, y: 4 }, Visible, Health(100)));
38
39    let storage = world.storage_mut();
40
41    // Create a query over all entities that have `Position`, `Health`, and
42    // `Visible` components.
43    let query = (&storage.positions, &mut storage.healths, &storage.visibles).into_query();
44
45    query.for_each(|(_, (_, h, _))| {
46        h.0 += 10;
47    });
48
49    println!();
50
51    let query = (&storage.positions, &storage.healths, &storage.visibles).into_query();
52
53    query.for_each(|(e, (p, h, v))| {
54        println!("{e:?} is {v:?} at ({}, {}) with {} HP", p.x, p.y, h.0);
55    });
56}