Created
May 12, 2019 22:53
-
-
Save ElectricCoffee/821fbbb71164d3e7a5249499a590fdab to your computer and use it in GitHub Desktop.
Dependencies include specs and specs-derive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use specs::prelude::*; | |
use specs_derive::*; | |
#[derive(Component)] | |
#[storage(VecStorage)] | |
struct Position { | |
x: i32, | |
y: i32, | |
} | |
struct Color(u8, u8, u8); | |
#[derive(Component)] | |
#[storage(VecStorage)] | |
struct Drawable { | |
char: char, | |
background_color: Color, | |
foreground_color: Color, | |
} | |
#[derive(Component)] | |
#[storage(VecStorage)] | |
struct Health { | |
max_health: i32, | |
current_health: i32, | |
} | |
struct Draw; | |
impl<'a> System<'a> for Draw { | |
type SystemData = (ReadStorage<'a, Position>, ReadStorage<'a, Drawable>); | |
fn run(&mut self, (pos, drawable): Self::SystemData) { | |
use specs::Join; | |
for (pos, drawable) in (&pos, &drawable).join() { | |
println!("{} at ({}, {})", drawable.char, pos.x, pos.y); | |
} | |
} | |
} | |
struct UpdatePos; | |
impl<'a> System<'a> for UpdatePos { | |
type SystemData = WriteStorage<'a, Position>; | |
fn run(&mut self, mut pos: Self::SystemData) { | |
use specs::Join; | |
for pos in (&mut pos).join() { | |
pos.x += 1; | |
pos.y += 1; | |
} | |
} | |
} | |
fn create_player(world: &mut World, char: char, pos: Position) { | |
world.create_entity() | |
.with(pos) | |
.with(Health { max_health: 100, current_health: 100 }) | |
.with(Drawable { char, foreground_color: Color(0xff, 0xff, 0xff), background_color: Color(0, 0, 0)}) | |
.build(); | |
} | |
fn main() { | |
let mut world = World::new(); | |
// add these lines... | |
// world.register::<Position>(); | |
// world.register::<Drawable>(); | |
// world.register::<Health>(); | |
let mut dispatcher = DispatcherBuilder::new() | |
.with(UpdatePos, "update_pos", &[]) | |
.with(Draw, "draw", &["update_pos"]) | |
.build(); | |
dispatcher.setup(&mut world.res); // ...and comment out this line to make it work | |
create_player(&mut world, '@', Position { x: 0, y: 0 }); | |
create_player(&mut world, 'T', Position { x: 0, y: 5 }); | |
for _ in 0 .. 10 { | |
dispatcher.dispatch(&world.res); | |
world.maintain(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment