use std::collections::HashMap;
pub trait GObj {
fn new() -> Self;
fn reset(&mut self, t: u8, ps: &[u32]);
}
pub struct GameObject<T>
where
T: GObj,
{
pub id: usize,
pub obj: T,
pub active: bool,
}
pub struct GameObjPool<T>
where
T: GObj,
{
pub map: HashMap<usize, usize>,
pub pool: Vec<GameObject<T>>,
pub prefix: String,
pub max_count: usize,
}
impl<T> GameObjPool<T>
where
T: GObj,
{
pub fn new(pre: &str, mc: usize) -> Self {
Self {
map: HashMap::new(),
pool: vec![],
prefix: pre.to_string(),
max_count: mc,
}
}
pub fn create_with_func<F>(&mut self, otype: u8, mut f: F)
where
F: FnMut(u8, &mut GameObject<T>),
{
let mut find = false;
for o in &mut self.pool {
if !o.active {
f(otype, o);
o.active = true;
find = true;
break;
}
}
if !find {
let l = self.pool.len();
let bo: T = T::new();
let mut o = GameObject {
id: l,
obj: bo,
active: true,
};
f(otype, &mut o);
self.pool.push(o);
}
}
pub fn create(&mut self, otype: u8, ps: &[u32]) {
self.create_with_func(otype, |t, po| {
po.obj.reset(t, ps);
});
}
pub fn update_active<F>(&mut self, mut f: F)
where
F: FnMut(&mut GameObject<T>),
{
for o in self.pool.iter_mut().filter(|o| o.active) {
f(o);
}
}
}