Add more difficulty

This commit is contained in:
Kasper Juul Hermansen 2022-01-28 00:48:54 +01:00
parent e68fa87fc9
commit fb5b70ce3b
Signed by: kjuulh
GPG Key ID: DCD9397082D97069
7 changed files with 254 additions and 59 deletions

1
savegame.json Normal file

File diff suppressed because one or more lines are too long

View File

@ -53,6 +53,16 @@ pub fn draw_ui(ecs: &World, ctx: &mut Rltk) {
y += 1;
}
let map = ecs.fetch::<Map>();
let depth = format!("Depth: {}", map.depth);
ctx.print_color(
2,
43,
RGB::named(rltk::YELLOW),
RGB::named(rltk::BLACK),
&depth,
);
// Draw mouse
let mouse_pos = ctx.mouse_pos();
ctx.set_bg(mouse_pos.0, mouse_pos.1, RGB::named(rltk::MAGENTA));

View File

@ -13,6 +13,7 @@ use monster_ai_system::*;
use player::*;
use visibility_system::*;
use crate::gamelog::GameLog;
use crate::inventory_system::{ItemCollectionSystem, ItemDropSystem, ItemUseSystem};
mod components;
@ -25,6 +26,7 @@ mod map_indexing_system;
mod melee_combat_system;
mod monster_ai_system;
mod player;
mod random_table;
mod rect;
mod save_load_system;
mod spawner;
@ -46,12 +48,94 @@ pub enum RunState {
menu_selection: gui::MainMenuSelection,
},
SaveGame,
NextLevel,
}
pub struct State {
pub ecs: World,
}
impl State {
fn entities_to_remove_on_level_change(&mut self) -> Vec<Entity> {
let entities = self.ecs.entities();
let player = self.ecs.read_storage::<Player>();
let backpack = self.ecs.read_storage::<InBackpack>();
let player_entity = self.ecs.fetch::<Entity>();
let mut to_delete: Vec<Entity> = Vec::new();
for entity in entities.join() {
let mut should_delete = true;
let p = player.get(entity);
if let Some(p) = p {
should_delete = false;
}
let bp = backpack.get(entity);
if let Some(bp) = bp {
if bp.owner == *player_entity {
should_delete = false;
}
}
if should_delete {
to_delete.push(entity);
}
}
to_delete
}
fn goto_next_level(&mut self) {
let to_delete = self.entities_to_remove_on_level_change();
for target in to_delete {
self.ecs
.delete_entity(target)
.expect("Unable to delete entity")
}
let worldmap;
let current_depth;
{
let mut worldmap_resource = self.ecs.write_resource::<Map>();
current_depth = worldmap_resource.depth;
*worldmap_resource = Map::new_map_rooms_and_corridors(current_depth + 1);
worldmap = worldmap_resource.clone();
}
for room in worldmap.rooms.iter().skip(1) {
spawner::spawn_room(&mut self.ecs, room, current_depth + 1);
}
let (player_x, player_y) = worldmap.rooms[0].center();
let mut player_position = self.ecs.write_resource::<Point>();
*player_position = Point::new(player_x, player_y);
let mut position_components = self.ecs.write_storage::<Position>();
let player_entity = self.ecs.fetch::<Entity>();
let player_pos_comp = position_components.get_mut(*player_entity);
if let Some(player_pos) = player_pos_comp {
player_pos.x = player_x;
player_pos.y = player_y;
}
let mut viewshed_components = self.ecs.write_storage::<Viewshed>();
let vs = viewshed_components.get_mut(*player_entity);
if let Some(vs) = vs {
vs.dirty = true;
}
let mut gamelog = self.ecs.fetch_mut::<GameLog>();
gamelog
.entries
.push("You descend to the next level, and take a moment to heal".to_string());
let mut player_health_store = self.ecs.write_storage::<CombatStats>();
let player_health = player_health_store.get_mut(*player_entity);
if let Some(player_health) = player_health {
player_health.hp = i32::max(player_health.hp, player_health.max_hp / 2);
}
}
}
impl State {
fn run_systems(&mut self) {
let mut vis = VisibilitySystem {};
@ -221,6 +305,10 @@ impl GameState for State {
menu_selection: gui::MainMenuSelection::Quit,
};
}
RunState::NextLevel => {
self.goto_next_level();
new_run_state = RunState::PreRun;
}
}
{
@ -269,13 +357,13 @@ fn main() -> rltk::BError {
gs.ecs.insert(SimpleMarkerAllocator::<SerializeMe>::new());
let map = Map::new_map_rooms_and_corridors();
let map = Map::new_map_rooms_and_corridors(1);
let (player_x, player_y) = map.rooms[0].center();
let player_entity = spawner::player(&mut gs.ecs, player_x, player_y);
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);

View File

@ -10,6 +10,7 @@ use crate::rect::Rect;
pub enum TileType {
Wall,
Floor,
DownStairs,
}
pub const MAP_WIDTH: usize = 80;
@ -27,6 +28,7 @@ pub struct Map {
pub revealed_tiles: Vec<bool>,
pub visible_tiles: Vec<bool>,
pub blocked: Vec<bool>,
pub depth: i32,
#[serde(skip_serializing)]
#[serde(skip_deserializing)]
@ -85,7 +87,7 @@ impl Map {
}
}
pub fn new_map_rooms_and_corridors() -> Map {
pub fn new_map_rooms_and_corridors(new_depth: i32) -> Map {
let mut map = Map {
tiles: vec![TileType::Wall; MAP_COUNT],
rooms: Vec::new(),
@ -95,6 +97,7 @@ impl Map {
visible_tiles: vec![false; MAP_COUNT],
blocked: vec![false; MAP_COUNT],
tile_content: vec![Vec::new(); MAP_COUNT],
depth: new_depth,
};
const MAX_ROOMS: i32 = 30;
@ -134,6 +137,10 @@ impl Map {
}
}
let stairs_position = map.rooms[map.rooms.len() - 1].center();
let stairs_idx = map.xy_idx(stairs_position.0, stairs_position.1);
map.tiles[stairs_idx] = TileType::DownStairs;
map
}
}
@ -211,6 +218,11 @@ pub fn draw_map(ecs: &World, ctx: &mut Rltk) {
fg = RGB::from_f32(0., 1.0, 0.);
glyph = rltk::to_cp437('#');
}
TileType::DownStairs => {
glyph = rltk::to_cp437('>');
fg = RGB::from_f32(0., 1., 1.);
}
}
if !map.visible_tiles[idx] {
fg = fg.to_greyscale()

View File

@ -4,10 +4,11 @@ use rltk::{Point, Rltk, VirtualKeyCode};
use specs::prelude::*;
use crate::gamelog::GameLog;
use crate::spawner::player;
use crate::{
components::{CombatStats, Player, Position, Viewshed, WantsToMelee},
map::Map,
Item, RunState, State, WantsToPickupItem,
Item, Monster, RunState, State, TileType, WantsToPickupItem,
};
pub fn try_move_player(delta_x: i32, delta_y: i32, ecs: &mut World) {
@ -99,6 +100,7 @@ pub fn player_input(gs: &mut State, ctx: &mut Rltk) -> RunState {
VirtualKeyCode::Right | VirtualKeyCode::L => try_move_player(1, 0, &mut gs.ecs),
VirtualKeyCode::Up | VirtualKeyCode::K => try_move_player(0, -1, &mut gs.ecs),
VirtualKeyCode::Down | VirtualKeyCode::J => try_move_player(0, 1, &mut gs.ecs),
VirtualKeyCode::Space => return skip_turn(&mut gs.ecs),
VirtualKeyCode::Y => try_move_player(1, -1, &mut gs.ecs),
VirtualKeyCode::U => try_move_player(-1, -1, &mut gs.ecs),
VirtualKeyCode::N => try_move_player(1, 1, &mut gs.ecs),
@ -107,9 +109,56 @@ pub fn player_input(gs: &mut State, ctx: &mut Rltk) -> RunState {
VirtualKeyCode::I => return RunState::ShowInventory,
VirtualKeyCode::D => return RunState::ShowDropItem,
VirtualKeyCode::Escape => return RunState::SaveGame,
VirtualKeyCode::Period => {
if try_next_level(&mut gs.ecs) {
return RunState::NextLevel;
}
}
_ => return RunState::AwaitingInput,
},
}
RunState::PlayerTurn
}
fn skip_turn(ecs: &mut World) -> RunState {
let player_entity = ecs.fetch::<Entity>();
let viewshed_components = ecs.read_storage::<Viewshed>();
let monsters = ecs.read_storage::<Monster>();
let worldmap_resource = ecs.fetch::<Map>();
let mut can_heal = true;
let viewshed = viewshed_components.get(*player_entity).unwrap();
for tile in viewshed.visible_tiles.iter() {
let idx = worldmap_resource.xy_idx(tile.x, tile.y);
for entity_id in worldmap_resource.tile_content[idx].iter() {
if let Some(mob) = monsters.get(*entity_id) {
can_heal = true;
}
}
}
if can_heal {
let mut health_component = ecs.write_storage::<CombatStats>();
let player_hp = health_component.get_mut(*player_entity).unwrap();
player_hp.hp = i32::min(player_hp.hp + 1, player_hp.max_hp);
}
RunState::PlayerTurn
}
fn try_next_level(ecs: &mut World) -> bool {
let player_pos = ecs.fetch::<Point>();
let map = ecs.fetch::<Map>();
let player_idx = map.xy_idx(player_pos.x, player_pos.y);
if map.tiles[player_idx] == TileType::DownStairs {
true
} else {
let mut gamelog = ecs.fetch_mut::<GameLog>();
gamelog
.entries
.push("There is no way down from here".to_string());
false
}
}

55
src/random_table.rs Normal file
View File

@ -0,0 +1,55 @@
use rltk::RandomNumberGenerator;
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 {
pub fn new() -> RandomTable {
RandomTable {
total_weight: 0,
entries: Vec::new(),
}
}
pub fn add<S: ToString>(mut self, name: S, weight: i32) -> RandomTable {
self.total_weight += weight;
self.entries.push(RandomEntry::new(name, weight));
self
}
pub fn roll(&self, rng: &mut RandomNumberGenerator) -> String {
if self.total_weight == 0 {
return "None".to_string();
}
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;
}
"None".to_string()
}
}

View File

@ -1,7 +1,10 @@
use std::collections::HashMap;
use rltk::{FontCharType, RandomNumberGenerator, RGB};
use specs::prelude::*;
use specs::saveload::{MarkedBuilder, SimpleMarker};
use crate::random_table::RandomTable;
use crate::rect::Rect;
use crate::{
AreaOfEffect, BlocksTile, CombatStats, Confusion, Consumable, InflictsDamage, Item, Monster,
@ -40,18 +43,6 @@ pub fn player(ecs: &mut World, player_x: i32, player_y: i32) -> Entity {
.build()
}
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, 2);
}
match roll {
1 => orc(ecs, x, y),
_ => goblin(ecs, x, y),
}
}
fn orc(ecs: &mut World, x: i32, y: i32) {
monster(ecs, x, y, rltk::to_cp437('o'), "Orc")
}
@ -89,52 +80,45 @@ fn monster<S: ToString>(ecs: &mut World, x: i32, y: i32, glyph: FontCharType, na
.build();
}
pub fn spawn_room(ecs: &mut World, room: &Rect) {
let mut monster_spawn_points: Vec<usize> = Vec::new();
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();
{
let mut rng = ecs.write_resource::<RandomNumberGenerator>();
let num_monsters = rng.roll_dice(1, MAX_MONSTER + 2) - 3;
let num_items = rng.roll_dice(1, MAX_ITEMS + 2) - 3;
let num_spawns = rng.roll_dice(1, MAX_MONSTER + 3) + (map_depth - 1) - 3;
for _i in 0..num_monsters {
for _i in 0..num_spawns {
let mut added = false;
while !added {
let mut tried = 0;
while !added && tried < 20 {
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 * MAP_WIDTH) + x;
if !monster_spawn_points.contains(&idx) {
monster_spawn_points.push(idx);
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 * MAP_WIDTH) + x;
if !item_spawn_points.contains(&idx) {
item_spawn_points.push(idx);
if !spawn_points.contains_key(&idx) {
spawn_points.insert(idx, spawn_table.roll(&mut rng));
added = true;
} else {
tried += 1;
}
}
}
}
for idx in monster_spawn_points.iter() {
let x = *idx % MAP_WIDTH;
let y = *idx / MAP_WIDTH;
random_monster(ecs, x as i32, y as i32);
}
for spawn in spawn_points.iter() {
let x = (*spawn.0 % MAP_WIDTH) as i32;
let y = (*spawn.0 / MAP_WIDTH) as i32;
for idx in item_spawn_points.iter() {
let x = *idx % MAP_WIDTH;
let y = *idx / MAP_WIDTH;
random_item(ecs, x as i32, y as i32);
match spawn.1.as_ref() {
"Goblin" => goblin(ecs, x, y),
"Orc" => orc(ecs, x, y),
"Health Potion" => health_potion(ecs, x, y),
"Fireball Scroll" => fireball_scroll(ecs, x, y),
"Confusion Scroll" => confusion_scroll(ecs, x, y),
"Magic Missile Scroll" => magic_missile_scroll(ecs, x, y),
_ => {}
}
}
}
@ -218,16 +202,12 @@ pub fn confusion_scroll(ecs: &mut World, x: i32, y: i32) {
.build();
}
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, 4);
}
match roll {
1 => health_potion(ecs, x, y),
2 => fireball_scroll(ecs, x, y),
3 => confusion_scroll(ecs, x, y),
_ => magic_missile_scroll(ecs, x, y),
}
pub fn room_table(map_depth: i32) -> RandomTable {
RandomTable::new()
.add("Goblin", 10)
.add("Orc", 1 + map_depth)
.add("Health Potion", 7)
.add("Fireball Scroll", 2 + map_depth)
.add("Confusion Scroll", 2 + map_depth)
.add("Magic Missile Scroll", 4)
}