main.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. extern crate serde;
  2. extern crate rltk;
  3. use rltk::{Console, GameState, Rltk, Point};
  4. extern crate specs;
  5. use specs::prelude::*;
  6. use specs::saveload::{SimpleMarker, SimpleMarkerAllocator};
  7. #[macro_use]
  8. extern crate specs_derive;
  9. mod components;
  10. pub use components::*;
  11. mod map;
  12. pub use map::*;
  13. mod player;
  14. use player::*;
  15. mod rect;
  16. pub use rect::Rect;
  17. mod visibility_system;
  18. use visibility_system::VisibilitySystem;
  19. mod monster_ai_system;
  20. use monster_ai_system::MonsterAI;
  21. mod map_indexing_system;
  22. use map_indexing_system::MapIndexingSystem;
  23. mod melee_combat_system;
  24. use melee_combat_system::MeleeCombatSystem;
  25. mod damage_system;
  26. use damage_system::DamageSystem;
  27. mod gui;
  28. mod gamelog;
  29. mod spawner;
  30. mod inventory_system;
  31. use inventory_system::{ ItemCollectionSystem, ItemUseSystem, ItemDropSystem, ItemRemoveSystem };
  32. pub mod saveload_system;
  33. pub mod random_table;
  34. pub mod particle_system;
  35. pub mod hunger_system;
  36. pub mod rex_assets;
  37. pub mod trigger_system;
  38. pub mod map_builders;
  39. rltk::add_wasm_support!();
  40. const SHOW_MAPGEN_VISUALIZER : bool = true;
  41. #[derive(PartialEq, Copy, Clone)]
  42. pub enum RunState { AwaitingInput,
  43. PreRun,
  44. PlayerTurn,
  45. MonsterTurn,
  46. ShowInventory,
  47. ShowDropItem,
  48. ShowTargeting { range : i32, item : Entity},
  49. MainMenu { menu_selection : gui::MainMenuSelection },
  50. SaveGame,
  51. NextLevel,
  52. ShowRemoveItem,
  53. GameOver,
  54. MagicMapReveal { row : i32 },
  55. MapGeneration
  56. }
  57. pub struct State {
  58. pub ecs: World,
  59. mapgen_next_state : Option<RunState>,
  60. mapgen_history : Vec<Map>,
  61. mapgen_index : usize,
  62. mapgen_timer : f32
  63. }
  64. impl State {
  65. fn run_systems(&mut self) {
  66. let mut mapindex = MapIndexingSystem{};
  67. mapindex.run_now(&self.ecs);
  68. let mut vis = VisibilitySystem{};
  69. vis.run_now(&self.ecs);
  70. let mut mob = MonsterAI{};
  71. mob.run_now(&self.ecs);
  72. let mut triggers = trigger_system::TriggerSystem{};
  73. triggers.run_now(&self.ecs);
  74. let mut melee = MeleeCombatSystem{};
  75. melee.run_now(&self.ecs);
  76. let mut damage = DamageSystem{};
  77. damage.run_now(&self.ecs);
  78. let mut pickup = ItemCollectionSystem{};
  79. pickup.run_now(&self.ecs);
  80. let mut itemuse = ItemUseSystem{};
  81. itemuse.run_now(&self.ecs);
  82. let mut drop_items = ItemDropSystem{};
  83. drop_items.run_now(&self.ecs);
  84. let mut item_remove = ItemRemoveSystem{};
  85. item_remove.run_now(&self.ecs);
  86. let mut hunger = hunger_system::HungerSystem{};
  87. hunger.run_now(&self.ecs);
  88. let mut particles = particle_system::ParticleSpawnSystem{};
  89. particles.run_now(&self.ecs);
  90. self.ecs.maintain();
  91. }
  92. }
  93. impl GameState for State {
  94. fn tick(&mut self, ctx : &mut Rltk) {
  95. let mut newrunstate;
  96. {
  97. let runstate = self.ecs.fetch::<RunState>();
  98. newrunstate = *runstate;
  99. }
  100. ctx.cls();
  101. particle_system::cull_dead_particles(&mut self.ecs, ctx);
  102. match newrunstate {
  103. RunState::MainMenu{..} => {}
  104. RunState::GameOver{..} => {}
  105. _ => {
  106. draw_map(&self.ecs.fetch::<Map>(), ctx);
  107. let positions = self.ecs.read_storage::<Position>();
  108. let renderables = self.ecs.read_storage::<Renderable>();
  109. let hidden = self.ecs.read_storage::<Hidden>();
  110. let map = self.ecs.fetch::<Map>();
  111. let mut data = (&positions, &renderables, !&hidden).join().collect::<Vec<_>>();
  112. data.sort_by(|&a, &b| b.1.render_order.cmp(&a.1.render_order) );
  113. for (pos, render, _hidden) in data.iter() {
  114. let idx = map.xy_idx(pos.x, pos.y);
  115. if map.visible_tiles[idx] { ctx.set(pos.x, pos.y, render.fg, render.bg, render.glyph) }
  116. }
  117. gui::draw_ui(&self.ecs, ctx);
  118. }
  119. }
  120. match newrunstate {
  121. RunState::MapGeneration => {
  122. if !SHOW_MAPGEN_VISUALIZER {
  123. newrunstate = self.mapgen_next_state.unwrap();
  124. }
  125. ctx.cls();
  126. draw_map(&self.mapgen_history[self.mapgen_index], ctx);
  127. self.mapgen_timer += ctx.frame_time_ms;
  128. if self.mapgen_timer > 400.0 {
  129. self.mapgen_timer = 0.0;
  130. self.mapgen_index += 1;
  131. if self.mapgen_index == self.mapgen_history.len() {
  132. //self.mapgen_index -= 1;
  133. newrunstate = self.mapgen_next_state.unwrap();
  134. }
  135. }
  136. }
  137. RunState::PreRun => {
  138. self.run_systems();
  139. self.ecs.maintain();
  140. newrunstate = RunState::AwaitingInput;
  141. }
  142. RunState::AwaitingInput => {
  143. newrunstate = player_input(self, ctx);
  144. }
  145. RunState::PlayerTurn => {
  146. self.run_systems();
  147. self.ecs.maintain();
  148. match *self.ecs.fetch::<RunState>() {
  149. RunState::MagicMapReveal{ .. } => newrunstate = RunState::MagicMapReveal{ row: 0 },
  150. _ => newrunstate = RunState::MonsterTurn
  151. }
  152. }
  153. RunState::MonsterTurn => {
  154. self.run_systems();
  155. self.ecs.maintain();
  156. newrunstate = RunState::AwaitingInput;
  157. }
  158. RunState::ShowInventory => {
  159. let result = gui::show_inventory(self, ctx);
  160. match result.0 {
  161. gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
  162. gui::ItemMenuResult::NoResponse => {}
  163. gui::ItemMenuResult::Selected => {
  164. let item_entity = result.1.unwrap();
  165. let is_ranged = self.ecs.read_storage::<Ranged>();
  166. let is_item_ranged = is_ranged.get(item_entity);
  167. if let Some(is_item_ranged) = is_item_ranged {
  168. newrunstate = RunState::ShowTargeting{ range: is_item_ranged.range, item: item_entity };
  169. } else {
  170. let mut intent = self.ecs.write_storage::<WantsToUseItem>();
  171. intent.insert(*self.ecs.fetch::<Entity>(), WantsToUseItem{ item: item_entity, target: None }).expect("Unable to insert intent");
  172. newrunstate = RunState::PlayerTurn;
  173. }
  174. }
  175. }
  176. }
  177. RunState::ShowDropItem => {
  178. let result = gui::drop_item_menu(self, ctx);
  179. match result.0 {
  180. gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
  181. gui::ItemMenuResult::NoResponse => {}
  182. gui::ItemMenuResult::Selected => {
  183. let item_entity = result.1.unwrap();
  184. let mut intent = self.ecs.write_storage::<WantsToDropItem>();
  185. intent.insert(*self.ecs.fetch::<Entity>(), WantsToDropItem{ item: item_entity }).expect("Unable to insert intent");
  186. newrunstate = RunState::PlayerTurn;
  187. }
  188. }
  189. }
  190. RunState::ShowRemoveItem => {
  191. let result = gui::remove_item_menu(self, ctx);
  192. match result.0 {
  193. gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
  194. gui::ItemMenuResult::NoResponse => {}
  195. gui::ItemMenuResult::Selected => {
  196. let item_entity = result.1.unwrap();
  197. let mut intent = self.ecs.write_storage::<WantsToRemoveItem>();
  198. intent.insert(*self.ecs.fetch::<Entity>(), WantsToRemoveItem{ item: item_entity }).expect("Unable to insert intent");
  199. newrunstate = RunState::PlayerTurn;
  200. }
  201. }
  202. }
  203. RunState::ShowTargeting{range, item} => {
  204. let result = gui::ranged_target(self, ctx, range);
  205. match result.0 {
  206. gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
  207. gui::ItemMenuResult::NoResponse => {}
  208. gui::ItemMenuResult::Selected => {
  209. let mut intent = self.ecs.write_storage::<WantsToUseItem>();
  210. intent.insert(*self.ecs.fetch::<Entity>(), WantsToUseItem{ item, target: result.1 }).expect("Unable to insert intent");
  211. newrunstate = RunState::PlayerTurn;
  212. }
  213. }
  214. }
  215. RunState::MainMenu{ .. } => {
  216. let result = gui::main_menu(self, ctx);
  217. match result {
  218. gui::MainMenuResult::NoSelection{ selected } => newrunstate = RunState::MainMenu{ menu_selection: selected },
  219. gui::MainMenuResult::Selected{ selected } => {
  220. match selected {
  221. gui::MainMenuSelection::NewGame => newrunstate = RunState::PreRun,
  222. gui::MainMenuSelection::LoadGame => {
  223. saveload_system::load_game(&mut self.ecs);
  224. newrunstate = RunState::AwaitingInput;
  225. saveload_system::delete_save();
  226. }
  227. gui::MainMenuSelection::Quit => { ::std::process::exit(0); }
  228. }
  229. }
  230. }
  231. }
  232. RunState::GameOver => {
  233. let result = gui::game_over(ctx);
  234. match result {
  235. gui::GameOverResult::NoSelection => {}
  236. gui::GameOverResult::QuitToMenu => {
  237. self.game_over_cleanup();
  238. newrunstate = RunState::MapGeneration;
  239. self.mapgen_next_state = Some(RunState::MainMenu{ menu_selection: gui::MainMenuSelection::NewGame });
  240. }
  241. }
  242. }
  243. RunState::SaveGame => {
  244. saveload_system::save_game(&mut self.ecs);
  245. newrunstate = RunState::MainMenu{ menu_selection : gui::MainMenuSelection::LoadGame };
  246. }
  247. RunState::NextLevel => {
  248. self.goto_next_level();
  249. self.mapgen_next_state = Some(RunState::PreRun);
  250. newrunstate = RunState::MapGeneration;
  251. }
  252. RunState::MagicMapReveal{row} => {
  253. let mut map = self.ecs.fetch_mut::<Map>();
  254. for x in 0..MAPWIDTH {
  255. let idx = map.xy_idx(x as i32,row);
  256. map.revealed_tiles[idx] = true;
  257. }
  258. if row as usize == MAPHEIGHT-1 {
  259. newrunstate = RunState::MonsterTurn;
  260. } else {
  261. newrunstate = RunState::MagicMapReveal{ row: row+1 };
  262. }
  263. }
  264. }
  265. {
  266. let mut runwriter = self.ecs.write_resource::<RunState>();
  267. *runwriter = newrunstate;
  268. }
  269. damage_system::delete_the_dead(&mut self.ecs);
  270. }
  271. }
  272. impl State {
  273. fn entities_to_remove_on_level_change(&mut self) -> Vec<Entity> {
  274. let entities = self.ecs.entities();
  275. let player = self.ecs.read_storage::<Player>();
  276. let backpack = self.ecs.read_storage::<InBackpack>();
  277. let player_entity = self.ecs.fetch::<Entity>();
  278. let equipped = self.ecs.read_storage::<Equipped>();
  279. let mut to_delete : Vec<Entity> = Vec::new();
  280. for entity in entities.join() {
  281. let mut should_delete = true;
  282. // Don't delete the player
  283. let p = player.get(entity);
  284. if let Some(_p) = p {
  285. should_delete = false;
  286. }
  287. // Don't delete the player's equipment
  288. let bp = backpack.get(entity);
  289. if let Some(bp) = bp {
  290. if bp.owner == *player_entity {
  291. should_delete = false;
  292. }
  293. }
  294. let eq = equipped.get(entity);
  295. if let Some(eq) = eq {
  296. if eq.owner == *player_entity {
  297. should_delete = false;
  298. }
  299. }
  300. if should_delete {
  301. to_delete.push(entity);
  302. }
  303. }
  304. to_delete
  305. }
  306. fn goto_next_level(&mut self) {
  307. // Delete entities that aren't the player or his/her equipment
  308. let to_delete = self.entities_to_remove_on_level_change();
  309. for target in to_delete {
  310. self.ecs.delete_entity(target).expect("Unable to delete entity");
  311. }
  312. // Build a new map and place the player
  313. let current_depth;
  314. {
  315. let worldmap_resource = self.ecs.fetch::<Map>();
  316. current_depth = worldmap_resource.depth;
  317. }
  318. self.generate_world_map(current_depth + 1);
  319. // Notify the player and give them some health
  320. let player_entity = self.ecs.fetch::<Entity>();
  321. let mut gamelog = self.ecs.fetch_mut::<gamelog::GameLog>();
  322. gamelog.entries.insert(0, "You descend to the next level, and take a moment to heal.".to_string());
  323. let mut player_health_store = self.ecs.write_storage::<CombatStats>();
  324. let player_health = player_health_store.get_mut(*player_entity);
  325. if let Some(player_health) = player_health {
  326. player_health.hp = i32::max(player_health.hp, player_health.max_hp / 2);
  327. }
  328. }
  329. fn game_over_cleanup(&mut self) {
  330. // Delete everything
  331. let mut to_delete = Vec::new();
  332. for e in self.ecs.entities().join() {
  333. to_delete.push(e);
  334. }
  335. for del in to_delete.iter() {
  336. self.ecs.delete_entity(*del).expect("Deletion failed");
  337. }
  338. // Spawn a new player
  339. {
  340. let player_entity = spawner::player(&mut self.ecs, 0, 0);
  341. let mut player_entity_writer = self.ecs.write_resource::<Entity>();
  342. *player_entity_writer = player_entity;
  343. }
  344. // Build a new map and place the player
  345. self.generate_world_map(1);
  346. }
  347. fn generate_world_map(&mut self, new_depth : i32) {
  348. self.mapgen_index = 0;
  349. self.mapgen_timer = 0.0;
  350. self.mapgen_history.clear();
  351. let mut builder = map_builders::random_builder(new_depth);
  352. builder.build_map();
  353. self.mapgen_history = builder.get_snapshot_history();
  354. let player_start;
  355. {
  356. let mut worldmap_resource = self.ecs.write_resource::<Map>();
  357. *worldmap_resource = builder.get_map();
  358. player_start = builder.get_starting_position();
  359. }
  360. // Spawn bad guys
  361. builder.spawn_entities(&mut self.ecs);
  362. // Place the player and update resources
  363. let (player_x, player_y) = (player_start.x, player_start.y);
  364. let mut player_position = self.ecs.write_resource::<Point>();
  365. *player_position = Point::new(player_x, player_y);
  366. let mut position_components = self.ecs.write_storage::<Position>();
  367. let player_entity = self.ecs.fetch::<Entity>();
  368. let player_pos_comp = position_components.get_mut(*player_entity);
  369. if let Some(player_pos_comp) = player_pos_comp {
  370. player_pos_comp.x = player_x;
  371. player_pos_comp.y = player_y;
  372. }
  373. // Mark the player's visibility as dirty
  374. let mut viewshed_components = self.ecs.write_storage::<Viewshed>();
  375. let vs = viewshed_components.get_mut(*player_entity);
  376. if let Some(vs) = vs {
  377. vs.dirty = true;
  378. }
  379. }
  380. }
  381. fn main() {
  382. let mut context = Rltk::init_simple8x8(80, 50, "Hello Rust World", "resources");
  383. context.with_post_scanlines(true);
  384. let mut gs = State {
  385. ecs: World::new(),
  386. mapgen_next_state : Some(RunState::MainMenu{ menu_selection: gui::MainMenuSelection::NewGame }),
  387. mapgen_index : 0,
  388. mapgen_history: Vec::new(),
  389. mapgen_timer: 0.0
  390. };
  391. gs.ecs.register::<Position>();
  392. gs.ecs.register::<Renderable>();
  393. gs.ecs.register::<Player>();
  394. gs.ecs.register::<Viewshed>();
  395. gs.ecs.register::<Monster>();
  396. gs.ecs.register::<Name>();
  397. gs.ecs.register::<BlocksTile>();
  398. gs.ecs.register::<CombatStats>();
  399. gs.ecs.register::<WantsToMelee>();
  400. gs.ecs.register::<SufferDamage>();
  401. gs.ecs.register::<Item>();
  402. gs.ecs.register::<ProvidesHealing>();
  403. gs.ecs.register::<InflictsDamage>();
  404. gs.ecs.register::<AreaOfEffect>();
  405. gs.ecs.register::<Consumable>();
  406. gs.ecs.register::<Ranged>();
  407. gs.ecs.register::<InBackpack>();
  408. gs.ecs.register::<WantsToPickupItem>();
  409. gs.ecs.register::<WantsToUseItem>();
  410. gs.ecs.register::<WantsToDropItem>();
  411. gs.ecs.register::<Confusion>();
  412. gs.ecs.register::<SimpleMarker<SerializeMe>>();
  413. gs.ecs.register::<SerializationHelper>();
  414. gs.ecs.register::<Equippable>();
  415. gs.ecs.register::<Equipped>();
  416. gs.ecs.register::<MeleePowerBonus>();
  417. gs.ecs.register::<DefenseBonus>();
  418. gs.ecs.register::<WantsToRemoveItem>();
  419. gs.ecs.register::<ParticleLifetime>();
  420. gs.ecs.register::<HungerClock>();
  421. gs.ecs.register::<ProvidesFood>();
  422. gs.ecs.register::<MagicMapper>();
  423. gs.ecs.register::<Hidden>();
  424. gs.ecs.register::<EntryTrigger>();
  425. gs.ecs.register::<EntityMoved>();
  426. gs.ecs.register::<SingleActivation>();
  427. gs.ecs.insert(SimpleMarkerAllocator::<SerializeMe>::new());
  428. gs.ecs.insert(Map::new(1));
  429. gs.ecs.insert(Point::new(0, 0));
  430. gs.ecs.insert(rltk::RandomNumberGenerator::new());
  431. let player_entity = spawner::player(&mut gs.ecs, 0, 0);
  432. gs.ecs.insert(player_entity);
  433. gs.ecs.insert(RunState::MapGeneration{} );
  434. gs.ecs.insert(gamelog::GameLog{ entries : vec!["Welcome to Rusty Roguelike".to_string()] });
  435. gs.ecs.insert(particle_system::ParticleBuilder::new());
  436. gs.ecs.insert(rex_assets::RexAssets::new());
  437. gs.generate_world_map(1);
  438. rltk::main_loop(context, gs);
  439. }