main.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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 };
  32. pub mod saveload_system;
  33. rltk::add_wasm_support!();
  34. #[derive(PartialEq, Copy, Clone)]
  35. pub enum RunState { AwaitingInput,
  36. PreRun,
  37. PlayerTurn,
  38. MonsterTurn,
  39. ShowInventory,
  40. ShowDropItem,
  41. ShowTargeting { range : i32, item : Entity},
  42. MainMenu { menu_selection : gui::MainMenuSelection },
  43. SaveGame,
  44. NextLevel
  45. }
  46. pub struct State {
  47. pub ecs: World
  48. }
  49. impl State {
  50. fn run_systems(&mut self) {
  51. let mut mapindex = MapIndexingSystem{};
  52. mapindex.run_now(&self.ecs);
  53. let mut vis = VisibilitySystem{};
  54. vis.run_now(&self.ecs);
  55. let mut mob = MonsterAI{};
  56. mob.run_now(&self.ecs);
  57. let mut melee = MeleeCombatSystem{};
  58. melee.run_now(&self.ecs);
  59. let mut damage = DamageSystem{};
  60. damage.run_now(&self.ecs);
  61. let mut pickup = ItemCollectionSystem{};
  62. pickup.run_now(&self.ecs);
  63. let mut itemuse = ItemUseSystem{};
  64. itemuse.run_now(&self.ecs);
  65. let mut drop_items = ItemDropSystem{};
  66. drop_items.run_now(&self.ecs);
  67. self.ecs.maintain();
  68. }
  69. }
  70. impl GameState for State {
  71. fn tick(&mut self, ctx : &mut Rltk) {
  72. let mut newrunstate;
  73. {
  74. let runstate = self.ecs.fetch::<RunState>();
  75. newrunstate = *runstate;
  76. }
  77. ctx.cls();
  78. match newrunstate {
  79. RunState::MainMenu{..} => {}
  80. _ => {
  81. draw_map(&self.ecs, ctx);
  82. {
  83. let positions = self.ecs.read_storage::<Position>();
  84. let renderables = self.ecs.read_storage::<Renderable>();
  85. let map = self.ecs.fetch::<Map>();
  86. let mut data = (&positions, &renderables).join().collect::<Vec<_>>();
  87. data.sort_by(|&a, &b| b.1.render_order.cmp(&a.1.render_order) );
  88. for (pos, render) in data.iter() {
  89. let idx = map.xy_idx(pos.x, pos.y);
  90. if map.visible_tiles[idx] { ctx.set(pos.x, pos.y, render.fg, render.bg, render.glyph) }
  91. }
  92. gui::draw_ui(&self.ecs, ctx);
  93. }
  94. }
  95. }
  96. match newrunstate {
  97. RunState::PreRun => {
  98. self.run_systems();
  99. self.ecs.maintain();
  100. newrunstate = RunState::AwaitingInput;
  101. }
  102. RunState::AwaitingInput => {
  103. newrunstate = player_input(self, ctx);
  104. }
  105. RunState::PlayerTurn => {
  106. self.run_systems();
  107. self.ecs.maintain();
  108. newrunstate = RunState::MonsterTurn;
  109. }
  110. RunState::MonsterTurn => {
  111. self.run_systems();
  112. self.ecs.maintain();
  113. newrunstate = RunState::AwaitingInput;
  114. }
  115. RunState::ShowInventory => {
  116. let result = gui::show_inventory(self, ctx);
  117. match result.0 {
  118. gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
  119. gui::ItemMenuResult::NoResponse => {}
  120. gui::ItemMenuResult::Selected => {
  121. let item_entity = result.1.unwrap();
  122. let is_ranged = self.ecs.read_storage::<Ranged>();
  123. let is_item_ranged = is_ranged.get(item_entity);
  124. if let Some(is_item_ranged) = is_item_ranged {
  125. newrunstate = RunState::ShowTargeting{ range: is_item_ranged.range, item: item_entity };
  126. } else {
  127. let mut intent = self.ecs.write_storage::<WantsToUseItem>();
  128. intent.insert(*self.ecs.fetch::<Entity>(), WantsToUseItem{ item: item_entity, target: None }).expect("Unable to insert intent");
  129. newrunstate = RunState::PlayerTurn;
  130. }
  131. }
  132. }
  133. }
  134. RunState::ShowDropItem => {
  135. let result = gui::drop_item_menu(self, ctx);
  136. match result.0 {
  137. gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
  138. gui::ItemMenuResult::NoResponse => {}
  139. gui::ItemMenuResult::Selected => {
  140. let item_entity = result.1.unwrap();
  141. let mut intent = self.ecs.write_storage::<WantsToDropItem>();
  142. intent.insert(*self.ecs.fetch::<Entity>(), WantsToDropItem{ item: item_entity }).expect("Unable to insert intent");
  143. newrunstate = RunState::PlayerTurn;
  144. }
  145. }
  146. }
  147. RunState::ShowTargeting{range, item} => {
  148. let result = gui::ranged_target(self, ctx, range);
  149. match result.0 {
  150. gui::ItemMenuResult::Cancel => newrunstate = RunState::AwaitingInput,
  151. gui::ItemMenuResult::NoResponse => {}
  152. gui::ItemMenuResult::Selected => {
  153. let mut intent = self.ecs.write_storage::<WantsToUseItem>();
  154. intent.insert(*self.ecs.fetch::<Entity>(), WantsToUseItem{ item, target: result.1 }).expect("Unable to insert intent");
  155. newrunstate = RunState::PlayerTurn;
  156. }
  157. }
  158. }
  159. RunState::MainMenu{ .. } => {
  160. let result = gui::main_menu(self, ctx);
  161. match result {
  162. gui::MainMenuResult::NoSelection{ selected } => newrunstate = RunState::MainMenu{ menu_selection: selected },
  163. gui::MainMenuResult::Selected{ selected } => {
  164. match selected {
  165. gui::MainMenuSelection::NewGame => newrunstate = RunState::PreRun,
  166. gui::MainMenuSelection::LoadGame => {
  167. saveload_system::load_game(&mut self.ecs);
  168. newrunstate = RunState::AwaitingInput;
  169. saveload_system::delete_save();
  170. }
  171. gui::MainMenuSelection::Quit => { ::std::process::exit(0); }
  172. }
  173. }
  174. }
  175. }
  176. RunState::SaveGame => {
  177. saveload_system::save_game(&mut self.ecs);
  178. newrunstate = RunState::MainMenu{ menu_selection : gui::MainMenuSelection::LoadGame };
  179. }
  180. RunState::NextLevel => {
  181. self.goto_next_level();
  182. newrunstate = RunState::PreRun;
  183. }
  184. }
  185. {
  186. let mut runwriter = self.ecs.write_resource::<RunState>();
  187. *runwriter = newrunstate;
  188. }
  189. damage_system::delete_the_dead(&mut self.ecs);
  190. }
  191. }
  192. impl State {
  193. fn entities_to_remove_on_level_change(&mut self) -> Vec<Entity> {
  194. let entities = self.ecs.entities();
  195. let player = self.ecs.read_storage::<Player>();
  196. let backpack = self.ecs.read_storage::<InBackpack>();
  197. let player_entity = self.ecs.fetch::<Entity>();
  198. let mut to_delete : Vec<Entity> = Vec::new();
  199. for entity in entities.join() {
  200. let mut should_delete = true;
  201. // Don't delete the player
  202. let p = player.get(entity);
  203. if let Some(_p) = p {
  204. should_delete = false;
  205. }
  206. // Don't delete the player's equipment
  207. let bp = backpack.get(entity);
  208. if let Some(bp) = bp {
  209. if bp.owner == *player_entity {
  210. should_delete = false;
  211. }
  212. }
  213. if should_delete {
  214. to_delete.push(entity);
  215. }
  216. }
  217. to_delete
  218. }
  219. fn goto_next_level(&mut self) {
  220. // Delete entities that aren't the player or his/her equipment
  221. let to_delete = self.entities_to_remove_on_level_change();
  222. for target in to_delete {
  223. self.ecs.delete_entity(target).expect("Unable to delete entity");
  224. }
  225. // Build a new map and place the player
  226. let worldmap;
  227. {
  228. let mut worldmap_resource = self.ecs.write_resource::<Map>();
  229. let current_depth = worldmap_resource.depth;
  230. *worldmap_resource = Map::new_map_rooms_and_corridors(current_depth + 1);
  231. worldmap = worldmap_resource.clone();
  232. }
  233. // Spawn bad guys
  234. for room in worldmap.rooms.iter().skip(1) {
  235. spawner::spawn_room(&mut self.ecs, room);
  236. }
  237. // Place the player and update resources
  238. let (player_x, player_y) = worldmap.rooms[0].center();
  239. let mut player_position = self.ecs.write_resource::<Point>();
  240. *player_position = Point::new(player_x, player_y);
  241. let mut position_components = self.ecs.write_storage::<Position>();
  242. let player_entity = self.ecs.fetch::<Entity>();
  243. let player_pos_comp = position_components.get_mut(*player_entity);
  244. if let Some(player_pos_comp) = player_pos_comp {
  245. player_pos_comp.x = player_x;
  246. player_pos_comp.y = player_y;
  247. }
  248. // Mark the player's visibility as dirty
  249. let mut viewshed_components = self.ecs.write_storage::<Viewshed>();
  250. let vs = viewshed_components.get_mut(*player_entity);
  251. if let Some(vs) = vs {
  252. vs.dirty = true;
  253. }
  254. // Notify the player and give them some health
  255. let mut gamelog = self.ecs.fetch_mut::<gamelog::GameLog>();
  256. gamelog.entries.insert(0, "You descend to the next level, and take a moment to heal.".to_string());
  257. let mut player_health_store = self.ecs.write_storage::<CombatStats>();
  258. let player_health = player_health_store.get_mut(*player_entity);
  259. if let Some(player_health) = player_health {
  260. player_health.hp = i32::max(player_health.hp, player_health.max_hp / 2);
  261. }
  262. }
  263. }
  264. fn main() {
  265. let mut context = Rltk::init_simple8x8(80, 50, "Hello Rust World", "resources");
  266. context.with_post_scanlines(true);
  267. let mut gs = State {
  268. ecs: World::new()
  269. };
  270. gs.ecs.register::<Position>();
  271. gs.ecs.register::<Renderable>();
  272. gs.ecs.register::<Player>();
  273. gs.ecs.register::<Viewshed>();
  274. gs.ecs.register::<Monster>();
  275. gs.ecs.register::<Name>();
  276. gs.ecs.register::<BlocksTile>();
  277. gs.ecs.register::<CombatStats>();
  278. gs.ecs.register::<WantsToMelee>();
  279. gs.ecs.register::<SufferDamage>();
  280. gs.ecs.register::<Item>();
  281. gs.ecs.register::<ProvidesHealing>();
  282. gs.ecs.register::<InflictsDamage>();
  283. gs.ecs.register::<AreaOfEffect>();
  284. gs.ecs.register::<Consumable>();
  285. gs.ecs.register::<Ranged>();
  286. gs.ecs.register::<InBackpack>();
  287. gs.ecs.register::<WantsToPickupItem>();
  288. gs.ecs.register::<WantsToUseItem>();
  289. gs.ecs.register::<WantsToDropItem>();
  290. gs.ecs.register::<Confusion>();
  291. gs.ecs.register::<SimpleMarker<SerializeMe>>();
  292. gs.ecs.register::<SerializationHelper>();
  293. gs.ecs.insert(SimpleMarkerAllocator::<SerializeMe>::new());
  294. let map : Map = Map::new_map_rooms_and_corridors(1);
  295. let (player_x, player_y) = map.rooms[0].center();
  296. let player_entity = spawner::player(&mut gs.ecs, player_x, player_y);
  297. gs.ecs.insert(rltk::RandomNumberGenerator::new());
  298. for room in map.rooms.iter().skip(1) {
  299. spawner::spawn_room(&mut gs.ecs, room);
  300. }
  301. gs.ecs.insert(map);
  302. gs.ecs.insert(Point::new(player_x, player_y));
  303. gs.ecs.insert(player_entity);
  304. gs.ecs.insert(RunState::MainMenu{ menu_selection: gui::MainMenuSelection::NewGame });
  305. gs.ecs.insert(gamelog::GameLog{ entries : vec!["Welcome to Rusty Roguelike".to_string()] });
  306. rltk::main_loop(context, gs);
  307. }