rust-sokoban/src/components.rs

118 lines
2.4 KiB
Rust
Raw Normal View History

2020-07-23 18:12:52 -04:00
use specs::{Component, NullStorage, VecStorage, World, WorldExt};
2020-07-24 17:55:38 -04:00
use std::fmt;
use std::fmt::Display;
2020-07-23 18:12:52 -04:00
2020-07-24 18:00:23 -04:00
#[derive(PartialEq)]
2020-07-24 14:55:49 -04:00
pub enum BoxColor {
Red,
Blue,
2020-07-28 10:04:44 -04:00
Green,
Brown,
2020-07-24 14:55:49 -04:00
}
impl Display for BoxColor {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2020-07-24 17:55:38 -04:00
fmt.write_str(match self {
BoxColor::Red => "red",
BoxColor::Blue => "blue",
2020-07-28 10:04:44 -04:00
BoxColor::Green => "green",
BoxColor::Brown => "brown",
2020-07-24 17:55:38 -04:00
})?;
Ok(())
2020-07-24 14:55:49 -04:00
}
}
2020-07-24 18:56:48 -04:00
pub enum RenderableKind {
Static,
Animated,
}
2020-07-23 18:12:52 -04:00
#[derive(Debug, Component, Clone, Copy)]
#[storage(VecStorage)]
pub struct Position {
pub x: u8,
pub y: u8,
pub z: u8,
}
impl Position {
pub fn new(x: u8, y: u8) -> Self {
Position { x, y, z: 0 }
}
2020-07-24 14:55:49 -04:00
pub fn with_z(self, z: u8) -> Self {
Position { z, ..self }
}
2020-07-23 18:12:52 -04:00
}
#[derive(Component)]
#[storage(VecStorage)]
pub struct Renderable {
2020-07-24 18:56:48 -04:00
paths: Vec<String>,
}
impl Renderable {
pub fn new_static(path: String) -> Self {
Self { paths: vec![path] }
}
pub fn new_animated(paths: Vec<String>) -> Self {
Self { paths }
}
pub fn kind(&self) -> RenderableKind {
match self.paths.len() {
0 => panic!("invalid renderable"),
1 => RenderableKind::Static,
_ => RenderableKind::Animated,
}
}
pub fn path(&self, path_index: usize) -> String {
// If we get asked for a path that is larger than the
// number of paths we actually have, we simply mod the index
// with the length to get an index that is in range
self.paths[path_index % self.paths.len()].clone()
}
2020-07-23 18:12:52 -04:00
}
#[derive(Component)]
#[storage(VecStorage)]
pub struct Wall {}
#[derive(Component)]
#[storage(VecStorage)]
pub struct Player {}
#[derive(Component)]
#[storage(VecStorage)]
2020-07-24 14:55:49 -04:00
pub struct Box {
pub color: BoxColor,
}
2020-07-23 18:12:52 -04:00
#[derive(Component)]
#[storage(VecStorage)]
2020-07-24 14:55:49 -04:00
pub struct BoxSpot {
pub color: BoxColor,
}
2020-07-23 18:12:52 -04:00
#[derive(Component, Default)]
#[storage(NullStorage)]
pub struct Movable;
#[derive(Component, Default)]
#[storage(NullStorage)]
pub struct Immovable;
pub fn register_components(world: &mut World) {
world.register::<Position>();
world.register::<Renderable>();
world.register::<Player>();
world.register::<Wall>();
world.register::<Box>();
world.register::<BoxSpot>();
world.register::<Movable>();
world.register::<Immovable>();
}