This commit is contained in:
Kasper Juul Hermansen 2022-01-29 21:27:59 +01:00
parent fa71410453
commit ce4eb0b4cf
Signed by: kjuulh
GPG Key ID: DCD9397082D97069
6 changed files with 480 additions and 450 deletions

File diff suppressed because one or more lines are too long

View File

@ -14,13 +14,16 @@ use player::*;
use visibility_system::*; use visibility_system::*;
use crate::gamelog::GameLog; use crate::gamelog::GameLog;
use crate::gui::MainMenuSelection;
use crate::healing_system::HealingSystem; use crate::healing_system::HealingSystem;
use crate::hunger_system::HungerSystem; use crate::hunger_system::HungerSystem;
use crate::inventory_system::{ use crate::inventory_system::{
ItemCollectionSystem, ItemDropSystem, ItemRemoveSystem, ItemUseSystem, ItemCollectionSystem, ItemDropSystem, ItemRemoveSystem, ItemUseSystem,
}; };
use crate::particle_system::ParticleSpawnSystem; use crate::particle_system::ParticleSpawnSystem;
use crate::state::{RunState, State};
use crate::trigger_system::TriggerSystem; use crate::trigger_system::TriggerSystem;
use crate::RunState::MapGeneration;
mod components; mod components;
mod damage_system; mod damage_system;
@ -30,7 +33,7 @@ mod healing_system;
mod hunger_system; mod hunger_system;
mod inventory_system; mod inventory_system;
mod map; mod map;
pub mod map_builders; mod map_builders;
mod map_indexing_system; mod map_indexing_system;
mod melee_combat_system; mod melee_combat_system;
mod monster_ai_system; mod monster_ai_system;
@ -41,428 +44,11 @@ mod rect;
mod rex_assets; mod rex_assets;
mod save_load_system; mod save_load_system;
mod spawner; mod spawner;
mod state;
mod trigger_system; mod trigger_system;
mod visibility_system; mod visibility_system;
#[derive(PartialEq, Copy, Clone)] const SHOW_MAPGEN_VISUALIZER: bool = true;
pub enum RunState {
AwaitingInput,
PreRun,
PlayerTurn,
MonsterTurn,
ShowInventory,
ShowDropItem,
ShowTargeting {
range: i32,
item: Entity,
},
MainMenu {
menu_selection: gui::MainMenuSelection,
},
SaveGame,
NextLevel,
ShowRemoveItem,
GameOver,
MagicMapReveal {
row: i32,
},
}
pub struct State {
pub ecs: World,
}
impl State {
pub fn game_over_cleanup(&mut self) {
// Delete everything
let mut to_delete = Vec::new();
for e in self.ecs.entities().join() {
to_delete.push(e);
}
for del in to_delete.iter() {
self.ecs.delete_entity(*del).expect("Deletion failed");
}
// Build a new map and place the player
let mut map_builder = map_builders::new_random_builder(1);
let worldmap;
let player_start;
{
let mut worldmap_resource = self.ecs.write_resource::<Map>();
map_builder.build_map();
*worldmap_resource = map_builder.get_map();
player_start = map_builder.get_starting_position();
worldmap = worldmap_resource.clone();
}
// Spawn bad guys
map_builder.spawn_entities(&mut self.ecs);
// Place the player and update resources
let (player_x, player_y) = (player_start.x, player_start.y);
let player_entity = spawner::player(&mut self.ecs, player_x, player_y);
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 mut player_entity_writer = self.ecs.write_resource::<Entity>();
*player_entity_writer = player_entity;
let player_pos_comp = position_components.get_mut(player_entity);
if let Some(player_pos_comp) = player_pos_comp {
player_pos_comp.x = player_x;
player_pos_comp.y = player_y;
}
// Mark the player's visibility as dirty
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;
}
}
}
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 equipped = self.ecs.read_storage::<Equipped>();
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 let Some(eq) = equipped.get(entity) {
if eq.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 mut map_builder;
let worldmap;
let current_depth;
let player_start;
{
let mut worldmap_resource = self.ecs.write_resource::<Map>();
current_depth = worldmap_resource.depth;
map_builder = map_builders::new_random_builder(current_depth + 1);
map_builder.build_map();
*worldmap_resource = map_builder.get_map();
player_start = map_builder.get_starting_position();
worldmap = worldmap_resource.clone();
}
map_builder.spawn_entities(&mut self.ecs);
let (player_x, player_y) = (player_start.x, player_start.y);
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 {};
vis.run_now(&self.ecs);
let mut mob = MonsterAI {};
mob.run_now(&self.ecs);
let mut trigger = TriggerSystem {};
trigger.run_now(&self.ecs);
let mut map_index = MapIndexingSystem {};
map_index.run_now(&self.ecs);
let mut melee_system = MeleeCombatSystem {};
melee_system.run_now(&self.ecs);
let mut damage_system = DamageSystem {};
damage_system.run_now(&self.ecs);
let mut healing_system = HealingSystem {};
healing_system.run_now(&self.ecs);
let mut inventory = ItemCollectionSystem {};
inventory.run_now(&self.ecs);
let mut potions = ItemUseSystem {};
potions.run_now(&self.ecs);
let mut drop_items = ItemDropSystem {};
drop_items.run_now(&self.ecs);
let mut remove_items = ItemRemoveSystem {};
remove_items.run_now(&self.ecs);
let mut hunger = HungerSystem {};
hunger.run_now(&self.ecs);
let mut particle_spawn = ParticleSpawnSystem {};
particle_spawn.run_now(&self.ecs);
self.ecs.maintain();
}
}
impl GameState for State {
fn tick(&mut self, ctx: &mut rltk::Rltk) {
let mut new_run_state;
{
let run_state = self.ecs.fetch::<RunState>();
new_run_state = *run_state;
}
ctx.cls();
particle_system::cull_dead_particles(&mut self.ecs, ctx);
match new_run_state {
RunState::MainMenu { .. } => {}
_ => {
draw_map(&self.ecs, ctx);
let positions = self.ecs.read_storage::<Position>();
let renderables = self.ecs.read_storage::<Renderable>();
let hidden = self.ecs.read_storage::<Hidden>();
let map = self.ecs.fetch::<Map>();
let mut data = (&positions, &renderables, !&hidden)
.join()
.collect::<Vec<_>>();
data.sort_by(|&a, &b| b.1.render_order.cmp(&a.1.render_order));
for (pos, render, _hidden) in data.iter() {
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)
}
}
gui::draw_ui(&self.ecs, ctx);
}
}
match new_run_state {
RunState::PreRun => {
self.run_systems();
new_run_state = RunState::AwaitingInput;
}
RunState::AwaitingInput => new_run_state = player_input(self, ctx),
RunState::PlayerTurn => {
self.run_systems();
new_run_state = RunState::MonsterTurn;
match *self.ecs.fetch::<RunState>() {
RunState::MagicMapReveal { .. } => {
new_run_state = RunState::MagicMapReveal { row: 0 }
}
_ => {
new_run_state = RunState::MonsterTurn;
}
}
}
RunState::MonsterTurn => {
self.run_systems();
new_run_state = RunState::AwaitingInput;
}
RunState::ShowInventory => {
let result = gui::show_inventory(self, ctx);
match result.0 {
gui::ItemMenuResult::Cancel => new_run_state = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => {
let item_entity = result.1.unwrap();
let is_ranged = self.ecs.read_storage::<Ranged>();
let is_item_ranged = is_ranged.get(item_entity);
if let Some(is_item_ranged) = is_item_ranged {
new_run_state = RunState::ShowTargeting {
range: is_item_ranged.range,
item: item_entity,
}
} else {
let mut intent = self.ecs.write_storage::<WantsToUseItem>();
intent
.insert(
*self.ecs.fetch::<Entity>(),
WantsToUseItem {
item: item_entity,
target: None,
},
)
.expect("Unable to insert intent");
new_run_state = RunState::PlayerTurn;
}
}
}
}
RunState::ShowDropItem => {
let result = gui::drop_item_menu(self, ctx);
match result.0 {
gui::ItemMenuResult::Cancel => new_run_state = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => {
let item_entity = result.1.unwrap();
let mut intent = self.ecs.write_storage::<WantsToDropItem>();
intent
.insert(
*self.ecs.fetch::<Entity>(),
WantsToDropItem { item: item_entity },
)
.expect("Unable to insert intent");
new_run_state = RunState::PlayerTurn;
}
}
}
RunState::ShowTargeting { range, item } => {
let result = gui::ranged_target(self, ctx, range);
match result.0 {
gui::ItemMenuResult::Cancel => new_run_state = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => {
let mut intent = self.ecs.write_storage::<WantsToUseItem>();
intent
.insert(
*self.ecs.fetch::<Entity>(),
WantsToUseItem {
item,
target: result.1,
},
)
.expect("Unable to insert intent");
new_run_state = RunState::PlayerTurn;
}
}
}
RunState::MainMenu { .. } => {
let result = gui::main_menu(self, ctx);
match result {
gui::MainMenuResult::NoSelection { selected } => {
new_run_state = RunState::MainMenu {
menu_selection: selected,
}
}
gui::MainMenuResult::Selected { selected } => match selected {
gui::MainMenuSelection::NewGame => new_run_state = RunState::PreRun,
gui::MainMenuSelection::LoadGame => {
save_load_system::load_game(&mut self.ecs);
new_run_state = RunState::AwaitingInput;
save_load_system::delete_save();
}
gui::MainMenuSelection::Quit => ::std::process::exit(0),
},
}
}
RunState::SaveGame => {
save_load_system::save_game(&mut self.ecs);
new_run_state = RunState::MainMenu {
menu_selection: gui::MainMenuSelection::Quit,
};
}
RunState::NextLevel => {
self.goto_next_level();
new_run_state = RunState::PreRun;
}
RunState::ShowRemoveItem => {
let result = gui::remove_item_menu(self, ctx);
match result.0 {
gui::ItemMenuResult::Cancel => new_run_state = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => {
let item_entity = result.1.unwrap();
let mut intent = self.ecs.write_storage::<WantsToRemoveItem>();
intent
.insert(
*self.ecs.fetch::<Entity>(),
WantsToRemoveItem { item: item_entity },
)
.expect("Unable to insert intent");
new_run_state = RunState::PlayerTurn;
}
}
}
RunState::GameOver => {
let result = gui::game_over(ctx);
match result {
gui::GameOverResult::NoSelection => {}
gui::GameOverResult::QuitToMenu => {
self.game_over_cleanup();
new_run_state = RunState::MainMenu {
menu_selection: gui::MainMenuSelection::NewGame,
};
}
}
}
RunState::MagicMapReveal { row } => {
let mut map = self.ecs.fetch_mut::<Map>();
for x in 0..MAP_WIDTH {
let idx = map.xy_idx(x as i32, row);
map.revealed_tiles[idx] = true;
}
if row as usize == MAP_HEIGHT - 1 {
new_run_state = RunState::MonsterTurn;
} else {
new_run_state = RunState::MagicMapReveal { row: row + 1 }
}
}
}
{
let mut run_writer = self.ecs.write_resource::<RunState>();
*run_writer = new_run_state;
}
damage_system::delete_the_dead(&mut self.ecs);
}
}
fn main() -> rltk::BError { fn main() -> rltk::BError {
use rltk::RltkBuilder; use rltk::RltkBuilder;
@ -472,11 +58,7 @@ fn main() -> rltk::BError {
.with_dimensions(80 * 3, 50 * 3) .with_dimensions(80 * 3, 50 * 3)
.build()?; .build()?;
context.with_post_scanlines(true); context.with_post_scanlines(true);
let mut gs = State { ecs: World::new() }; let mut gs = State::new();
gs.ecs.insert(rltk::RandomNumberGenerator::new());
gs.ecs.insert(particle_system::ParticleBuilder::new());
gs.ecs.insert(rex_assets::RexAssets::new());
gs.ecs.register::<Position>(); gs.ecs.register::<Position>();
gs.ecs.register::<Renderable>(); gs.ecs.register::<Renderable>();
@ -518,24 +100,19 @@ fn main() -> rltk::BError {
gs.ecs.insert(SimpleMarkerAllocator::<SerializeMe>::new()); gs.ecs.insert(SimpleMarkerAllocator::<SerializeMe>::new());
let mut map_builder = map_builders::new_random_builder(1); gs.ecs.insert(Map::new(1));
map_builder.build_map(); gs.ecs.insert(Point::new(0, 0));
let player_pos = map_builder.get_starting_position(); gs.ecs.insert(rltk::RandomNumberGenerator::new());
let mut map = map_builder.get_map(); let player_entity = spawner::player(&mut gs.ecs, 0, 0);
let (player_x, player_y) = (player_pos.x, player_pos.y);
let player_entity = spawner::player(&mut gs.ecs, player_x, player_y);
map_builder.spawn_entities(&mut gs.ecs);
gs.ecs.insert(map);
gs.ecs.insert(Point::new(player_x, player_y));
gs.ecs.insert(player_entity); gs.ecs.insert(player_entity);
gs.ecs.insert(RunState::MainMenu { gs.ecs.insert(RunState::MapGeneration {});
menu_selection: gui::MainMenuSelection::NewGame,
});
gs.ecs.insert(gamelog::GameLog { gs.ecs.insert(gamelog::GameLog {
entries: vec!["Welcome to Rusty Roguelike".to_string()], entries: vec!["Welcome to Rusty Roguelike".to_string()],
}); });
gs.ecs.insert(particle_system::ParticleBuilder::new());
gs.ecs.insert(rex_assets::RexAssets::new());
gs.generate_world_map(1);
rltk::main_loop(context, gs) rltk::main_loop(context, gs)
} }

View File

@ -1,6 +1,6 @@
use std::collections::HashSet; use std::collections::HashSet;
use rltk::{Algorithm2D, BaseMap, FontCharType, Point, RGB, Rltk}; use rltk::{Algorithm2D, BaseMap, FontCharType, Point, Rltk, RGB};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use specs::prelude::*; use specs::prelude::*;
@ -128,9 +128,7 @@ impl Algorithm2D for Map {
} }
} }
pub fn draw_map(ecs: &World, ctx: &mut Rltk) { pub fn draw_map(map: &Map, ctx: &mut Rltk) {
let map = ecs.fetch::<Map>();
let mut y = 0; let mut y = 0;
let mut x = 0; let mut x = 0;
for (idx, tile) in map.tiles.iter().enumerate() { for (idx, tile) in map.tiles.iter().enumerate() {

View File

@ -1,16 +1,18 @@
use specs::World; use specs::World;
use crate::{Map, Position};
use crate::map_builders::simple_map::SimpleMapBuilder; use crate::map_builders::simple_map::SimpleMapBuilder;
use crate::{Map, Position};
pub mod common; mod common;
pub mod simple_map; mod simple_map;
pub trait MapBuilder { pub trait MapBuilder {
fn build_map(&mut self); fn build_map(&mut self);
fn spawn_entities(&mut self, ecs: &mut World); fn spawn_entities(&mut self, ecs: &mut World);
fn get_map(&self) -> Map; fn get_map(&self) -> Map;
fn get_starting_position(&self) -> Position; fn get_starting_position(&self) -> Position;
fn get_snapshot_history(&self) -> Vec<Map>;
fn take_snapshot(&mut self);
} }
pub fn new_random_builder(new_depth: i32) -> Box<dyn MapBuilder> { pub fn new_random_builder(new_depth: i32) -> Box<dyn MapBuilder> {

View File

@ -1,15 +1,16 @@
use rltk::RandomNumberGenerator; use rltk::RandomNumberGenerator;
use specs::prelude::*; use specs::prelude::*;
use crate::{Map, Position, spawner, TileType};
use crate::map_builders::{common, MapBuilder}; use crate::map_builders::{common, MapBuilder};
use crate::rect::Rect; use crate::rect::Rect;
use crate::{spawner, Map, Position, TileType, SHOW_MAPGEN_VISUALIZER};
pub struct SimpleMapBuilder { pub struct SimpleMapBuilder {
map: Map, map: Map,
starting_position: Position, starting_position: Position,
depth: i32, depth: i32,
rooms: Vec<Rect>, rooms: Vec<Rect>,
history: Vec<Map>,
} }
impl SimpleMapBuilder { impl SimpleMapBuilder {
@ -19,6 +20,7 @@ impl SimpleMapBuilder {
map: Map::new(new_depth), map: Map::new(new_depth),
depth: new_depth, depth: new_depth,
rooms: Vec::new(), rooms: Vec::new(),
history: Vec::new(),
} }
} }
@ -43,6 +45,7 @@ impl SimpleMapBuilder {
} }
if ok { if ok {
common::apply_room_to_map(&mut self.map, &new_room); common::apply_room_to_map(&mut self.map, &new_room);
self.take_snapshot();
if !self.rooms.is_empty() { if !self.rooms.is_empty() {
let (new_x, new_y) = new_room.center(); let (new_x, new_y) = new_room.center();
@ -57,6 +60,7 @@ impl SimpleMapBuilder {
} }
self.rooms.push(new_room); self.rooms.push(new_room);
self.take_snapshot();
} }
} }
@ -65,7 +69,10 @@ impl SimpleMapBuilder {
self.map.tiles[stairs_idx] = TileType::DownStairs; self.map.tiles[stairs_idx] = TileType::DownStairs;
let start_pos = self.rooms[0].center(); let start_pos = self.rooms[0].center();
self.starting_position = Position { x: start_pos.0, y: start_pos.1 } self.starting_position = Position {
x: start_pos.0,
y: start_pos.1,
}
} }
} }
@ -87,4 +94,18 @@ impl MapBuilder for SimpleMapBuilder {
fn get_starting_position(&self) -> Position { fn get_starting_position(&self) -> Position {
self.starting_position.clone() self.starting_position.clone()
} }
fn get_snapshot_history(&self) -> Vec<Map> {
self.history.clone()
}
fn take_snapshot(&mut self) {
if SHOW_MAPGEN_VISUALIZER {
let mut snapshot = self.map.clone();
for v in snapshot.revealed_tiles.iter_mut() {
*v = true;
}
self.history.push(snapshot);
}
}
} }

432
src/state.rs Normal file
View File

@ -0,0 +1,432 @@
use specs::prelude::*;
use crate::*;
#[derive(PartialEq, Copy, Clone)]
pub enum RunState {
AwaitingInput,
PreRun,
PlayerTurn,
MonsterTurn,
ShowInventory,
ShowDropItem,
ShowTargeting {
range: i32,
item: Entity,
},
MainMenu {
menu_selection: gui::MainMenuSelection,
},
SaveGame,
NextLevel,
ShowRemoveItem,
GameOver,
MagicMapReveal {
row: i32,
},
MapGeneration,
}
pub struct State {
pub ecs: World,
mapgen_next_state: Option<RunState>,
mapgen_history: Vec<Map>,
mapgen_index: usize,
mapgen_timer: f32,
}
impl State {
pub fn new() -> Self {
Self {
ecs: World::new(),
mapgen_history: Vec::new(),
mapgen_index: 0,
mapgen_timer: 0.,
mapgen_next_state: Some(RunState::MainMenu {
menu_selection: MainMenuSelection::NewGame,
}),
}
}
pub fn game_over_cleanup(&mut self) {
// Delete everything
let mut to_delete = Vec::new();
for e in self.ecs.entities().join() {
to_delete.push(e);
}
for del in to_delete.iter() {
self.ecs.delete_entity(*del).expect("Deletion failed");
}
{
let player_entity = spawner::player(&mut self.ecs, 0, 0);
let mut player_entity_writer = self.ecs.write_resource::<Entity>();
*player_entity_writer = player_entity
}
self.generate_world_map(1);
}
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 equipped = self.ecs.read_storage::<Equipped>();
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 let Some(eq) = equipped.get(entity) {
if eq.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 current_depth;
{
let mut worldmap_resource = self.ecs.write_resource::<Map>();
current_depth = worldmap_resource.depth;
}
self.generate_world_map(current_depth + 1);
let player_entity = self.ecs.fetch::<Entity>();
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);
}
}
fn run_systems(&mut self) {
let mut vis = VisibilitySystem {};
vis.run_now(&self.ecs);
let mut mob = MonsterAI {};
mob.run_now(&self.ecs);
let mut trigger = TriggerSystem {};
trigger.run_now(&self.ecs);
let mut map_index = MapIndexingSystem {};
map_index.run_now(&self.ecs);
let mut melee_system = MeleeCombatSystem {};
melee_system.run_now(&self.ecs);
let mut damage_system = DamageSystem {};
damage_system.run_now(&self.ecs);
let mut healing_system = HealingSystem {};
healing_system.run_now(&self.ecs);
let mut inventory = ItemCollectionSystem {};
inventory.run_now(&self.ecs);
let mut potions = ItemUseSystem {};
potions.run_now(&self.ecs);
let mut drop_items = ItemDropSystem {};
drop_items.run_now(&self.ecs);
let mut remove_items = ItemRemoveSystem {};
remove_items.run_now(&self.ecs);
let mut hunger = HungerSystem {};
hunger.run_now(&self.ecs);
let mut particle_spawn = ParticleSpawnSystem {};
particle_spawn.run_now(&self.ecs);
self.ecs.maintain();
}
pub fn generate_world_map(&mut self, new_depth: i32) {
self.mapgen_index = 0;
self.mapgen_timer = 0.0;
self.mapgen_history.clear();
let mut map_builder = map_builders::new_random_builder(new_depth);
map_builder.build_map();
self.mapgen_history = map_builder.get_snapshot_history();
let player_start;
{
let mut world_map_resource = self.ecs.write_resource::<Map>();
*world_map_resource = map_builder.get_map();
player_start = map_builder.get_starting_position();
}
map_builder.spawn_entities(&mut self.ecs);
let (player_x, player_y) = (player_start.x, player_start.y);
let mut player_pos = self.ecs.write_resource::<Point>();
*player_pos = Point::new(player_x, player_y);
let mut pos_comp = self.ecs.write_storage::<Position>();
let player_entity = self.ecs.fetch::<Entity>();
if let Some(player_pos_comp) = pos_comp.get_mut(*player_entity) {
player_pos_comp.x = player_x;
player_pos_comp.y = player_y;
}
let mut viewshed_comp = self.ecs.write_storage::<Viewshed>();
if let Some(vs) = viewshed_comp.get_mut(*player_entity) {
vs.dirty = true;
}
}
}
impl GameState for State {
fn tick(&mut self, ctx: &mut rltk::Rltk) {
let mut new_run_state;
{
let run_state = self.ecs.fetch::<RunState>();
new_run_state = *run_state;
}
ctx.cls();
particle_system::cull_dead_particles(&mut self.ecs, ctx);
match new_run_state {
RunState::MainMenu { .. } => {}
_ => {
draw_map(&self.ecs.fetch::<Map>(), ctx);
let positions = self.ecs.read_storage::<Position>();
let renderables = self.ecs.read_storage::<Renderable>();
let hidden = self.ecs.read_storage::<Hidden>();
let map = self.ecs.fetch::<Map>();
let mut data = (&positions, &renderables, !&hidden)
.join()
.collect::<Vec<_>>();
data.sort_by(|&a, &b| b.1.render_order.cmp(&a.1.render_order));
for (pos, render, _hidden) in data.iter() {
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)
}
}
gui::draw_ui(&self.ecs, ctx);
}
}
match new_run_state {
RunState::PreRun => {
self.run_systems();
new_run_state = RunState::AwaitingInput;
}
RunState::AwaitingInput => new_run_state = player_input(self, ctx),
RunState::PlayerTurn => {
self.run_systems();
new_run_state = RunState::MonsterTurn;
match *self.ecs.fetch::<RunState>() {
RunState::MagicMapReveal { .. } => {
new_run_state = RunState::MagicMapReveal { row: 0 }
}
_ => {
new_run_state = RunState::MonsterTurn;
}
}
}
RunState::MonsterTurn => {
self.run_systems();
new_run_state = RunState::AwaitingInput;
}
RunState::ShowInventory => {
let result = gui::show_inventory(self, ctx);
match result.0 {
gui::ItemMenuResult::Cancel => new_run_state = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => {
let item_entity = result.1.unwrap();
let is_ranged = self.ecs.read_storage::<Ranged>();
let is_item_ranged = is_ranged.get(item_entity);
if let Some(is_item_ranged) = is_item_ranged {
new_run_state = RunState::ShowTargeting {
range: is_item_ranged.range,
item: item_entity,
}
} else {
let mut intent = self.ecs.write_storage::<WantsToUseItem>();
intent
.insert(
*self.ecs.fetch::<Entity>(),
WantsToUseItem {
item: item_entity,
target: None,
},
)
.expect("Unable to insert intent");
new_run_state = RunState::PlayerTurn;
}
}
}
}
RunState::ShowDropItem => {
let result = gui::drop_item_menu(self, ctx);
match result.0 {
gui::ItemMenuResult::Cancel => new_run_state = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => {
let item_entity = result.1.unwrap();
let mut intent = self.ecs.write_storage::<WantsToDropItem>();
intent
.insert(
*self.ecs.fetch::<Entity>(),
WantsToDropItem { item: item_entity },
)
.expect("Unable to insert intent");
new_run_state = RunState::PlayerTurn;
}
}
}
RunState::ShowTargeting { range, item } => {
let result = gui::ranged_target(self, ctx, range);
match result.0 {
gui::ItemMenuResult::Cancel => new_run_state = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => {
let mut intent = self.ecs.write_storage::<WantsToUseItem>();
intent
.insert(
*self.ecs.fetch::<Entity>(),
WantsToUseItem {
item,
target: result.1,
},
)
.expect("Unable to insert intent");
new_run_state = RunState::PlayerTurn;
}
}
}
RunState::MainMenu { .. } => {
let result = gui::main_menu(self, ctx);
match result {
gui::MainMenuResult::NoSelection { selected } => {
new_run_state = RunState::MainMenu {
menu_selection: selected,
}
}
gui::MainMenuResult::Selected { selected } => match selected {
gui::MainMenuSelection::NewGame => new_run_state = RunState::PreRun,
gui::MainMenuSelection::LoadGame => {
save_load_system::load_game(&mut self.ecs);
new_run_state = RunState::AwaitingInput;
save_load_system::delete_save();
}
gui::MainMenuSelection::Quit => ::std::process::exit(0),
},
}
}
RunState::SaveGame => {
save_load_system::save_game(&mut self.ecs);
new_run_state = RunState::MainMenu {
menu_selection: gui::MainMenuSelection::Quit,
};
}
RunState::NextLevel => {
self.goto_next_level();
new_run_state = RunState::PreRun;
}
RunState::ShowRemoveItem => {
let result = gui::remove_item_menu(self, ctx);
match result.0 {
gui::ItemMenuResult::Cancel => new_run_state = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => {
let item_entity = result.1.unwrap();
let mut intent = self.ecs.write_storage::<WantsToRemoveItem>();
intent
.insert(
*self.ecs.fetch::<Entity>(),
WantsToRemoveItem { item: item_entity },
)
.expect("Unable to insert intent");
new_run_state = RunState::PlayerTurn;
}
}
}
RunState::GameOver => {
let result = gui::game_over(ctx);
match result {
gui::GameOverResult::NoSelection => {}
gui::GameOverResult::QuitToMenu => {
self.game_over_cleanup();
new_run_state = RunState::MainMenu {
menu_selection: gui::MainMenuSelection::NewGame,
};
}
}
}
RunState::MagicMapReveal { row } => {
let mut map = self.ecs.fetch_mut::<Map>();
for x in 0..MAP_WIDTH {
let idx = map.xy_idx(x as i32, row);
map.revealed_tiles[idx] = true;
}
if row as usize == MAP_HEIGHT - 1 {
new_run_state = RunState::MonsterTurn;
} else {
new_run_state = RunState::MagicMapReveal { row: row + 1 }
}
}
RunState::MapGeneration => {
if !SHOW_MAPGEN_VISUALIZER {
new_run_state = self.mapgen_next_state.unwrap();
}
ctx.cls();
draw_map(&self.mapgen_history[self.mapgen_index], ctx);
self.mapgen_timer += ctx.frame_time_ms;
if self.mapgen_timer > 300.0 {
self.mapgen_timer = 0.0;
self.mapgen_index += 1;
if self.mapgen_index >= self.mapgen_history.len() {
new_run_state = self.mapgen_next_state.unwrap();
}
}
}
}
{
let mut run_writer = self.ecs.write_resource::<RunState>();
*run_writer = new_run_state;
}
damage_system::delete_the_dead(&mut self.ecs);
}
}