Add basic ui with healthbar, game log, and mouse tooltips

This commit is contained in:
Timothy Warren 2021-11-01 14:46:45 -04:00
parent 2793c05730
commit a17cc6f2e6
6 changed files with 187 additions and 13 deletions

View File

@ -1,4 +1,4 @@
use crate::{CombatStats, Player, SufferDamage}; use crate::{gamelog::GameLog, CombatStats, Name, Player, SufferDamage};
use rltk::console; use rltk::console;
use specs::prelude::*; use specs::prelude::*;
@ -28,12 +28,22 @@ pub fn delete_the_dead(ecs: &mut World) {
{ {
let combat_stats = ecs.read_storage::<CombatStats>(); let combat_stats = ecs.read_storage::<CombatStats>();
let players = ecs.read_storage::<Player>(); let players = ecs.read_storage::<Player>();
let names = ecs.read_storage::<Name>();
let entities = ecs.entities(); let entities = ecs.entities();
let mut log = ecs.write_resource::<GameLog>();
for (entity, stats) in (&entities, &combat_stats).join() { for (entity, stats) in (&entities, &combat_stats).join() {
if stats.hp < 1 { if stats.hp < 1 {
let player = players.get(entity); let player = players.get(entity);
match player { match player {
None => dead.push(entity), None => {
let victim_name = names.get(entity);
if let Some(victim_name) = victim_name {
log.entries.push(format!("{} is dead", &victim_name.name));
}
dead.push(entity)
}
Some(_) => console::log("You are dead"), Some(_) => console::log("You are dead"),
} }
} }

3
src/gamelog.rs Normal file
View File

@ -0,0 +1,3 @@
pub struct GameLog {
pub entries: Vec<String>,
}

149
src/gui.rs Normal file
View File

@ -0,0 +1,149 @@
use crate::{gamelog::GameLog, CombatStats, Map, Name, Player, Position};
use rltk::{Point, Rltk, RGB};
use specs::prelude::*;
pub fn draw_ui(ecs: &World, ctx: &mut Rltk) {
ctx.draw_box(
0,
43,
79,
6,
RGB::named(rltk::WHITE),
RGB::named(rltk::BLACK),
);
let combat_stats = ecs.read_storage::<CombatStats>();
let players = ecs.read_storage::<Player>();
// Display player health
for (_player, stats) in (&players, &combat_stats).join() {
let health = format!(" HP: {} / {} ", stats.hp, stats.max_hp);
ctx.print_color(
12,
43,
RGB::named(rltk::YELLOW),
RGB::named(rltk::BLACK),
&health,
);
ctx.draw_bar_horizontal(
29,
43,
51,
stats.hp,
stats.max_hp,
RGB::named(rltk::RED),
RGB::named(rltk::BLACK),
);
}
// Display logs
let log = ecs.fetch::<GameLog>();
let mut y = 44;
for s in log.entries.iter().rev() {
if y < 49 {
ctx.print(2, y, s);
}
y += 1;
}
// Mouse cursor
let mouse_pos = ctx.mouse_pos();
ctx.set_bg(mouse_pos.0, mouse_pos.1, RGB::named(rltk::MAGENTA));
draw_tooltips(ecs, ctx);
}
fn draw_tooltips(ecs: &World, ctx: &mut Rltk) {
let map = ecs.fetch::<Map>();
let names = ecs.read_storage::<Name>();
let positions = ecs.read_storage::<Position>();
let mouse_pos = ctx.mouse_pos();
if mouse_pos.0 >= map.width || mouse_pos.1 >= map.height {
return;
}
let mut tooltip: Vec<String> = Vec::new();
for (name, position) in (&names, &positions).join() {
let idx = map.xy_idx(position.x, position.y);
if position.x == mouse_pos.0 && position.y == mouse_pos.1 && map.visible_tiles[idx] {
tooltip.push(name.name.to_string());
}
}
if !tooltip.is_empty() {
let mut width: i32 = 0;
for s in tooltip.iter() {
if width < s.len() as i32 {
width = s.len() as i32;
}
}
width += 3;
if mouse_pos.0 > 40 {
let arrow_pos = Point::new(mouse_pos.0 - 2, mouse_pos.1);
let left_x = mouse_pos.0 - width;
let mut y = mouse_pos.1;
for s in tooltip.iter() {
ctx.print_color(left_x, y, RGB::named(rltk::WHITE), RGB::named(rltk::GREY), s);
let padding = (width - s.len() as i32) - 1;
for i in 0..padding {
ctx.print_color(
arrow_pos.x - i,
y,
RGB::named(rltk::WHITE),
RGB::named(rltk::GREY),
&" ".to_string(),
);
}
y += 1;
}
ctx.print_color(
arrow_pos.x,
arrow_pos.y,
RGB::named(rltk::WHITE),
RGB::named(rltk::GREY),
&"->".to_string(),
);
} else {
let arrow_pos = Point::new(mouse_pos.0 + 1, mouse_pos.1);
let left_x = mouse_pos.0 + 3;
let mut y = mouse_pos.1;
for s in tooltip.iter() {
ctx.print_color(
left_x + 1,
y,
RGB::named(rltk::WHITE),
RGB::named(rltk::GREY),
s,
);
let padding = (width - s.len() as i32) - 1;
for i in 0..padding {
ctx.print_color(
arrow_pos.x + 1 + i,
y,
RGB::named(rltk::WHITE),
RGB::named(rltk::GREY),
&" ".to_string(),
);
}
y += 1;
}
ctx.print_color(
arrow_pos.x,
arrow_pos.y,
RGB::named(rltk::WHITE),
RGB::named(rltk::GREY),
&"<-".to_string(),
);
}
}
}

View File

@ -19,6 +19,9 @@ mod melee_combat_system;
use melee_combat_system::MeleeCombatSystem; use melee_combat_system::MeleeCombatSystem;
mod damage_system; mod damage_system;
use damage_system::DamageSystem; use damage_system::DamageSystem;
mod gamelog;
mod gui;
pub use gamelog::GameLog;
pub const MAP_SIZE: usize = 80 * 50; pub const MAP_SIZE: usize = 80 * 50;
@ -102,6 +105,8 @@ impl GameState for State {
ctx.set(pos.x, pos.y, render.fg, render.bg, render.glyph) ctx.set(pos.x, pos.y, render.fg, render.bg, render.glyph)
} }
} }
gui::draw_ui(&self.ecs, ctx);
} }
} }
@ -206,6 +211,9 @@ fn main() -> rltk::BError {
gs.ecs.insert(Point::new(player_x, player_y)); gs.ecs.insert(Point::new(player_x, player_y));
gs.ecs.insert(player_entity); gs.ecs.insert(player_entity);
gs.ecs.insert(RunState::PreRun); gs.ecs.insert(RunState::PreRun);
gs.ecs.insert(gamelog::GameLog {
entries: vec!["Welcome to Rusty Roguelike".to_string()],
});
rltk::main_loop(context, gs) rltk::main_loop(context, gs)
} }

View File

@ -1,8 +1,12 @@
use super::{Rect, MAP_SIZE}; use super::Rect;
use rltk::{Algorithm2D, BaseMap, Point, RandomNumberGenerator, Rltk, SmallVec, RGB}; use rltk::{Algorithm2D, BaseMap, Point, RandomNumberGenerator, Rltk, SmallVec, RGB};
use specs::prelude::*; use specs::prelude::*;
use std::cmp::{max, min}; use std::cmp::{max, min};
const MAPWIDTH: usize = 80;
const MAPHEIGHT: usize = 50;
const MAPCOUNT: usize = MAPHEIGHT * MAPWIDTH;
#[derive(PartialEq, Copy, Clone)] #[derive(PartialEq, Copy, Clone)]
pub enum TileType { pub enum TileType {
Wall, Wall,
@ -58,14 +62,14 @@ impl Map {
/// This gives a handful of random rooms and corridors joining them together /// This gives a handful of random rooms and corridors joining them together
pub fn new_map_rooms_and_corridors() -> Map { pub fn new_map_rooms_and_corridors() -> Map {
let mut map = Map { let mut map = Map {
tiles: vec![TileType::Wall; MAP_SIZE], tiles: vec![TileType::Wall; MAPCOUNT],
rooms: Vec::new(), rooms: Vec::new(),
width: 80, width: 80,
height: 50, height: 50,
revealed_tiles: vec![false; MAP_SIZE], revealed_tiles: vec![false; MAPCOUNT],
visible_tiles: vec![false; MAP_SIZE], visible_tiles: vec![false; MAPCOUNT],
blocked: vec![false; MAP_SIZE], blocked: vec![false; MAPCOUNT],
tile_content: vec![Vec::new(); MAP_SIZE], tile_content: vec![Vec::new(); MAPCOUNT],
}; };
const MAX_ROOMS: i32 = 30; const MAX_ROOMS: i32 = 30;

View File

@ -1,5 +1,4 @@
use crate::{CombatStats, Name, SufferDamage, WantsToMelee}; use crate::{gamelog::GameLog, CombatStats, Name, SufferDamage, WantsToMelee};
use rltk::console;
use specs::prelude::*; use specs::prelude::*;
pub struct MeleeCombatSystem {} pub struct MeleeCombatSystem {}
@ -7,6 +6,7 @@ pub struct MeleeCombatSystem {}
impl<'a> System<'a> for MeleeCombatSystem { impl<'a> System<'a> for MeleeCombatSystem {
type SystemData = ( type SystemData = (
Entities<'a>, Entities<'a>,
WriteExpect<'a, GameLog>,
WriteStorage<'a, WantsToMelee>, WriteStorage<'a, WantsToMelee>,
ReadStorage<'a, Name>, ReadStorage<'a, Name>,
ReadStorage<'a, CombatStats>, ReadStorage<'a, CombatStats>,
@ -14,7 +14,7 @@ impl<'a> System<'a> for MeleeCombatSystem {
); );
fn run(&mut self, data: Self::SystemData) { fn run(&mut self, data: Self::SystemData) {
let (entities, mut wants_melee, names, combat_stats, mut inflict_damage) = data; let (entities, mut log, mut wants_melee, names, combat_stats, mut inflict_damage) = data;
for (_entity, wants_melee, name, stats) in for (_entity, wants_melee, name, stats) in
(&entities, &wants_melee, &names, &combat_stats).join() (&entities, &wants_melee, &names, &combat_stats).join()
@ -26,12 +26,12 @@ impl<'a> System<'a> for MeleeCombatSystem {
let damage = i32::max(0, stats.power - target_stats.defense); let damage = i32::max(0, stats.power - target_stats.defense);
if damage == 0 { if damage == 0 {
console::log(&format!( log.entries.push(format!(
"{} is unable to hurt {}", "{} is unable to hurt {}",
&name.name, &target_name.name &name.name, &target_name.name
)); ));
} else { } else {
console::log(&format!( log.entries.push(format!(
"{} hits {}, for {} hp", "{} hits {}, for {} hp",
&name.name, &target_name.name, damage &name.name, &target_name.name, damage
)); ));