roguelike-game/src/visibility_system.rs

66 lines
2.4 KiB
Rust
Raw Normal View History

2021-12-01 10:14:30 -05:00
use crate::{
components::Hidden, components::Name, game_log::GameLog, Map, Player, Position, Viewshed,
};
2021-10-25 15:26:39 -04:00
use rltk::{field_of_view, Point};
use specs::prelude::*;
pub struct VisibilitySystem {}
impl<'a> System<'a> for VisibilitySystem {
2021-12-01 10:14:30 -05:00
#[allow(clippy::type_complexity)]
2021-10-25 15:26:39 -04:00
type SystemData = (
WriteExpect<'a, Map>,
Entities<'a>,
WriteStorage<'a, Viewshed>,
2021-12-01 10:14:30 -05:00
ReadStorage<'a, Position>,
2021-10-25 15:26:39 -04:00
ReadStorage<'a, Player>,
2021-12-01 10:14:30 -05:00
WriteStorage<'a, Hidden>,
WriteExpect<'a, rltk::RandomNumberGenerator>,
WriteExpect<'a, GameLog>,
ReadStorage<'a, Name>,
2021-10-25 15:26:39 -04:00
);
fn run(&mut self, data: Self::SystemData) {
2021-12-01 10:14:30 -05:00
let (mut map, entities, mut viewshed, pos, player, mut hidden, mut rng, mut log, names) =
data;
2021-10-25 15:26:39 -04:00
for (ent, viewshed, pos) in (&entities, &mut viewshed, &pos).join() {
2021-10-26 14:23:08 -04:00
if viewshed.dirty {
viewshed.dirty = false;
viewshed.visible_tiles.clear();
viewshed.visible_tiles =
field_of_view(Point::new(pos.x, pos.y), viewshed.range, &*map);
viewshed
.visible_tiles
.retain(|p| p.x >= 0 && p.x < map.width && p.y >= 0 && p.y < map.height);
2021-10-25 15:26:39 -04:00
2021-10-26 14:23:08 -04:00
// if this is the player, reveal what they can see
if let Some(_p) = player.get(ent) {
2021-10-26 14:23:08 -04:00
for t in map.visible_tiles.iter_mut() {
*t = false
}
2021-12-01 10:14:30 -05:00
2021-10-26 14:23:08 -04:00
for vis in viewshed.visible_tiles.iter() {
let idx = map.xy_idx(vis.x, vis.y);
map.revealed_tiles[idx] = true;
map.visible_tiles[idx] = true;
2021-12-01 10:14:30 -05:00
// Chance to reveal hidden things
for e in map.tile_content[idx].iter() {
if let Some(_maybe_hidden) = hidden.get(*e) {
if rng.roll_dice(1, 24) == 1 {
if let Some(name) = names.get(*e) {
log.append(format!("You spotted a {}.", &name.name));
}
hidden.remove(*e);
}
}
}
2021-10-26 14:23:08 -04:00
}
2021-10-25 15:26:39 -04:00
}
}
}
}
}