use bevy_kindly::*;
use bevy_ecs::prelude::*;
#[derive(EntityKind)]
struct Containable(Entity);
#[derive(Component, Default)]
struct Items(Vec<Containable>);
#[derive(Component)]
struct Capacity(usize);
#[derive(EntityKind)]
#[default_components(Items)]
#[components(Capacity)]
struct Container(Entity);
trait InsertIntoContainer {
fn insert_into_container(self, container: &Container) -> Self;
}
impl InsertIntoContainer for &mut EntityKindCommands<'_, '_, '_, Containable> {
fn insert_into_container(self, &Container(entity): &Container) -> Self {
let item = self.get();
self.commands().add(move |world: &mut World| {
let &Capacity(capacity) = world
.get::<Capacity>(entity)
.expect("container must have capacity");
let Items(items) = world
.get_mut::<Items>(entity)
.expect("container must have items")
.into_inner();
if items.len() < capacity {
items.push(item);
}
});
self
}
}
#[test]
fn it_works() {
use bevy_kindly::utils::Execute;
let mut world = World::new();
let container: Container = world
.execute(|_, mut commands| commands.spawn_with_kind::<Container>((Capacity(5),)).get());
assert!(world.entity(container.entity()).contains::<Capacity>());
assert!(world.entity(container.entity()).contains::<Items>());
world.execute(|_, mut commands| {
commands
.spawn_with_kind::<Containable>(())
.insert_into_container(&container);
});
assert_eq!(world.get::<Items>(container.entity()).unwrap().0.len(), 1);
}