Partial refactor

This commit is contained in:
Benjamyn Love 2022-11-27 02:38:07 +11:00
parent 379df46c34
commit e1459cc27b
4 changed files with 94 additions and 62 deletions

View File

@ -1,4 +1,4 @@
use rltk::{RGB}; use rltk::RGB;
use specs::prelude::*; use specs::prelude::*;
use specs_derive::*; use specs_derive::*;
@ -13,7 +13,7 @@ pub struct Renderable {
pub glyph: rltk::FontCharType, pub glyph: rltk::FontCharType,
pub fg: RGB, pub fg: RGB,
pub bg: RGB, pub bg: RGB,
pub render_order : i32, pub render_order: i32,
} }
#[derive(Component, Debug)] #[derive(Component, Debug)]
@ -41,7 +41,7 @@ pub enum RunState {
PlayerTurn, PlayerTurn,
MonsterTurn, MonsterTurn,
ShowInventory, ShowInventory,
ShowDropItem ShowDropItem,
} }
#[derive(Component, Debug)] #[derive(Component, Debug)]
@ -82,7 +82,7 @@ impl SufferDamage {
pub struct Item {} pub struct Item {}
#[derive(Component, Debug)] #[derive(Component, Debug)]
pub struct Potion { pub struct ProvidesHealing {
pub heal_amount: i32, pub heal_amount: i32,
} }
@ -98,12 +98,12 @@ pub struct WantsToPickupItem {
} }
#[derive(Component, Debug)] #[derive(Component, Debug)]
pub struct WantsToDrinkPotion { pub struct WantsToUseItem {
pub potion: Entity, pub item: Entity,
} }
#[derive(Component, Debug, Clone)] #[derive(Component, Debug, Clone)]
pub struct WantsToDropItem { pub struct WantsToDropItem {
pub item : Entity pub item: Entity,
} }
#[derive(Component, Debug)] #[derive(Component, Debug)]

View File

@ -1,11 +1,10 @@
use specs::prelude::*; use specs::prelude::*;
use super::{ use super::{
gamelog::GameLog, CombatStats, InBackpack, Name, Position, Potion, WantsToDrinkPotion, gamelog::GameLog, CombatStats, Consumable, InBackpack, Name, Position, ProvidesHealing,
WantsToPickupItem,WantsToDropItem WantsToDropItem, WantsToPickupItem, WantsToUseItem,
}; };
pub struct ItemCollectionSystem {} pub struct ItemCollectionSystem {}
impl<'a> System<'a> for ItemCollectionSystem { impl<'a> System<'a> for ItemCollectionSystem {
@ -45,17 +44,18 @@ impl<'a> System<'a> for ItemCollectionSystem {
} }
} }
pub struct PotionUseSystem {} pub struct ItemUseSystem {}
impl<'a> System<'a> for PotionUseSystem { impl<'a> System<'a> for ItemUseSystem {
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
type SystemData = ( type SystemData = (
ReadExpect<'a, Entity>, ReadExpect<'a, Entity>,
WriteExpect<'a, GameLog>, WriteExpect<'a, GameLog>,
Entities<'a>, Entities<'a>,
WriteStorage<'a, WantsToDrinkPotion>, WriteStorage<'a, WantsToUseItem>,
ReadStorage<'a, Name>, ReadStorage<'a, Name>,
ReadStorage<'a, Potion>, ReadStorage<'a, Consumable>,
ReadStorage<'a, ProvidesHealing>,
WriteStorage<'a, CombatStats>, WriteStorage<'a, CombatStats>,
); );
@ -64,62 +64,82 @@ impl<'a> System<'a> for PotionUseSystem {
player_entity, player_entity,
mut gamelog, mut gamelog,
entities, entities,
mut wants_drink, mut wants_use,
names, names,
potions, consumables,
healing,
mut combat_stats, mut combat_stats,
) = data; ) = data;
for (entity, drink, stats) in (&entities, &wants_drink, &mut combat_stats).join() { for (entity, useitem) in (&entities, &wants_use).join() {
let potion = potions.get(drink.potion); let item_heals = healing.get(useitem.item);
match item_heals {
match potion {
None => {} None => {}
Some(potion) => { Some(healer) => {
stats.hp = i32::min(stats.max_hp, stats.hp + potion.heal_amount); let stats = combat_stats.get_mut(*player_entity);
gamelog.entries.push(format!("{}", stats.hp)); stats.hp = i32::min(stats.max_hp, stats.hp + healer.heal_amount);
if entity == *player_entity { }
gamelog.entries.push(format!( }
"You drink the {}, healing {} hp.", let consumable = consumables.get(useitem.item);
names.get(drink.potion).unwrap().name,
potion.heal_amount match consumable {
)); None => {}
entities.delete(drink.potion).expect("Delete failed") Some(_) => {
entities.delete(useitem.item).expect("Delete failed");
} }
} }
} }
} wants_use.clear();
wants_drink.clear();
} }
} }
pub struct ItemDropSystem {} pub struct ItemDropSystem {}
impl<'a> System<'a> for ItemDropSystem { impl<'a> System<'a> for ItemDropSystem {
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
type SystemData = ( ReadExpect<'a, Entity>, type SystemData = (
ReadExpect<'a, Entity>,
WriteExpect<'a, GameLog>, WriteExpect<'a, GameLog>,
Entities<'a>, Entities<'a>,
WriteStorage<'a, WantsToDropItem>, WriteStorage<'a, WantsToDropItem>,
ReadStorage<'a, Name>, ReadStorage<'a, Name>,
WriteStorage<'a, Position>, WriteStorage<'a, Position>,
WriteStorage<'a, InBackpack> WriteStorage<'a, InBackpack>,
); );
fn run(&mut self, data : Self::SystemData) { fn run(&mut self, data: Self::SystemData) {
let (player_entity, mut gamelog, entities, mut wants_drop, names, mut positions, mut backpack) = data; let (
player_entity,
mut gamelog,
entities,
mut wants_drop,
names,
mut positions,
mut backpack,
) = data;
for (entity, to_drop) in (&entities, &wants_drop).join() { for (entity, to_drop) in (&entities, &wants_drop).join() {
let mut dropper_pos : Position = Position{x:0, y:0}; let mut dropper_pos: Position = Position { x: 0, y: 0 };
{ {
let dropped_pos = positions.get(entity).unwrap(); let dropped_pos = positions.get(entity).unwrap();
dropper_pos.x = dropped_pos.x; dropper_pos.x = dropped_pos.x;
dropper_pos.y = dropped_pos.y; dropper_pos.y = dropped_pos.y;
} }
positions.insert(to_drop.item, Position{ x : dropper_pos.x, y : dropper_pos.y}).expect("Unable to insert position"); positions
.insert(
to_drop.item,
Position {
x: dropper_pos.x,
y: dropper_pos.y,
},
)
.expect("Unable to insert position");
backpack.remove(to_drop.item); backpack.remove(to_drop.item);
if entity == *player_entity { if entity == *player_entity {
gamelog.entries.push(format!("You drop the {}", names.get(to_drop.item).unwrap().name)); gamelog.entries.push(format!(
"You drop the {}",
names.get(to_drop.item).unwrap().name
));
} }
} }

View File

@ -58,9 +58,9 @@ impl State {
damage_system.run_now(&self.ecs); damage_system.run_now(&self.ecs);
let mut pickup = ItemCollectionSystem {}; let mut pickup = ItemCollectionSystem {};
pickup.run_now(&self.ecs); pickup.run_now(&self.ecs);
let mut drop_items = ItemDropSystem{}; let mut drop_items = ItemDropSystem {};
drop_items.run_now(&self.ecs); drop_items.run_now(&self.ecs);
let mut potions = PotionUseSystem {}; let mut potions = ItemUseSystem {};
potions.run_now(&self.ecs); potions.run_now(&self.ecs);
self.ecs.maintain(); self.ecs.maintain();
} }
@ -77,11 +77,13 @@ impl GameState for State {
let map = self.ecs.fetch::<Map>(); let map = self.ecs.fetch::<Map>();
let mut data = (&positions, &renderables).join().collect::<Vec<_>>(); let mut data = (&positions, &renderables).join().collect::<Vec<_>>();
data.sort_by(|&a, &b| b.1.render_order.cmp(&a.1.render_order) ); data.sort_by(|&a, &b| b.1.render_order.cmp(&a.1.render_order));
for (pos, render) in data.iter() { for (pos, render) in data.iter() {
let idx = map.xy_idx(pos.x, pos.y); let idx = map.xy_idx(pos.x, pos.y);
if map.visible_tiles[idx] { ctx.set(pos.x, pos.y, render.fg, render.bg, render.glyph) } if map.visible_tiles[idx] {
ctx.set(pos.x, pos.y, render.fg, render.bg, render.glyph)
}
} }
// for (pos, render) in (&positions, &renderables).join() { // for (pos, render) in (&positions, &renderables).join() {
// let idx = map.xy_idx(pos.x, pos.y); // let idx = map.xy_idx(pos.x, pos.y);
@ -142,11 +144,16 @@ impl GameState for State {
let result = gui::drop_item_menu(self, ctx); let result = gui::drop_item_menu(self, ctx);
match result.0 { match result.0 {
gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput, gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}, gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => { gui::ItemMenuResult::Selected => {
let item_entity = result.1.unwrap(); let item_entity = result.1.unwrap();
let mut intent = self.ecs.write_storage::<WantsToDropItem>(); let mut intent = self.ecs.write_storage::<WantsToDropItem>();
intent.insert(*self.ecs.fetch::<Entity>(), WantsToDropItem { item: item_entity }).expect("Unable to insert intent"); intent
.insert(
*self.ecs.fetch::<Entity>(),
WantsToDropItem { item: item_entity },
)
.expect("Unable to insert intent");
newrunstate = RunState::PlayerTurn; newrunstate = RunState::PlayerTurn;
} }
} }
@ -155,11 +162,16 @@ impl GameState for State {
let result = gui::drop_item_menu(self, ctx); let result = gui::drop_item_menu(self, ctx);
match result.0 { match result.0 {
gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput, gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}, gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => { gui::ItemMenuResult::Selected => {
let item_entity = result.1.unwrap(); let item_entity = result.1.unwrap();
let mut intent = self.ecs.write_storage::<WantsToDropItem>(); let mut intent = self.ecs.write_storage::<WantsToDropItem>();
intent.insert(*self.ecs.fetch::<Entity>(), WantsToDropItem { item: item_entity }).expect("Unable to insert intent"); intent
.insert(
*self.ecs.fetch::<Entity>(),
WantsToDropItem { item: item_entity },
)
.expect("Unable to insert intent");
newrunstate = RunState::PlayerTurn; newrunstate = RunState::PlayerTurn;
} }
} }
@ -193,7 +205,7 @@ fn main() -> rltk::BError {
gs.ecs.register::<WantsToMelee>(); gs.ecs.register::<WantsToMelee>();
gs.ecs.register::<SufferDamage>(); gs.ecs.register::<SufferDamage>();
gs.ecs.register::<Item>(); gs.ecs.register::<Item>();
gs.ecs.register::<Potion>(); gs.ecs.register::<ProvidesHealing>();
gs.ecs.register::<InBackpack>(); gs.ecs.register::<InBackpack>();
gs.ecs.register::<WantsToPickupItem>(); gs.ecs.register::<WantsToPickupItem>();
gs.ecs.register::<WantsToDropItem>(); gs.ecs.register::<WantsToDropItem>();

View File

@ -1,8 +1,8 @@
use crate::MAPWIDTH; use crate::MAPWIDTH;
use super::{ use super::{
BlocksTile, CombatStats, Item, Monster, Name, Player, Position, Potion, Rect, Renderable, BlocksTile, CombatStats, Item, Monster, Name, Player, Position, ProvidesHealing, Rect,
Viewshed, Renderable, Viewshed,
}; };
use rltk::{RandomNumberGenerator, RGB}; use rltk::{RandomNumberGenerator, RGB};
use specs::prelude::*; use specs::prelude::*;
@ -21,7 +21,7 @@ pub fn player(ecs: &mut World, player_x: i32, player_y: i32) -> Entity {
glyph: rltk::to_cp437('@'), glyph: rltk::to_cp437('@'),
fg: RGB::named(rltk::YELLOW), fg: RGB::named(rltk::YELLOW),
bg: RGB::named(rltk::BLACK), bg: RGB::named(rltk::BLACK),
render_order: 0 render_order: 0,
}) })
.with(Player {}) .with(Player {})
.with(Viewshed { .with(Viewshed {
@ -67,7 +67,7 @@ fn monster<S: ToString>(ecs: &mut World, x: i32, y: i32, glyph: rltk::FontCharTy
glyph: glyph, glyph: glyph,
fg: RGB::named(rltk::RED), fg: RGB::named(rltk::RED),
bg: RGB::named(rltk::BLACK), bg: RGB::named(rltk::BLACK),
render_order: 1 render_order: 1,
}) })
.with(Viewshed { .with(Viewshed {
visible_tiles: Vec::new(), visible_tiles: Vec::new(),
@ -144,12 +144,12 @@ fn health_potion(ecs: &mut World, x: i32, y: i32) {
glyph: rltk::to_cp437(';'), glyph: rltk::to_cp437(';'),
fg: RGB::named(rltk::MAGENTA), fg: RGB::named(rltk::MAGENTA),
bg: RGB::named(rltk::BLACK), bg: RGB::named(rltk::BLACK),
render_order: 2 render_order: 2,
}) })
.with(Name { .with(Name {
name: "Health Potion".to_string(), name: "Health Potion".to_string(),
}) })
.with(Item {}) .with(Item {})
.with(Potion { heal_amount: 8 }) .with(ProvidesHealing { heal_amount: 8 })
.build(); .build();
} }