rust-sokoban/src/entities.rs

76 lines
2.0 KiB
Rust

use crate::components::*;
use specs::{Builder, EntityBuilder, World, WorldExt};
/// Cut down on the common syntax boilerplate
fn static_entity<'w>(
world: &'w mut World,
position: Position,
z: u8,
sprite_path: &str,
) -> EntityBuilder<'w> {
let sprite_path = sprite_path.to_string();
world
.create_entity()
.with(position.with_z(z))
.with(Renderable::new_static(sprite_path))
}
/// Cut down on animated entity boilerplate,
/// and accept vectors of `&str` and `String`
fn animated_entity<S>(
world: &mut World,
position: Position,
z: u8,
sprites: Vec<S>,
) -> EntityBuilder
where
S: Into<String>,
{
let sprites: Vec<String> = sprites.into_iter().map(|s| s.into()).collect();
world
.create_entity()
.with(position.with_z(z))
.with(Renderable::new_animated(sprites))
}
pub fn create_wall(world: &mut World, position: Position) {
static_entity(world, position, 10, "/images/wall.png")
.with(Wall {})
.with(Immovable)
.build();
}
pub fn create_floor(world: &mut World, position: Position) {
static_entity(world, position, 5, "/images/floor.png").build();
}
pub fn create_box(world: &mut World, position: Position, color: BoxColor) {
let mut sprites: Vec<String> = vec![];
for x in 1..=2 {
sprites.push(format!("/images/box_{}_{}.png", color, x));
}
animated_entity(world, position, 10, sprites)
.with(Box { color })
.with(Movable)
.build();
}
pub fn create_box_spot(world: &mut World, position: Position, color: BoxColor) {
let path = format!("/images/box_spot_{}.png", color);
static_entity(world, position, 9, &path)
.with(BoxSpot { color })
.build();
}
pub fn create_player(world: &mut World, position: Position) {
let sprites = vec![
"/images/player_1.png",
"/images/player_2.png",
"/images/player_3.png",
];
animated_entity(world, position, 10, sprites)
.with(Player {})
.with(Movable)
.build();
}