playing with entity component system and mapping

This commit is contained in:
Ben Morrison 2019-09-14 02:35:55 -04:00
parent af61b57b1c
commit 95f2733371
Signed by: gbmor
GPG Key ID: 8F192E4720BB0DAC

View File

@ -20,6 +20,12 @@ struct Renderable {
bg: RGB,
}
#[derive(PartialEq, Copy, Clone)]
enum TileType {
Wall,
Floor,
}
#[derive(Component)]
struct LeftMover {}
@ -60,6 +66,9 @@ impl GameState for State {
player_input(self, ctx);
self.systems.dispatch(&self.ecs);
let map = self.ecs.fetch::<Vec<TileType>>();
draw_map(&map, ctx);
let positions = self.ecs.read_storage::<Position>();
let renderables = self.ecs.read_storage::<Renderable>();
@ -83,6 +92,8 @@ fn main() {
gs.ecs.register::<LeftMover>();
gs.ecs.register::<Player>();
gs.ecs.insert(new_map());
gs.ecs
.create_entity()
.with(Position { x: 40, y: 25 })
@ -147,3 +158,68 @@ fn player_input(gs: &mut State, ctx: &mut Rltk) {
},
}
}
fn xy_idx(x: i32, y: i32) -> usize {
(y as usize * 80) + x as usize
}
fn new_map() -> Vec<TileType> {
let mut map = vec![TileType::Floor; 80 * 50];
(0..80).into_iter().for_each(|x| {
map[xy_idx(x, 0)] = TileType::Wall;
map[xy_idx(x, 49)] = TileType::Wall;
});
(0..50).into_iter().for_each(|y| {
map[xy_idx(0, y)] = TileType::Wall;
map[xy_idx(79, y)] = TileType::Wall;
});
//rando-splat of walls
let mut rng = rltk::RandomNumberGenerator::new();
(0..400).into_iter().for_each(|_| {
let x = rng.roll_dice(1, 79);
let y = rng.roll_dice(1, 49);
let idx = xy_idx(x, y);
if idx != xy_idx(40, 25) {
map[idx] = TileType::Wall;
}
});
map
}
fn draw_map(map: &[TileType], ctx: &mut Rltk) {
let mut y = 0;
let mut x = 0;
map.iter().for_each(|tile| {
match tile {
TileType::Floor => {
ctx.set(
x,
y,
RGB::from_f32(0.5, 0.5, 0.5),
RGB::from_f32(0., 0., 0.),
rltk::to_cp437('.'),
);
}
TileType::Wall => {
ctx.set(
x,
y,
RGB::from_f32(0.0, 1.0, 0.0),
RGB::from_f32(0., 0., 0.),
rltk::to_cp437('#'),
);
}
}
x += 1;
if x > 79 {
x = 0;
y += 1;
}
});
}