roguelike-game/src/main.rs

559 lines
19 KiB
Rust
Raw Normal View History

use rltk::{GameState, Point, Rltk};
2021-10-21 12:54:39 -04:00
use specs::prelude::*;
2021-11-08 13:58:40 -05:00
use specs::saveload::{SimpleMarker, SimpleMarkerAllocator};
2021-10-20 12:01:15 -04:00
2021-10-22 10:05:06 -04:00
mod components;
mod damage_system;
2021-11-04 10:44:52 -04:00
mod game_log;
mod gui;
2021-11-18 10:28:49 -05:00
mod hunger_system;
mod inventory_system;
2021-10-22 10:05:06 -04:00
mod map;
pub mod map_builders;
mod map_indexing_system;
mod melee_combat_system;
mod monster_ai_system;
2021-11-16 11:33:58 -05:00
mod particle_system;
2021-10-22 10:05:06 -04:00
mod player;
pub mod random_table;
2021-10-22 10:05:06 -04:00
mod rect;
2021-11-29 14:59:46 -05:00
mod rex_assets;
2021-11-08 13:58:40 -05:00
pub mod saveload_system;
mod spawner;
2021-11-29 16:00:07 -05:00
mod trigger_system;
2021-10-25 15:26:39 -04:00
mod visibility_system;
2021-11-15 13:27:40 -05:00
use crate::inventory_system::ItemRemoveSystem;
2021-11-05 14:32:14 -04:00
use components::*;
2021-10-29 15:15:22 -04:00
use damage_system::DamageSystem;
2021-11-04 10:44:52 -04:00
pub use game_log::GameLog;
use inventory_system::{ItemCollectionSystem, ItemDropSystem, ItemUseSystem};
pub use map::*;
use map_indexing_system::MapIndexingSystem;
use melee_combat_system::MeleeCombatSystem;
use monster_ai_system::MonsterAI;
use player::*;
pub use rect::Rect;
use visibility_system::VisibilitySystem;
2021-10-25 15:26:39 -04:00
/// Cut down on the amount of syntax to register components
macro_rules! register {
// $gs is needed to get the scope at the usage point
// $Type is the Component type that is being registered
($gs: ident <- $( $Type: ty ),*,) => {
$(
$gs.ecs.register::<$Type>();
)*
}
}
2021-10-26 15:43:59 -04:00
#[derive(PartialEq, Copy, Clone)]
pub enum RunState {
2021-10-29 15:15:22 -04:00
AwaitingInput,
PreRun,
PlayerTurn,
MonsterTurn,
2021-11-03 15:11:19 -04:00
ShowInventory,
2021-11-04 09:40:58 -04:00
ShowDropItem,
2021-11-08 10:22:11 -05:00
ShowTargeting {
range: i32,
item: Entity,
},
MainMenu {
menu_selection: gui::MainMenuSelection,
},
2021-11-08 13:58:40 -05:00
SaveGame,
2021-11-09 15:50:42 -05:00
NextLevel,
2021-11-15 11:32:09 -05:00
ShowRemoveItem,
2021-11-15 13:27:40 -05:00
GameOver,
MagicMapReveal {
row: i32,
},
2021-10-26 15:43:59 -04:00
}
2021-10-22 10:05:06 -04:00
pub struct State {
2021-10-26 15:43:59 -04:00
pub ecs: World,
2021-10-21 12:54:39 -04:00
}
2021-10-20 12:01:15 -04:00
2021-10-25 14:23:19 -04:00
impl State {
fn new() -> Self {
State { ecs: World::new() }
}
2021-10-25 14:23:19 -04:00
fn run_systems(&mut self) {
2021-10-25 15:26:39 -04:00
let mut vis = VisibilitySystem {};
vis.run_now(&self.ecs);
2021-10-26 15:43:59 -04:00
let mut mob = MonsterAI {};
mob.run_now(&self.ecs);
2021-11-29 16:00:07 -05:00
let mut triggers = trigger_system::TriggerSystem {};
triggers.run_now(&self.ecs);
2021-10-29 11:11:17 -04:00
let mut mapindex = MapIndexingSystem {};
mapindex.run_now(&self.ecs);
2021-10-29 15:15:22 -04:00
let mut melee = MeleeCombatSystem {};
melee.run_now(&self.ecs);
let mut damage = DamageSystem {};
damage.run_now(&self.ecs);
2021-11-03 15:11:19 -04:00
let mut pickup = ItemCollectionSystem {};
pickup.run_now(&self.ecs);
let mut items = ItemUseSystem {};
items.run_now(&self.ecs);
2021-11-03 15:59:23 -04:00
2021-11-04 09:40:58 -04:00
let mut drop_items = ItemDropSystem {};
drop_items.run_now(&self.ecs);
2021-11-15 11:32:09 -05:00
let mut item_remove = ItemRemoveSystem {};
item_remove.run_now(&self.ecs);
2021-11-18 10:28:49 -05:00
let mut hunger = hunger_system::HungerSystem {};
hunger.run_now(&self.ecs);
2021-11-16 11:33:58 -05:00
let mut particles = particle_system::ParticleSpawnSystem {};
particles.run_now(&self.ecs);
2021-10-25 14:23:19 -04:00
self.ecs.maintain();
}
}
2021-10-20 12:01:15 -04:00
impl GameState for State {
fn tick(&mut self, ctx: &mut Rltk) {
2021-11-08 10:22:11 -05:00
let mut newrunstate;
{
2021-11-08 10:22:11 -05:00
let runstate = self.ecs.fetch::<RunState>();
newrunstate = *runstate;
}
2021-11-08 10:22:11 -05:00
ctx.cls();
2021-11-16 11:33:58 -05:00
particle_system::cull_dead_particles(&mut self.ecs, ctx);
2021-11-08 10:22:11 -05:00
match newrunstate {
2021-11-09 10:38:56 -05:00
RunState::MainMenu { .. } => {}
2021-11-29 16:00:07 -05:00
RunState::GameOver { .. } => {}
2021-11-08 10:22:11 -05:00
_ => {
// Draw the UI
draw_map(&self.ecs, ctx);
{
let positions = self.ecs.read_storage::<Position>();
let renderables = self.ecs.read_storage::<Renderable>();
2021-11-29 16:00:07 -05:00
let hidden = self.ecs.read_storage::<Hidden>();
2021-11-08 10:22:11 -05:00
let map = self.ecs.fetch::<Map>();
2021-11-29 16:00:07 -05:00
let mut data: Vec<_> = (&positions, &renderables, !&hidden).join().collect();
2021-11-08 10:22:11 -05:00
data.sort_by(|&a, &b| b.1.render_order.cmp(&a.1.render_order));
2021-11-29 16:00:07 -05:00
for (pos, render, _hidden) in data.iter() {
2021-11-08 10:22:11 -05:00
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)
}
}
2021-11-08 10:22:11 -05:00
gui::draw_ui(&self.ecs, ctx);
}
}
2021-10-29 15:15:22 -04:00
}
match newrunstate {
RunState::PreRun => {
self.run_systems();
2021-11-03 15:59:23 -04:00
self.ecs.maintain();
2021-10-29 15:15:22 -04:00
newrunstate = RunState::AwaitingInput;
}
RunState::AwaitingInput => {
newrunstate = player_input(self, ctx);
}
RunState::PlayerTurn => {
self.run_systems();
2021-11-03 15:59:23 -04:00
self.ecs.maintain();
match *self.ecs.fetch::<RunState>() {
RunState::MagicMapReveal { .. } => {
newrunstate = RunState::MagicMapReveal { row: 0 }
}
_ => newrunstate = RunState::MonsterTurn,
}
2021-10-29 15:15:22 -04:00
}
RunState::MonsterTurn => {
self.run_systems();
2021-11-03 15:59:23 -04:00
self.ecs.maintain();
2021-10-29 15:15:22 -04:00
newrunstate = RunState::AwaitingInput;
}
2021-11-03 15:11:19 -04:00
RunState::ShowInventory => {
2021-11-03 15:59:23 -04:00
let result = gui::show_inventory(self, ctx);
match result.0 {
gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
gui::ItemMenuResult::NoResponse => {}
gui::ItemMenuResult::Selected => {
let item_entity = result.1.unwrap();
2021-11-05 10:42:44 -04:00
let is_ranged = self.ecs.read_storage::<Ranged>();
if let Some(is_item_ranged) = is_ranged.get(item_entity) {
2021-11-05 10:42:44 -04:00
newrunstate = 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("failed to add intent to use item");
newrunstate = RunState::PlayerTurn;
}
2021-11-03 15:59:23 -04:00
}
2021-11-03 15:11:19 -04:00
}
}
2021-11-04 09:40:58 -04:00
RunState::ShowDropItem => {
let result = gui::drop_item_menu(self, ctx);
match result.0 {
gui::ItemMenuResult::Cancel => newrunstate = 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("failed to add intent to drop item");
newrunstate = RunState::PlayerTurn;
}
}
}
RunState::ShowRemoveItem => {
let result = gui::remove_item_menu(self, ctx);
match result.0 {
gui::ItemMenuResult::Cancel => newrunstate = 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 to remove item");
newrunstate = RunState::PlayerTurn;
}
}
}
2021-11-05 10:42:44 -04:00
RunState::ShowTargeting { range, item } => {
let result = gui::ranged_target(self, ctx, range);
match result.0 {
gui::ItemMenuResult::Cancel => newrunstate = 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("failed to add intent to use item");
newrunstate = RunState::PlayerTurn;
}
}
}
2021-11-09 10:38:56 -05:00
RunState::MainMenu { .. } => match gui::main_menu(self, ctx) {
gui::MainMenuResult::NoSelection { selected } => {
newrunstate = RunState::MainMenu {
menu_selection: selected,
2021-11-08 10:22:11 -05:00
}
}
2021-11-09 10:38:56 -05:00
gui::MainMenuResult::Selected { selected } => match selected {
gui::MainMenuSelection::NewGame => newrunstate = RunState::PreRun,
gui::MainMenuSelection::LoadGame => {
saveload_system::load_game(&mut self.ecs);
newrunstate = RunState::AwaitingInput;
saveload_system::delete_save();
}
gui::MainMenuSelection::Quit => {
::std::process::exit(0);
}
},
},
RunState::GameOver => match gui::game_over(ctx) {
gui::GameOverResult::NoSelection => {}
gui::GameOverResult::QuitToMenu => {
self.game_over_cleanup();
newrunstate = RunState::MainMenu {
menu_selection: gui::MainMenuSelection::NewGame,
};
}
},
2021-11-08 13:58:40 -05:00
RunState::SaveGame => {
saveload_system::save_game(&mut self.ecs);
newrunstate = RunState::MainMenu {
menu_selection: gui::MainMenuSelection::LoadGame,
}
}
2021-11-09 15:50:42 -05:00
RunState::NextLevel => {
self.goto_next_level();
newrunstate = RunState::PreRun;
}
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 {
newrunstate = RunState::MonsterTurn;
} else {
newrunstate = RunState::MagicMapReveal { row: row + 1 };
}
}
2021-10-29 15:15:22 -04:00
}
2021-10-21 14:24:40 -04:00
2021-10-29 15:15:22 -04:00
{
let mut runwriter = self.ecs.write_resource::<RunState>();
*runwriter = newrunstate;
2021-10-26 15:43:59 -04:00
}
2021-10-21 14:24:40 -04:00
2021-10-29 15:15:22 -04:00
damage_system::delete_the_dead(&mut self.ecs);
2021-10-21 14:24:40 -04:00
}
}
2021-11-09 15:50:42 -05:00
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>();
2021-11-15 09:19:22 -05:00
let equipped = self.ecs.read_storage::<Equipped>();
2021-11-09 15:50:42 -05:00
let mut to_delete: Vec<Entity> = Vec::new();
for entity in entities.join() {
let mut should_delete = true;
// Don't delete the player
if let Some(_p) = player.get(entity) {
2021-11-09 15:50:42 -05:00
should_delete = false;
}
// Don't delete the player's equipment
if let Some(bp) = backpack.get(entity) {
2021-11-09 15:50:42 -05:00
if bp.owner == *player_entity {
should_delete = false;
}
}
if let Some(eq) = equipped.get(entity) {
2021-11-15 09:19:22 -05:00
if eq.owner == *player_entity {
should_delete = false;
}
}
2021-11-09 15:50:42 -05:00
if should_delete {
to_delete.push(entity);
}
}
to_delete
}
fn goto_next_level(&mut self) {
// Delete entities that aren't the palyer or their equipment
let to_delete = self.entities_to_remove_on_level_change();
for target in to_delete {
self.ecs
.delete_entity(target)
.expect("failed to delete entity");
}
// Build a new map and place the player
let worldmap;
2021-11-12 14:12:15 -05:00
let current_depth;
let player_start;
2021-11-09 15:50:42 -05:00
{
let mut worldmap_resource = self.ecs.write_resource::<Map>();
2021-11-12 14:12:15 -05:00
current_depth = worldmap_resource.depth;
2021-11-09 15:50:42 -05:00
let (newmap, start) = map_builders::build_random_map(current_depth + 1);
*worldmap_resource = newmap;
player_start = start;
2021-11-09 15:50:42 -05:00
worldmap = worldmap_resource.clone();
}
// Spawn bad guys
for room in worldmap.rooms.iter().skip(1) {
2021-11-12 14:12:15 -05:00
spawner::spawn_room(&mut self.ecs, room, current_depth + 1);
2021-11-09 15:50:42 -05:00
}
// Place the player and update resources
let (player_x, player_y) = (player_start.x, player_start.y);
2021-11-09 15:50:42 -05:00
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>();
if let Some(player_pos_comp) = position_components.get_mut(*player_entity) {
2021-11-09 15:50:42 -05:00
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>();
if let Some(vs) = viewshed_components.get_mut(*player_entity) {
2021-11-09 15:50:42 -05:00
vs.dirty = true;
}
// Notify the player and give them some health
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);
}
}
2021-11-15 13:27:40 -05:00
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("Failed to delete entity");
}
// Build a new map and place the player
let worldmap;
let player_start;
2021-11-15 13:27:40 -05:00
{
let mut worldmap_resource = self.ecs.write_resource::<Map>();
let (newmap, start) = map_builders::build_random_map(1);
*worldmap_resource = newmap;
player_start = start;
2021-11-15 13:27:40 -05:00
worldmap = worldmap_resource.clone();
}
// Spawn bad guys
for room in worldmap.rooms.iter().skip(1) {
spawner::spawn_room(&mut self.ecs, room, 1);
}
// Place the player and update resources
let (player_x, player_y) = (player_start.x, player_start.y);
2021-11-15 13:27:40 -05:00
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;
if let Some(player_pos_comp) = position_components.get_mut(player_entity) {
2021-11-15 13:27:40 -05:00
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;
}
}
2021-11-09 15:50:42 -05:00
}
2021-10-20 12:01:15 -04:00
fn main() -> rltk::BError {
use rltk::RltkBuilder;
let context = RltkBuilder::simple80x50()
.with_title("Roguelike Tutorial")
.build()?;
let mut gs = State::new();
2021-10-21 12:54:39 -04:00
register!(
gs <-
Position,
Renderable,
Player,
Viewshed,
Monster,
Name,
BlocksTile,
CombatStats,
WantsToMelee,
SufferDamage,
Item,
ProvidesHealing,
InBackpack,
WantsToPickupItem,
WantsToUseItem,
WantsToDropItem,
Consumable,
2021-11-05 10:42:44 -04:00
Ranged,
InflictsDamage,
2021-11-05 13:12:22 -04:00
AreaOfEffect,
2021-11-05 14:32:14 -04:00
Confusion,
2021-11-08 13:58:40 -05:00
SimpleMarker<SerializeMe>,
SerializationHelper,
2021-11-15 09:19:22 -05:00
Equippable,
Equipped,
MeleePowerBonus,
DefenseBonus,
2021-11-15 11:32:09 -05:00
WantsToRemoveItem,
2021-11-16 11:33:58 -05:00
ParticleLifetime,
2021-11-17 16:23:01 -05:00
HungerClock,
ProvidesFood,
MagicMapper,
2021-11-29 16:00:07 -05:00
Hidden,
EntryTrigger,
EntityMoved,
2021-12-01 09:46:34 -05:00
SingleActivation,
);
2021-10-21 12:54:39 -04:00
2021-11-08 13:58:40 -05:00
gs.ecs.insert(SimpleMarkerAllocator::<SerializeMe>::new());
let (map, player_start) = map_builders::build_random_map(1);
let (player_x, player_y) = (player_start.x, player_start.y);
2021-10-22 14:50:04 -04:00
let player_entity = spawner::player(&mut gs.ecs, player_x, player_y);
2021-10-26 15:43:59 -04:00
gs.ecs.insert(rltk::RandomNumberGenerator::new());
for room in map.rooms.iter().skip(1) {
2021-11-12 14:12:15 -05:00
spawner::spawn_room(&mut gs.ecs, room, 1);
2021-10-26 14:38:30 -04:00
}
2021-10-22 14:50:04 -04:00
2021-10-26 14:38:30 -04:00
gs.ecs.insert(map);
2021-10-26 15:43:59 -04:00
gs.ecs.insert(Point::new(player_x, player_y));
2021-10-29 15:15:22 -04:00
gs.ecs.insert(player_entity);
gs.ecs.insert(RunState::MainMenu {
menu_selection: gui::MainMenuSelection::NewGame,
});
2021-11-05 14:32:14 -04:00
gs.ecs.insert(GameLog::new("Welcome to Rusty Roguelike"));
2021-11-16 11:33:58 -05:00
gs.ecs.insert(particle_system::ParticleBuilder::new());
2021-11-29 14:59:46 -05:00
gs.ecs.insert(rex_assets::RexAssets::new());
2021-10-26 14:38:30 -04:00
2021-10-20 12:01:15 -04:00
rltk::main_loop(context, gs)
2021-10-21 12:54:39 -04:00
}