Complete chapter 2.9

This commit is contained in:
Timothy Warren 2021-11-05 14:32:14 -04:00
parent 36af877217
commit 7d0200b262
7 changed files with 128 additions and 45 deletions

View File

@ -16,7 +16,7 @@ pub struct Renderable {
pub render_order: i32, pub render_order: i32,
} }
#[derive(Component, Debug)] #[derive(Component, Debug, Default)]
pub struct Player {} pub struct Player {}
#[derive(Component)] #[derive(Component)]
@ -36,7 +36,7 @@ impl Default for Viewshed {
} }
} }
#[derive(Component, Debug)] #[derive(Component, Debug, Default)]
pub struct Monster {} pub struct Monster {}
#[derive(Component, Debug)] #[derive(Component, Debug)]
@ -52,7 +52,7 @@ impl Name {
} }
} }
#[derive(Component, Debug)] #[derive(Component, Debug, Default)]
pub struct BlocksTile {} pub struct BlocksTile {}
#[derive(Component, Debug)] #[derive(Component, Debug)]
@ -86,7 +86,7 @@ impl SufferDamage {
} }
} }
#[derive(Component, Debug)] #[derive(Component, Debug, Default)]
pub struct Item {} pub struct Item {}
#[derive(Component, Debug)] #[derive(Component, Debug)]
@ -116,7 +116,7 @@ pub struct WantsToDropItem {
pub item: Entity, pub item: Entity,
} }
#[derive(Component, Debug)] #[derive(Component, Debug, Default)]
pub struct Consumable {} pub struct Consumable {}
#[derive(Component, Debug)] #[derive(Component, Debug)]
@ -133,3 +133,8 @@ pub struct InflictsDamage {
pub struct AreaOfEffect { pub struct AreaOfEffect {
pub radius: i32, pub radius: i32,
} }
#[derive(Component, Debug)]
pub struct Confusion {
pub turns: i32,
}

View File

@ -1,3 +1,12 @@
pub struct GameLog { pub struct GameLog {
pub entries: Vec<String>, pub entries: Vec<String>,
} }
impl GameLog {
pub fn new<S: ToString>(first_entry: S) -> Self {
let mut entries: Vec<String> = Vec::new();
entries.push(first_entry.to_string());
GameLog { entries }
}
}

View File

@ -1,7 +1,7 @@
use crate::{ use crate::{
game_log::GameLog, AreaOfEffect, CombatStats, Consumable, InBackpack, InflictsDamage, Map, game_log::GameLog, AreaOfEffect, CombatStats, Confusion, Consumable, InBackpack,
Name, Position, ProvidesHealing, SufferDamage, WantsToDropItem, WantsToPickupItem, InflictsDamage, Map, Name, Position, ProvidesHealing, SufferDamage, WantsToDropItem,
WantsToUseItem, WantsToPickupItem, WantsToUseItem,
}; };
use specs::prelude::*; use specs::prelude::*;
@ -62,6 +62,7 @@ impl<'a> System<'a> for ItemUseSystem {
WriteStorage<'a, CombatStats>, WriteStorage<'a, CombatStats>,
WriteStorage<'a, SufferDamage>, WriteStorage<'a, SufferDamage>,
ReadStorage<'a, AreaOfEffect>, ReadStorage<'a, AreaOfEffect>,
WriteStorage<'a, Confusion>,
); );
fn run(&mut self, data: Self::SystemData) { fn run(&mut self, data: Self::SystemData) {
@ -78,6 +79,7 @@ impl<'a> System<'a> for ItemUseSystem {
mut combat_stats, mut combat_stats,
mut suffer_damage, mut suffer_damage,
aoe, aoe,
mut confused,
) = data; ) = data;
for (entity, useitem) in (&entities, &wants_use).join() { for (entity, useitem) in (&entities, &wants_use).join() {
@ -164,6 +166,36 @@ impl<'a> System<'a> for ItemUseSystem {
} }
} }
// Can it pass along confusion? Note the use of scopes
// to escape from the borrow checker!
let mut add_confusion = Vec::new();
{
match confused.get(useitem.item) {
None => {}
Some(confusion) => {
used_item = false;
for mob in targets.iter() {
add_confusion.push((*mob, confusion.turns));
if entity == *player_entity {
let mob_name = names.get(*mob).unwrap();
let item_name = names.get(useitem.item).unwrap();
gamelog.entries.push(format!(
"You use {} on {}, confusing them.",
item_name.name, mob_name.name
));
}
}
}
}
}
for mob in add_confusion.iter() {
confused
.insert(mob.0, Confusion { turns: mob.1 })
.expect("Unable to add confused status");
}
// If it's a consumable, delete it on use // If it's a consumable, delete it on use
if used_item { if used_item {
let consumable = consumables.get(useitem.item); let consumable = consumables.get(useitem.item);

View File

@ -15,7 +15,7 @@ mod rect;
mod spawner; mod spawner;
mod visibility_system; mod visibility_system;
pub use components::*; use components::*;
use damage_system::DamageSystem; use damage_system::DamageSystem;
pub use game_log::GameLog; pub use game_log::GameLog;
use inventory_system::{ItemCollectionSystem, ItemDropSystem, ItemUseSystem}; use inventory_system::{ItemCollectionSystem, ItemDropSystem, ItemUseSystem};
@ -100,7 +100,7 @@ impl GameState for State {
let renderables = self.ecs.read_storage::<Renderable>(); let renderables = self.ecs.read_storage::<Renderable>();
let map = self.ecs.fetch::<Map>(); let map = self.ecs.fetch::<Map>();
let mut data = (&positions, &renderables).join().collect::<Vec<_>>(); let mut data: Vec<_> = (&positions, &renderables).join().collect();
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);
@ -254,6 +254,7 @@ fn main() -> rltk::BError {
Ranged, Ranged,
InflictsDamage, InflictsDamage,
AreaOfEffect, AreaOfEffect,
Confusion,
); );
let map = Map::new_map_rooms_and_corridors(); let map = Map::new_map_rooms_and_corridors();
@ -270,9 +271,7 @@ 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(game_log::GameLog { gs.ecs.insert(GameLog::new("Welcome to Rusty Roguelike"));
entries: vec!["Welcome to Rusty Roguelike".to_string()],
});
rltk::main_loop(context, gs) rltk::main_loop(context, gs)
} }

View File

@ -1,4 +1,4 @@
use super::Rect; use crate::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};

View File

@ -1,4 +1,6 @@
use crate::{Map, Monster, Position, RunState, Viewshed, WantsToMelee}; use crate::components::{Confusion, Monster, Position, Viewshed, WantsToMelee};
use crate::{Map, RunState};
use rltk::Point; use rltk::Point;
use specs::prelude::*; use specs::prelude::*;
@ -16,6 +18,7 @@ impl<'a> System<'a> for MonsterAI {
ReadStorage<'a, Monster>, ReadStorage<'a, Monster>,
WriteStorage<'a, Position>, WriteStorage<'a, Position>,
WriteStorage<'a, WantsToMelee>, WriteStorage<'a, WantsToMelee>,
WriteStorage<'a, Confusion>,
); );
fn run(&mut self, data: Self::SystemData) { fn run(&mut self, data: Self::SystemData) {
@ -29,6 +32,7 @@ impl<'a> System<'a> for MonsterAI {
monster, monster,
mut position, mut position,
mut wants_to_melee, mut wants_to_melee,
mut confused,
) = data; ) = data;
if *runstate != RunState::MonsterTurn { if *runstate != RunState::MonsterTurn {
@ -38,35 +42,50 @@ impl<'a> System<'a> for MonsterAI {
for (entity, mut viewshed, _monster, mut pos) in for (entity, mut viewshed, _monster, mut pos) in
(&entities, &mut viewshed, &monster, &mut position).join() (&entities, &mut viewshed, &monster, &mut position).join()
{ {
let distance = let mut can_act = true;
rltk::DistanceAlg::Pythagoras.distance2d(Point::new(pos.x, pos.y), *player_pos);
if distance < 1.5 {
// Attack goes here
wants_to_melee
.insert(
entity,
WantsToMelee {
target: *player_entity,
},
)
.expect("Unable to insert attack");
} else if viewshed.visible_tiles.contains(&*player_pos) {
let path = rltk::a_star_search(
map.xy_idx(pos.x, pos.y) as i32,
map.xy_idx(player_pos.x, player_pos.y) as i32,
&mut *map,
);
if path.success && path.steps.len() > 1 { let is_confused = confused.get_mut(entity);
let mut idx = map.xy_idx(pos.x, pos.y); if let Some(i_am_confused) = is_confused {
i_am_confused.turns -= 1;
if i_am_confused.turns < 1 {
confused.remove(entity);
}
map.blocked[idx] = false; can_act = false;
pos.x = path.steps[1] as i32 % map.width; }
pos.y = path.steps[1] as i32 / map.width;
idx = map.xy_idx(pos.x, pos.y); if can_act {
map.blocked[idx] = true; let distance =
viewshed.dirty = true; rltk::DistanceAlg::Pythagoras.distance2d(Point::new(pos.x, pos.y), *player_pos);
if distance < 1.5 {
// Attack goes here
wants_to_melee
.insert(
entity,
WantsToMelee {
target: *player_entity,
},
)
.expect("Unable to insert attack");
} else if viewshed.visible_tiles.contains(&*player_pos) {
// The path to the player
let path = rltk::a_star_search(
map.xy_idx(pos.x, pos.y) as i32,
map.xy_idx(player_pos.x, player_pos.y) as i32,
&mut *map,
);
if path.success && path.steps.len() > 1 {
let mut idx = map.xy_idx(pos.x, pos.y);
map.blocked[idx] = false;
pos.x = path.steps[1] as i32 % map.width;
pos.y = path.steps[1] as i32 / map.width;
idx = map.xy_idx(pos.x, pos.y);
map.blocked[idx] = true;
viewshed.dirty = true;
}
} }
} }
} }

View File

@ -1,7 +1,8 @@
use crate::{ use crate::components::{
AreaOfEffect, BlocksTile, CombatStats, Consumable, InflictsDamage, Item, Monster, Name, Player, AreaOfEffect, BlocksTile, CombatStats, Confusion, Consumable, InflictsDamage, Item, Monster,
Position, ProvidesHealing, Ranged, Rect, Renderable, Viewshed, MAP_WIDTH, Name, Player, Position, ProvidesHealing, Ranged, Renderable, Viewshed,
}; };
use crate::{Rect, MAP_WIDTH};
use rltk::{RandomNumberGenerator, RGB}; use rltk::{RandomNumberGenerator, RGB};
use specs::prelude::*; use specs::prelude::*;
@ -172,12 +173,13 @@ fn random_item(ecs: &mut World, x: i32, y: i32) {
let roll: i32; let roll: i32;
{ {
let mut rng = ecs.write_resource::<RandomNumberGenerator>(); let mut rng = ecs.write_resource::<RandomNumberGenerator>();
roll = rng.roll_dice(1, 3); roll = rng.roll_dice(1, 4);
} }
match roll { match roll {
1 => health_potion(ecs, x, y), 1 => health_potion(ecs, x, y),
2 => fireball_scroll(ecs, x, y), 2 => fireball_scroll(ecs, x, y),
3 => confusion_scroll(ecs, x, y),
_ => magic_missile_scroll(ecs, x, y), _ => magic_missile_scroll(ecs, x, y),
} }
} }
@ -199,3 +201,20 @@ fn fireball_scroll(ecs: &mut World, x: i32, y: i32) {
.with(AreaOfEffect { radius: 3 }) .with(AreaOfEffect { radius: 3 })
.build(); .build();
} }
fn confusion_scroll(ecs: &mut World, x: i32, y: i32) {
ecs.create_entity()
.with(Position { x, y })
.with(Renderable {
glyph: rltk::to_cp437(')'),
fg: RGB::named(rltk::PINK),
bg: RGB::named(rltk::BLACK),
render_order: 2,
})
.with(Name::new("Confusion Scroll"))
.with(Item {})
.with(Consumable {})
.with(Ranged { range: 6 })
.with(Confusion { turns: 4 })
.build();
}