weighted spawns, magic mapping, and curses

This commit is contained in:
Llywelwyn 2023-07-10 06:49:31 +01:00
parent b8f8691e90
commit c6639b7616
8 changed files with 318 additions and 133 deletions

View file

@ -81,6 +81,9 @@ impl SufferDamage {
#[derive(Component, Debug, Serialize, Deserialize, Clone)] #[derive(Component, Debug, Serialize, Deserialize, Clone)]
pub struct Item {} pub struct Item {}
#[derive(Component, Debug, Serialize, Deserialize, Clone)]
pub struct Cursed {}
#[derive(Component, Debug, ConvertSaveload, Clone)] #[derive(Component, Debug, ConvertSaveload, Clone)]
pub struct ProvidesHealing { pub struct ProvidesHealing {
pub amount: i32, pub amount: i32,
@ -106,6 +109,9 @@ pub struct Confusion {
pub turns: i32, pub turns: i32,
} }
#[derive(Component, Serialize, Deserialize, Clone)]
pub struct MagicMapper {}
#[derive(Component, Debug, ConvertSaveload)] #[derive(Component, Debug, ConvertSaveload)]
pub struct InBackpack { pub struct InBackpack {
pub owner: Entity, pub owner: Entity,

View file

@ -57,64 +57,54 @@ fn draw_tooltips(ecs: &World, ctx: &mut Rltk) {
} }
if !tooltip.is_empty() { if !tooltip.is_empty() {
let mut width: i32 = 0; if mouse_pos.0 > 40 {
for s in tooltip.iter() { let arrow_pos = Point::new(mouse_pos.0 - 2, mouse_pos.1);
if width < s.len() as i32 { let left_x = mouse_pos.0 - 3;
width = s.len() as i32; let mut y = mouse_pos.1;
} for s in tooltip.iter() {
width += 3; for i in 0..2 {
ctx.print_color(
if mouse_pos.0 > 40 { arrow_pos.x - i,
let arrow_pos = Point::new(mouse_pos.0 - 2, mouse_pos.1); y,
let left_x = mouse_pos.0 - width; RGB::named(rltk::WHITE),
let mut y = mouse_pos.1; RGB::named(rltk::GREY),
for s in tooltip.iter() { &" ".to_string(),
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( ctx.print_color_right(left_x, y, RGB::named(rltk::WHITE), RGB::named(rltk::GREY), s);
arrow_pos.x, y += 1;
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(),
);
} }
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() {
for i in 0..2 {
ctx.print_color(
arrow_pos.x + 1 + i,
y,
RGB::named(rltk::WHITE),
RGB::named(rltk::GREY),
&" ".to_string(),
);
}
ctx.print_color(left_x + 1, y, RGB::named(rltk::WHITE), RGB::named(rltk::DARKGREY), s);
y += 1;
}
ctx.print_color(
arrow_pos.x,
arrow_pos.y,
RGB::named(rltk::WHITE),
RGB::named(rltk::GREY),
&"<-".to_string(),
);
} }
} }
} }
@ -136,7 +126,7 @@ pub fn show_inventory(gs: &mut State, ctx: &mut Rltk) -> (ItemMenuResult, Option
let count = inventory.count(); let count = inventory.count();
let mut y = (25 - (count / 2)) as i32; let mut y = (25 - (count / 2)) as i32;
ctx.draw_box(15, y - 2, 31, (count + 3) as i32, RGB::named(rltk::WHITE), RGB::named(rltk::BLACK)); ctx.draw_box(15, y - 2, 37, (count + 3) as i32, RGB::named(rltk::WHITE), RGB::named(rltk::BLACK));
ctx.print_color(18, y - 2, RGB::named(rltk::YELLOW), RGB::named(rltk::BLACK), "Inventory"); ctx.print_color(18, y - 2, RGB::named(rltk::YELLOW), RGB::named(rltk::BLACK), "Inventory");
ctx.print_color(18, y + count as i32 + 1, RGB::named(rltk::YELLOW), RGB::named(rltk::BLACK), "ESC to cancel"); ctx.print_color(18, y + count as i32 + 1, RGB::named(rltk::YELLOW), RGB::named(rltk::BLACK), "ESC to cancel");
@ -178,7 +168,7 @@ pub fn drop_item_menu(gs: &mut State, ctx: &mut Rltk) -> (ItemMenuResult, Option
let count = inventory.count(); let count = inventory.count();
let mut y = (25 - (count / 2)) as i32; let mut y = (25 - (count / 2)) as i32;
ctx.draw_box(15, y - 2, 31, (count + 3) as i32, RGB::named(rltk::WHITE), RGB::named(rltk::BLACK)); ctx.draw_box(15, y - 2, 37, (count + 3) as i32, RGB::named(rltk::WHITE), RGB::named(rltk::BLACK));
ctx.print_color(18, y - 2, RGB::named(rltk::YELLOW), RGB::named(rltk::BLACK), "Drop what?"); ctx.print_color(18, y - 2, RGB::named(rltk::YELLOW), RGB::named(rltk::BLACK), "Drop what?");
ctx.print_color(18, y + count as i32 + 1, RGB::named(rltk::YELLOW), RGB::named(rltk::BLACK), "ESC to cancel"); ctx.print_color(18, y + count as i32 + 1, RGB::named(rltk::YELLOW), RGB::named(rltk::BLACK), "ESC to cancel");

View file

@ -1,7 +1,7 @@
use super::{ use super::{
gamelog::GameLog, CombatStats, Confusion, Consumable, Destructible, InBackpack, InflictsDamage, Map, Name, gamelog::GameLog, CombatStats, Confusion, Consumable, Cursed, Destructible, InBackpack, InflictsDamage,
ParticleBuilder, Position, ProvidesHealing, SufferDamage, WantsToDropItem, WantsToPickupItem, WantsToUseItem, AOE, MagicMapper, Map, Name, ParticleBuilder, Position, ProvidesHealing, RunState, SufferDamage, WantsToDropItem,
DEFAULT_PARTICLE_LIFETIME, LONG_PARTICLE_LIFETIME, WantsToPickupItem, WantsToUseItem, AOE, DEFAULT_PARTICLE_LIFETIME, LONG_PARTICLE_LIFETIME,
}; };
use specs::prelude::*; use specs::prelude::*;
@ -46,6 +46,7 @@ impl<'a> System<'a> for ItemUseSystem {
ReadStorage<'a, Name>, ReadStorage<'a, Name>,
ReadStorage<'a, Consumable>, ReadStorage<'a, Consumable>,
ReadStorage<'a, Destructible>, ReadStorage<'a, Destructible>,
ReadStorage<'a, Cursed>,
ReadStorage<'a, ProvidesHealing>, ReadStorage<'a, ProvidesHealing>,
WriteStorage<'a, CombatStats>, WriteStorage<'a, CombatStats>,
WriteStorage<'a, SufferDamage>, WriteStorage<'a, SufferDamage>,
@ -54,6 +55,8 @@ impl<'a> System<'a> for ItemUseSystem {
ReadStorage<'a, InflictsDamage>, ReadStorage<'a, InflictsDamage>,
ReadStorage<'a, AOE>, ReadStorage<'a, AOE>,
WriteStorage<'a, Confusion>, WriteStorage<'a, Confusion>,
ReadStorage<'a, MagicMapper>,
WriteExpect<'a, RunState>,
); );
fn run(&mut self, data: Self::SystemData) { fn run(&mut self, data: Self::SystemData) {
@ -66,6 +69,7 @@ impl<'a> System<'a> for ItemUseSystem {
names, names,
consumables, consumables,
destructibles, destructibles,
cursed_items,
provides_healing, provides_healing,
mut combat_stats, mut combat_stats,
mut suffer_damage, mut suffer_damage,
@ -74,6 +78,8 @@ impl<'a> System<'a> for ItemUseSystem {
inflicts_damage, inflicts_damage,
aoe, aoe,
mut confused, mut confused,
magic_mapper,
mut runstate,
) = data; ) = data;
for (entity, wants_to_use) in (&entities, &wants_to_use).join() { for (entity, wants_to_use) in (&entities, &wants_to_use).join() {
@ -81,6 +87,8 @@ impl<'a> System<'a> for ItemUseSystem {
let mut aoe_item = false; let mut aoe_item = false;
let item_being_used = names.get(wants_to_use.item).unwrap(); let item_being_used = names.get(wants_to_use.item).unwrap();
let is_cursed = cursed_items.get(wants_to_use.item);
// TARGETING // TARGETING
let mut targets: Vec<Entity> = Vec::new(); let mut targets: Vec<Entity> = Vec::new();
match wants_to_use.target { match wants_to_use.target {
@ -132,7 +140,7 @@ impl<'a> System<'a> for ItemUseSystem {
// Ideally, replace it with something that picks the correct verb for // Ideally, replace it with something that picks the correct verb for
// whatever the item is being used, probably tied to a component. // whatever the item is being used, probably tied to a component.
// i.e. quaffs, uses, reads // i.e. quaffs, uses, reads
gamelog.entries.push(format!("You use the {}!", item_being_used.name)); gamelog.entries.push(format!("You use the {}.", item_being_used.name));
} }
Some(heal) => { Some(heal) => {
for target in targets.iter() { for target in targets.iter() {
@ -219,6 +227,25 @@ impl<'a> System<'a> for ItemUseSystem {
confused.insert(mob.0, Confusion { turns: mob.1 }).expect("Unable to insert status"); confused.insert(mob.0, Confusion { turns: mob.1 }).expect("Unable to insert status");
} }
// MAGIC MAPPERS
let is_mapper = magic_mapper.get(wants_to_use.item);
match is_mapper {
None => {}
Some(_) => {
used_item = true;
match is_cursed {
None => {
gamelog.entries.push("You feel a sense of acuity to your surroundings.".to_string());
*runstate = RunState::MagicMapReveal { row: 0, cursed: false };
}
Some(_) => {
gamelog.entries.push("You forget where you just were!".to_string());
*runstate = RunState::MagicMapReveal { row: 0, cursed: true };
}
}
}
}
// ITEM DELETION AFTER USE // ITEM DELETION AFTER USE
if used_item { if used_item {
let consumable = consumables.get(wants_to_use.item); let consumable = consumables.get(wants_to_use.item);

View file

@ -30,6 +30,7 @@ mod inventory_system;
use inventory_system::*; use inventory_system::*;
mod particle_system; mod particle_system;
use particle_system::{ParticleBuilder, DEFAULT_PARTICLE_LIFETIME, LONG_PARTICLE_LIFETIME}; use particle_system::{ParticleBuilder, DEFAULT_PARTICLE_LIFETIME, LONG_PARTICLE_LIFETIME};
mod random_table;
mod rex_assets; mod rex_assets;
// Embedded resources for use in wasm build // Embedded resources for use in wasm build
@ -49,6 +50,7 @@ pub enum RunState {
MainMenu { menu_selection: gui::MainMenuSelection }, MainMenu { menu_selection: gui::MainMenuSelection },
SaveGame, SaveGame,
NextLevel, NextLevel,
MagicMapReveal { row: i32, cursed: bool },
} }
pub struct State { pub struct State {
@ -119,16 +121,17 @@ impl State {
// Build new map // Build new map
let worldmap; let worldmap;
let current_depth;
{ {
let mut worldmap_resource = self.ecs.write_resource::<Map>(); let mut worldmap_resource = self.ecs.write_resource::<Map>();
let current_depth = worldmap_resource.depth; current_depth = worldmap_resource.depth;
*worldmap_resource = Map::new_map_rooms_and_corridors(current_depth + 1); *worldmap_resource = Map::new_map_rooms_and_corridors(current_depth + 1);
worldmap = worldmap_resource.clone(); worldmap = worldmap_resource.clone();
} }
// Spawn things in rooms // Spawn things in rooms
for room in worldmap.rooms.iter().skip(1) { for room in worldmap.rooms.iter().skip(1) {
spawner::spawn_room(&mut self.ecs, room); spawner::spawn_room(&mut self.ecs, room, current_depth + 1);
} }
// Place the player and update resources // Place the player and update resources
@ -213,7 +216,12 @@ impl GameState for State {
RunState::PlayerTurn => { RunState::PlayerTurn => {
self.run_systems(); self.run_systems();
self.ecs.maintain(); self.ecs.maintain();
new_runstate = RunState::MonsterTurn; match *self.ecs.fetch::<RunState>() {
RunState::MagicMapReveal { row, cursed } => {
new_runstate = RunState::MagicMapReveal { row: row, cursed: cursed }
}
_ => new_runstate = RunState::MonsterTurn,
}
} }
RunState::MonsterTurn => { RunState::MonsterTurn => {
self.run_systems(); self.run_systems();
@ -308,6 +316,37 @@ impl GameState for State {
self.goto_next_level(); self.goto_next_level();
new_runstate = RunState::PreRun; new_runstate = RunState::PreRun;
} }
RunState::MagicMapReveal { row, cursed } => {
let mut map = self.ecs.fetch_mut::<Map>();
for x in 0..MAPWIDTH {
let top_idx = map.xy_idx(x as i32, row);
let bottom_idx = map.xy_idx(x as i32, (MAPHEIGHT as i32 - 1) - row);
if !cursed {
map.revealed_tiles[top_idx] = true;
map.revealed_tiles[bottom_idx] = true;
} else {
map.revealed_tiles[top_idx] = false;
map.revealed_tiles[bottom_idx] = false;
}
}
// Dirtify viewshed only if cursed, so our currently visible tiles aren't removed too
if cursed {
let player_entity = self.ecs.fetch::<Entity>();
let mut viewshed_components = self.ecs.write_storage::<Viewshed>();
let viewshed = viewshed_components.get_mut(*player_entity);
if let Some(viewshed) = viewshed {
viewshed.dirty = true;
}
}
if row as usize == MAPHEIGHT / 2 {
new_runstate = RunState::MonsterTurn;
} else {
new_runstate = RunState::MagicMapReveal { row: row + 1, cursed: cursed };
}
}
} }
{ {
@ -349,11 +388,13 @@ 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::<Cursed>();
gs.ecs.register::<ProvidesHealing>(); gs.ecs.register::<ProvidesHealing>();
gs.ecs.register::<InflictsDamage>(); gs.ecs.register::<InflictsDamage>();
gs.ecs.register::<Ranged>(); gs.ecs.register::<Ranged>();
gs.ecs.register::<AOE>(); gs.ecs.register::<AOE>();
gs.ecs.register::<Confusion>(); gs.ecs.register::<Confusion>();
gs.ecs.register::<MagicMapper>();
gs.ecs.register::<InBackpack>(); gs.ecs.register::<InBackpack>();
gs.ecs.register::<WantsToPickupItem>(); gs.ecs.register::<WantsToPickupItem>();
gs.ecs.register::<WantsToDropItem>(); gs.ecs.register::<WantsToDropItem>();
@ -372,7 +413,7 @@ fn main() -> rltk::BError {
gs.ecs.insert(rltk::RandomNumberGenerator::new()); gs.ecs.insert(rltk::RandomNumberGenerator::new());
for room in map.rooms.iter().skip(1) { for room in map.rooms.iter().skip(1) {
spawner::spawn_room(&mut gs.ecs, room); spawner::spawn_room(&mut gs.ecs, room, 1);
} }
gs.ecs.insert(map); gs.ecs.insert(map);

View file

@ -1,5 +1,5 @@
use super::{ use super::{
gamelog::GameLog, CombatStats, Item, Map, Monster, Player, Position, RunState, State, TileType, Viewshed, gamelog::GameLog, CombatStats, Item, Map, Monster, Name, Player, Position, RunState, State, TileType, Viewshed,
WantsToMelee, WantsToPickupItem, MAPHEIGHT, MAPWIDTH, WantsToMelee, WantsToPickupItem, MAPHEIGHT, MAPWIDTH,
}; };
use rltk::{Point, RandomNumberGenerator, Rltk, VirtualKeyCode}; use rltk::{Point, RandomNumberGenerator, Rltk, VirtualKeyCode};
@ -35,6 +35,22 @@ pub fn try_move_player(delta_x: i32, delta_y: i32, ecs: &mut World) {
} }
if !map.blocked[destination_idx] { if !map.blocked[destination_idx] {
// TODO: Refactor
let mut tile_content = "You see ".to_string();
let names = ecs.read_storage::<Name>();
for entity in map.tile_content[destination_idx].iter() {
if let Some(name) = names.get(*entity) {
if tile_content != "You see " {
tile_content.push_str(", ");
}
tile_content.push_str(&name.name);
}
}
if tile_content != "You see " {
tile_content.push_str(".");
let mut gamelog = ecs.write_resource::<GameLog>();
gamelog.entries.push(tile_content);
}
pos.x = min((MAPWIDTH as i32) - 1, max(0, pos.x + delta_x)); pos.x = min((MAPWIDTH as i32) - 1, max(0, pos.x + delta_x));
pos.y = min((MAPHEIGHT as i32) - 1, max(0, pos.y + delta_y)); pos.y = min((MAPHEIGHT as i32) - 1, max(0, pos.y + delta_y));
viewshed.dirty = true; viewshed.dirty = true;

67
src/random_table.rs Normal file
View file

@ -0,0 +1,67 @@
use rltk::RandomNumberGenerator;
// FIXME: note to self,
// passing around strings here is super inefficient, so this is
// a good place to look for optimisation. Using a unique ID here
// for every entry on the table and returning that instead of the
// name would be helpful. That said, these tables see low enough
// use that reducing readability and confusing things right now
// seems like a waste of time.
pub struct RandomEntry {
name: String,
weight: i32,
}
impl RandomEntry {
pub fn new<S: ToString>(name: S, weight: i32) -> RandomEntry {
RandomEntry { name: name.to_string(), weight }
}
}
#[derive(Default)]
pub struct RandomTable {
entries: Vec<RandomEntry>,
total_weight: i32,
}
impl RandomTable {
/// Creates a new, blank RandomTable
pub fn new() -> RandomTable {
return RandomTable { entries: Vec::new(), total_weight: 0 };
}
/// Adds an entry to an existing RandomTable
pub fn add<S: ToString>(mut self, name: S, weight: i32) -> RandomTable {
self.total_weight += weight;
self.entries.push(RandomEntry::new(name.to_string(), weight));
return self;
}
/// Rolls on an existing RandomTable
pub fn roll(&self, rng: &mut RandomNumberGenerator) -> String {
// If the table has no weight, return nothing.
if self.total_weight == 0 {
return "None".to_string();
}
// If the table has weight, roll a die, and iterate through
// every index on the RandomTable. If the roll is below the
// weight of the current index, return it - otherwise, reduce
// the roll by the weight and test the next entry.
let mut roll = rng.roll_dice(1, self.total_weight) - 1;
let mut index: usize = 0;
while roll > 0 {
if roll < self.entries[index].weight {
return self.entries[index].name.clone();
}
roll -= self.entries[index].weight;
index += 1;
}
// If the rolling fails to produce anything (i.e. there is no
// item on the table with a weight large to be spawned
// by the roll) then return nothing.
return "None".to_string();
}
}

View file

@ -51,12 +51,14 @@ pub fn save_game(ecs: &mut World) {
SufferDamage, SufferDamage,
WantsToMelee, WantsToMelee,
Item, Item,
Cursed,
Consumable, Consumable,
Destructible, Destructible,
Ranged, Ranged,
InflictsDamage, InflictsDamage,
AOE, AOE,
Confusion, Confusion,
MagicMapper,
ProvidesHealing, ProvidesHealing,
InBackpack, InBackpack,
WantsToPickupItem, WantsToPickupItem,
@ -126,12 +128,14 @@ pub fn load_game(ecs: &mut World) {
SufferDamage, SufferDamage,
WantsToMelee, WantsToMelee,
Item, Item,
Cursed,
Consumable, Consumable,
Destructible, Destructible,
Ranged, Ranged,
InflictsDamage, InflictsDamage,
AOE, AOE,
Confusion, Confusion,
MagicMapper,
ProvidesHealing, ProvidesHealing,
InBackpack, InBackpack,
WantsToPickupItem, WantsToPickupItem,

View file

@ -1,10 +1,12 @@
use super::{ use super::{
BlocksTile, CombatStats, Confusion, Consumable, Destructible, InflictsDamage, Item, Monster, Name, Player, random_table::RandomTable, BlocksTile, CombatStats, Confusion, Consumable, Cursed, Destructible, InflictsDamage,
Position, ProvidesHealing, Ranged, Rect, Renderable, SerializeMe, Viewshed, AOE, MAPWIDTH, Item, MagicMapper, Monster, Name, Player, Position, ProvidesHealing, Ranged, Rect, Renderable, SerializeMe,
Viewshed, AOE, MAPWIDTH,
}; };
use rltk::{RandomNumberGenerator, RGB}; use rltk::{RandomNumberGenerator, RGB};
use specs::prelude::*; use specs::prelude::*;
use specs::saveload::{MarkedBuilder, SimpleMarker}; use specs::saveload::{MarkedBuilder, SimpleMarker};
use std::collections::HashMap;
/// Spawns the player and returns his/her entity object. /// Spawns the player and returns his/her entity object.
pub fn player(ecs: &mut World, player_x: i32, player_y: i32, player_name: String) -> Entity { pub fn player(ecs: &mut World, player_x: i32, player_y: i32, player_name: String) -> Entity {
@ -25,39 +27,6 @@ pub fn player(ecs: &mut World, player_x: i32, player_y: i32, player_name: String
.build() .build()
} }
/// Spawns a random monster at a given loc
pub fn random_monster(ecs: &mut World, x: i32, y: i32) {
let roll: i32;
{
let mut rng = ecs.write_resource::<RandomNumberGenerator>();
roll = rng.roll_dice(1, 3);
}
match roll {
1 => orc(ecs, x, y),
2 => goblin_chieftain(ecs, x, y),
_ => goblin(ecs, x, y),
}
}
/// Spawns a random item at a given loc
pub fn random_item(ecs: &mut World, x: i32, y: i32) {
let roll: i32;
{
let mut rng = ecs.write_resource::<RandomNumberGenerator>();
roll = rng.roll_dice(1, 6);
}
match roll {
1 => health_potion(ecs, x, y),
2 => poison_potion(ecs, x, y),
3 => magic_missile_scroll(ecs, x, y),
4 => fireball_scroll(ecs, x, y),
5 => confusion_scroll(ecs, x, y),
_ => weak_health_potion(ecs, x, y),
}
}
const MAX_MONSTERS: i32 = 4;
const MAX_ITEMS: i32 = 3;
fn monster<S: ToString>(ecs: &mut World, x: i32, y: i32, glyph: rltk::FontCharType, name: S, hit_die: i32) { fn monster<S: ToString>(ecs: &mut World, x: i32, y: i32, glyph: rltk::FontCharType, name: S, hit_die: i32) {
let rolled_hp = roll_hit_dice(ecs, 1, hit_die); let rolled_hp = roll_hit_dice(ecs, 1, hit_die);
@ -96,56 +65,82 @@ pub fn roll_hit_dice(ecs: &mut World, n: i32, d: i32) -> i32 {
return rolled_hp; return rolled_hp;
} }
pub fn spawn_room(ecs: &mut World, room: &Rect) { // Consts
let mut monster_spawn_points: Vec<usize> = Vec::new(); const MAX_ENTITIES: i32 = 4;
let mut item_spawn_points: Vec<usize> = Vec::new();
#[allow(clippy::map_entry)]
pub fn spawn_room(ecs: &mut World, room: &Rect, map_depth: i32) {
let spawn_table = room_table(map_depth);
let mut spawn_points: HashMap<usize, String> = HashMap::new();
// Scope for borrow checker // Scope for borrow checker
{ {
let mut rng = ecs.write_resource::<RandomNumberGenerator>(); let mut rng = ecs.write_resource::<RandomNumberGenerator>();
let num_monsters = rng.roll_dice(1, MAX_MONSTERS + 2) - 3; let num_spawns = rng.roll_dice(1, MAX_ENTITIES + 3) + (map_depth - 1) - 3;
let num_items = rng.roll_dice(1, MAX_ITEMS + 2) - 3; // With a MAX_ENTITIES of 4, this means each room has between:
// d1: -2 to 4
// d2: -1 to 5
// d3: 0 to 6
// etc.
for _i in 0..num_monsters { for _i in 0..num_spawns {
let mut added = false; let mut added = false;
while !added { let mut tries = 0;
while !added && tries < 20 {
let x = (room.x1 + rng.roll_dice(1, i32::abs(room.x2 - room.x1))) as usize; let x = (room.x1 + rng.roll_dice(1, i32::abs(room.x2 - room.x1))) as usize;
let y = (room.y1 + rng.roll_dice(1, i32::abs(room.y2 - room.y1))) as usize; let y = (room.y1 + rng.roll_dice(1, i32::abs(room.y2 - room.y1))) as usize;
let idx = (y * MAPWIDTH) + x; let idx = (y * MAPWIDTH) + x;
if !monster_spawn_points.contains(&idx) { if !spawn_points.contains_key(&idx) {
monster_spawn_points.push(idx); spawn_points.insert(idx, spawn_table.roll(&mut rng));
added = true;
}
}
}
for _i in 0..num_items {
let mut added = false;
while !added {
let x = (room.x1 + rng.roll_dice(1, i32::abs(room.x2 - room.x1))) as usize;
let y = (room.y1 + rng.roll_dice(1, i32::abs(room.y2 - room.y1))) as usize;
let idx = (y * MAPWIDTH) + x;
if !item_spawn_points.contains(&idx) {
item_spawn_points.push(idx);
added = true; added = true;
} else {
tries += 1;
} }
} }
} }
} }
// Spawn // Spawn
for idx in monster_spawn_points.iter() { for spawn in spawn_points.iter() {
let x = *idx % MAPWIDTH; let x = (*spawn.0 % MAPWIDTH) as i32;
let y = *idx / MAPWIDTH; let y = (*spawn.0 / MAPWIDTH) as i32;
random_monster(ecs, x as i32, y as i32);
} match spawn.1.as_ref() {
for idx in item_spawn_points.iter() { // Monsters
let x = *idx % MAPWIDTH; "goblin" => goblin(ecs, x, y),
let y = *idx / MAPWIDTH; "goblin chieftain" => goblin_chieftain(ecs, x, y),
random_item(ecs, x as i32, y as i32); "orc" => orc(ecs, x, y),
// Potions
"weak health potion" => weak_health_potion(ecs, x, y),
"health potion" => health_potion(ecs, x, y),
// Scrolls
"fireball scroll" => fireball_scroll(ecs, x, y),
"confusion scroll" => confusion_scroll(ecs, x, y),
"magic missile scroll" => magic_missile_scroll(ecs, x, y),
"magic map scroll" => magic_map_scroll(ecs, x, y),
"cursed magic map scroll" => cursed_magic_map_scroll(ecs, x, y),
_ => {}
}
} }
} }
fn room_table(map_depth: i32) -> RandomTable {
return RandomTable::new()
// Monsters
.add("goblin", 15)
.add("goblin chieftain", 2 + map_depth)
.add("orc", 4 + map_depth)
// Potions
.add("weak health potion", 4)
.add("health potion", 1 + map_depth)
// Scrolls
.add("fireball scroll", 1 + map_depth)
.add("confusion scroll", 1)
.add("magic missile scroll", 4)
.add("magic map scroll", 400)
.add("cursed magic map scroll", 400);
}
fn health_potion(ecs: &mut World, x: i32, y: i32) { fn health_potion(ecs: &mut World, x: i32, y: i32) {
ecs.create_entity() ecs.create_entity()
.with(Position { x, y }) .with(Position { x, y })
@ -182,6 +177,7 @@ fn weak_health_potion(ecs: &mut World, x: i32, y: i32) {
.build(); .build();
} }
/*
fn poison_potion(ecs: &mut World, x: i32, y: i32) { fn poison_potion(ecs: &mut World, x: i32, y: i32) {
ecs.create_entity() ecs.create_entity()
.with(Position { x, y }) .with(Position { x, y })
@ -199,6 +195,7 @@ fn poison_potion(ecs: &mut World, x: i32, y: i32) {
.marked::<SimpleMarker<SerializeMe>>() .marked::<SimpleMarker<SerializeMe>>()
.build(); .build();
} }
*/
// Scrolls // Scrolls
// ~10 range should be considered average here. // ~10 range should be considered average here.
@ -259,3 +256,40 @@ fn confusion_scroll(ecs: &mut World, x: i32, y: i32) {
.marked::<SimpleMarker<SerializeMe>>() .marked::<SimpleMarker<SerializeMe>>()
.build(); .build();
} }
fn magic_map_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::ROYALBLUE),
bg: RGB::named(rltk::BLACK),
render_order: 2,
})
.with(Name { name: "scroll of magic mapping".to_string() })
.with(Item {})
.with(MagicMapper {})
.with(Consumable {})
.with(Destructible {})
.marked::<SimpleMarker<SerializeMe>>()
.build();
}
fn cursed_magic_map_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::ROYALBLUE),
bg: RGB::named(rltk::BLACK),
render_order: 2,
})
.with(Name { name: "cursed scroll of magic mapping".to_string() })
.with(Item {})
.with(Cursed {})
.with(MagicMapper {})
.with(Consumable {})
.with(Destructible {})
.marked::<SimpleMarker<SerializeMe>>()
.build();
}