├── .gitignore ├── src ├── scenes │ ├── save_game.rs │ ├── mod.rs │ ├── show_text.rs │ ├── main_menu.rs │ └── game.rs ├── resources │ ├── camera.rs │ ├── gamelog.rs │ ├── mod.rs │ └── map.rs ├── systems │ ├── mod.rs │ ├── map_indexing_system.rs │ ├── output_system.rs │ ├── energy_system.rs │ ├── melee_combat_system.rs │ ├── monster_ai_systems.rs │ ├── camera_system.rs │ ├── visibility_system.rs │ ├── damage_system.rs │ ├── inventory_system.rs │ └── consume_system.rs ├── ecs.rs ├── messages.rs ├── queues.rs ├── entity_adapter.rs ├── positions.rs ├── components.rs ├── main.rs ├── spawner.rs ├── player.rs └── gui.rs ├── langgen_english ├── .gitignore ├── Cargo.toml ├── tests │ ├── test_output_queue.rs │ └── common │ │ └── mod.rs └── src │ ├── queue_adapter_impls.rs │ ├── traits.rs │ ├── output_queue │ ├── output_helper.rs │ ├── output_builder.rs │ └── mod.rs │ └── lib.rs ├── screenshots └── overview.png ├── .vscode └── settings.json ├── assets └── help.txt ├── .gitmodules ├── README.md ├── Cargo.toml ├── .github └── workflows │ ├── rust.yml │ ├── release.yml │ └── create_new_release.yml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | TODO.md 3 | save.dat 4 | -------------------------------------------------------------------------------- /src/scenes/save_game.rs: -------------------------------------------------------------------------------- 1 | // TODO Implement save 2 | -------------------------------------------------------------------------------- /langgen_english/.gitignore: -------------------------------------------------------------------------------- 1 | /Cargo.lock 2 | /target 3 | -------------------------------------------------------------------------------- /screenshots/overview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bofh69/rouge/HEAD/screenshots/overview.png -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.exclude": { 3 | "**/target": true 4 | }, 5 | "files.watcherExclude": { 6 | "**/target": true 7 | } 8 | } -------------------------------------------------------------------------------- /assets/help.txt: -------------------------------------------------------------------------------- 1 | Keys: 2 | 3 | hjkl - left, down, up, right. 4 | yubn - left+up, right+up, left+down, right+down. 5 | + SHIFT - run in the given direction. 6 | a - apply/eat 7 | d - drop 8 | , - pickup 9 | X - explore 10 | Q - save & quit 11 | SPACE - wait 12 | ESC - quit 13 | 14 | -------------------------------------------------------------------------------- /src/resources/camera.rs: -------------------------------------------------------------------------------- 1 | use crate::MapPosition; 2 | use ::serde::*; 3 | 4 | #[derive(Serialize, Deserialize, Debug, Copy, Clone)] 5 | pub(crate) struct Camera { 6 | pub w: i32, 7 | pub h: i32, 8 | 9 | pub offset: MapPosition, 10 | pub sub_tile_offset: (f32, f32), 11 | pub old_player_pos: MapPosition, 12 | } 13 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "vendor/legion"] 2 | path = vendor/legion 3 | url = git@github.com:bofh69/legion.git 4 | [submodule "vendor/bracket-lib"] 5 | path = vendor/bracket-lib 6 | url = git@github.com:bofh69/rltk_rs.git 7 | [submodule "vendor/legion_typeuuid"] 8 | path = vendor/legion_typeuuid 9 | url = git@github.com:bofh69/legion_typeuuid.git 10 | -------------------------------------------------------------------------------- /langgen_english/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "langgen_english" 3 | version = "0.1.0" 4 | authors = ["Sebastian Andersson "] 5 | edition = "2018" 6 | repository = "https://github.com/bofh69/rouge/" 7 | description = "Output proper English in games" 8 | keywords = [ "gamedev", "text", "english" ] 9 | categories = [ "game-development", "text-processing" ] 10 | license = "MIT OR Apache-2.0" 11 | 12 | 13 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 14 | 15 | [dependencies] 16 | -------------------------------------------------------------------------------- /src/systems/mod.rs: -------------------------------------------------------------------------------- 1 | mod camera_system; 2 | mod consume_system; 3 | mod damage_system; 4 | mod energy_system; 5 | mod inventory_system; 6 | mod map_indexing_system; 7 | mod melee_combat_system; 8 | mod monster_ai_systems; 9 | mod output_system; 10 | mod visibility_system; 11 | 12 | pub(crate) use camera_system::*; 13 | pub(crate) use consume_system::*; 14 | pub(crate) use damage_system::*; 15 | pub(crate) use energy_system::*; 16 | pub(crate) use inventory_system::*; 17 | pub(crate) use map_indexing_system::*; 18 | pub(crate) use melee_combat_system::*; 19 | pub(crate) use monster_ai_systems::*; 20 | pub(crate) use output_system::*; 21 | pub(crate) use visibility_system::*; 22 | -------------------------------------------------------------------------------- /src/ecs.rs: -------------------------------------------------------------------------------- 1 | use legion::*; 2 | 3 | pub(crate) struct Ecs { 4 | pub world: World, 5 | pub resources: Resources, 6 | } 7 | 8 | impl Ecs { 9 | pub fn new() -> Self { 10 | Self { 11 | world: World::default(), 12 | resources: Resources::default(), 13 | } 14 | } 15 | } 16 | 17 | #[macro_export] 18 | macro_rules! resource_get_mut { 19 | ($ecs:expr, $T:ty) => { 20 | $ecs.resources 21 | .get_mut::<$T>() 22 | .expect("Resource is expected") 23 | }; 24 | } 25 | 26 | #[macro_export] 27 | macro_rules! resource_get { 28 | ($ecs:expr, $T:ty) => { 29 | $ecs.resources.get::<$T>().expect("Resource is expected") 30 | }; 31 | } 32 | -------------------------------------------------------------------------------- /src/systems/map_indexing_system.rs: -------------------------------------------------------------------------------- 1 | use crate::components::{BlocksTile, Monster, Position}; 2 | use crate::resources::Map; 3 | use legion::{system, Entity}; 4 | use std::option::Option; 5 | 6 | #[system] 7 | pub(crate) fn map_indexing_clear(#[resource] map: &mut Map) { 8 | map.populate_blocked(); 9 | map.clear_content_index(); 10 | } 11 | 12 | #[system(for_each)] 13 | pub(crate) fn map_indexing( 14 | entity: &Entity, 15 | _block: &BlocksTile, 16 | pos: &Position, 17 | monster: Option<&Monster>, 18 | #[resource] map: &mut Map, 19 | ) { 20 | let idx = map.pos_to_idx(*pos); 21 | map.blocked[idx] = true; 22 | map.tile_content[idx].push(*entity); 23 | map.dangerous[idx] = monster.is_some(); 24 | } 25 | -------------------------------------------------------------------------------- /src/systems/output_system.rs: -------------------------------------------------------------------------------- 1 | use crate::components::{Item, Monster, Name, Position, Viewshed}; 2 | use crate::entity_adapter::EntityAdapterImpl; 3 | use crate::resources::{GameLog, OutputQueue}; 4 | use crate::PlayerEntity; 5 | use ::legion::system; 6 | use legion::world::SubWorld; 7 | 8 | #[system] 9 | #[read_component(Name)] 10 | #[read_component(Item)] 11 | #[read_component(Position)] 12 | #[read_component(Viewshed)] 13 | #[read_component(Monster)] 14 | pub(crate) fn output( 15 | world: &mut SubWorld, 16 | #[resource] output: &mut OutputQueue, 17 | #[resource] gamelog: &mut GameLog, 18 | #[resource] player: &PlayerEntity, 19 | ) { 20 | let mut entity_adapter = EntityAdapterImpl::new(world, gamelog, player.0); 21 | 22 | output.process_queue(&mut entity_adapter); 23 | } 24 | -------------------------------------------------------------------------------- /src/messages.rs: -------------------------------------------------------------------------------- 1 | use crate::positions::MapPosition; 2 | use legion::Entity; 3 | 4 | #[derive(Clone, Debug)] 5 | pub(crate) struct ReceiveHealthMessage { 6 | pub target: Entity, 7 | pub amount: i32, 8 | } 9 | 10 | #[derive(Debug, Clone)] 11 | pub(crate) struct RemoveItemMessage { 12 | pub target: Entity, 13 | } 14 | 15 | #[derive(Debug, Clone)] 16 | pub(crate) struct SufferDamageMessage { 17 | pub target: Entity, 18 | pub amount: i32, 19 | } 20 | 21 | #[derive(Debug, Clone)] 22 | pub(crate) struct WantsToMeleeMessage { 23 | pub attacker: Entity, 24 | pub target: Entity, 25 | } 26 | 27 | #[derive(Clone, Debug)] 28 | pub(crate) struct WantsToDropMessage { 29 | pub who: Entity, 30 | pub item: Entity, 31 | } 32 | 33 | pub(crate) struct WantsToPickupMessage { 34 | pub who: Entity, 35 | pub item: Entity, 36 | } 37 | 38 | pub(crate) struct WantsToUseMessage { 39 | pub who: Entity, 40 | pub item: Entity, 41 | pub target: Option, 42 | } 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rouge 2 | [![Actions status](https://github.com/bofh69/rouge/workflows/Rouge/badge.svg)](https://github.com/bofh69/rouge/actions) 3 | [![Dependency status](https://deps.rs/repo/github/bofh69/rouge/status.svg)](https://deps.rs/repo/github/bofh69/rouge) 4 | 5 | An experiment with [bracket_lib](https://github.com/thebracket/bracket-lib) 6 | and [legion](https://github.com/amethyst/legion), building a simple roguelike. 7 | 8 | This started when I followed the the excellent [Roguelike Tutorial - In Rust](https://bfnightly.bracketproductions.com/rustbook/), 9 | to learn about ECS. It has diverted a lot. 10 | 11 | It is not much of a game yet. Maybe one day it will be more fun playing than coding it? 12 | 13 | ## Screenshot 14 | ![Screenshot](screenshots/overview.png) 15 | 16 | ## Keys 17 | 18 | * F1 - shows the help. 19 | 20 | Lots of things don't work. Create a PR if it bothers you. 21 | 22 | ## Building 23 | 24 | Install [Rust](https://rust-lang.org/). 25 | 26 | Clone the repo (you need to use the SSH link to clone the submodules). 27 | 28 | cargo run 29 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rouge" 3 | description = "A simple roguelike game" 4 | repository = "https://github.com/bofh69/rouge/" 5 | keywords = [ "game", "rougelike" ] 6 | categories = [ "games" ] 7 | version = "0.1.0" 8 | license = "GPL-3.0" 9 | authors = ["Sebastian Andersson "] 10 | edition = "2024" 11 | rust-version = "1.85.0" 12 | 13 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 14 | 15 | [dependencies] 16 | legion_typeuuid = { version = "^0.1.0", path = "vendor/legion_typeuuid", features=['type-uuid', 'collect'] } 17 | langgen_english = { path = "langgen_english" } 18 | crossbeam-channel = "0.5.0" 19 | serde = { version = "1.0", features = [ "derive" ] } 20 | serde_yaml = "0.8.14" 21 | inventory = "0.1.9" 22 | type-uuid = "0.1.2" 23 | bincode = "1.3.1" 24 | bracket-lib = { version = "0.8", features=['serde'] } 25 | legion = "^0.4.0" 26 | # wfc = "*" # For maps? 27 | # grid_2d = "*" # For the Map and Position/ScreenPosition/MapPosition? 28 | 29 | [patch.crates-io] 30 | legion = { path = 'vendor/legion' } 31 | -------------------------------------------------------------------------------- /src/systems/energy_system.rs: -------------------------------------------------------------------------------- 1 | use crate::components::Energy; 2 | use crate::resources::Time; 3 | use crate::RunState; 4 | use ::legion::*; 5 | use legion::world::SubWorld; 6 | 7 | #[system] 8 | #[write_component(Energy)] 9 | pub(crate) fn regain_energy( 10 | world: &mut SubWorld, 11 | #[resource] rs: &RunState, 12 | #[resource] time: &mut Time, 13 | ) { 14 | if *rs == RunState::EnergylessTick { 15 | return; 16 | } 17 | 18 | let mut max = i32::MIN; 19 | 20 | // Find highest energy below zero. 21 | for energy in <&Energy>::query().iter(world) { 22 | if energy.energy < 0 && energy.energy > max { 23 | max = energy.energy; 24 | } 25 | } 26 | 27 | // TODO: Put a cap on max to make turn based animations smoother 28 | // or only when a particle has been spawned? 29 | 30 | let max = max; 31 | if max > i32::MIN { 32 | for energy in <&mut Energy>::query().iter_mut(world) { 33 | if energy.energy < 0 { 34 | energy.energy += -max; 35 | } 36 | } 37 | time.tick += -max as i64; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rouge 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | strategy: 8 | matrix: 9 | os: [ubuntu-latest, macos-12, windows-latest] 10 | include: 11 | - os: ubuntu-latest 12 | - os: macOS-12 13 | - os: windows-latest 14 | 15 | runs-on: ${{ matrix.os }} 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | with: 20 | submodules: 'true' 21 | 22 | - name: Build Release 23 | run: cargo build --verbose 24 | 25 | - name: Run tests 26 | if: matrix.os != 'windows-latest' 27 | run: cargo test --verbose 28 | 29 | - name: Check format 30 | if: matrix.os == 'ubuntu-latest' 31 | run: cargo fmt -- --check 32 | 33 | - name: Archive Windows artifacts 34 | if: matrix.os == 'windows-latest' 35 | uses: actions/upload-artifact@v3 36 | with: 37 | name: Windows Executable 38 | path: target/debug/rouge.exe 39 | 40 | - name: Archive MacOS artifacts 41 | if: matrix.os == 'macos-12' 42 | uses: actions/upload-artifact@v3 43 | with: 44 | name: MacOS Executable 45 | path: target/debug/rouge 46 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Build for release 2 | 3 | on: 4 | repository_dispatch: 5 | types: [release-created] 6 | 7 | jobs: 8 | build: 9 | strategy: 10 | matrix: 11 | os: [ubuntu-latest, macos-12, windows-latest] 12 | include: 13 | - os: ubuntu-latest 14 | os_name: Ubuntu 15 | binary: rouge 16 | - os: macOS-12 17 | os_name: MacOS 18 | binary: rouge 19 | - os: windows-latest 20 | os_name: Windows 21 | binary: rouge.exe 22 | 23 | runs-on: ${{ matrix.os }} 24 | 25 | steps: 26 | - uses: actions/checkout@v3 27 | with: 28 | submodules: 'true' 29 | 30 | - name: Build Release 31 | run: | 32 | cargo build --release --verbose 33 | 34 | - name: Upload release asset 35 | if: matrix.os != 'windows-latest' 36 | uses: actions/upload-release-asset@v1.0.1 37 | env: 38 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 39 | with: 40 | upload_url: ${{ github.event.client_payload.upload_url }} 41 | asset_path: target/release/${{ matrix.binary }} 42 | asset_name: ${{ matrix.os_name }}-${{ matrix.binary }} 43 | asset_content_type: application/binary 44 | -------------------------------------------------------------------------------- /src/queues.rs: -------------------------------------------------------------------------------- 1 | use crate::messages::*; 2 | use ::crossbeam_channel::*; 3 | use legion::*; 4 | 5 | pub(crate) struct Queue { 6 | tx: Sender, 7 | rx: Receiver, 8 | } 9 | 10 | pub(crate) type ReceiveHealthQueue = Queue; 11 | pub(crate) type RemoveItemQueue = Queue; 12 | pub(crate) type SufferDamageQueue = Queue; 13 | pub(crate) type WantsToDropQueue = Queue; 14 | pub(crate) type WantsToPickupQueue = Queue; 15 | pub(crate) type WantsToMeleeQueue = Queue; 16 | pub(crate) type WantsToUseQueue = Queue; 17 | 18 | pub(crate) fn register_queues(resources: &mut Resources) { 19 | resources.insert(ReceiveHealthQueue::new()); 20 | resources.insert(RemoveItemQueue::new()); 21 | resources.insert(SufferDamageQueue::new()); 22 | resources.insert(WantsToDropQueue::new()); 23 | resources.insert(WantsToPickupQueue::new()); 24 | resources.insert(WantsToMeleeQueue::new()); 25 | resources.insert(WantsToUseQueue::new()); 26 | } 27 | 28 | impl Queue { 29 | fn new() -> Self { 30 | let (tx, rx) = unbounded(); 31 | Self { tx, rx } 32 | } 33 | 34 | pub(crate) fn send(&self, msg: T) { 35 | self.tx.send(msg).expect("Queue full?"); 36 | } 37 | 38 | pub(crate) fn try_iter(&self) -> crossbeam_channel::TryIter { 39 | self.rx.try_iter() 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/scenes/mod.rs: -------------------------------------------------------------------------------- 1 | mod game; 2 | mod main_menu; 3 | mod save_game; 4 | mod show_text; 5 | 6 | pub(crate) use main_menu::*; 7 | // pub(crate) use save_game::*; 8 | 9 | use bracket_lib::prelude::*; 10 | 11 | pub(crate) enum SceneResult { 12 | Continue, 13 | Pop, 14 | #[allow(dead_code)] 15 | Push(Box>), 16 | Replace(Box>), 17 | } 18 | 19 | pub(crate) trait Scene { 20 | fn tick(&mut self, state: &mut T, ctx: &mut BTerm) -> SceneResult; 21 | } 22 | 23 | pub(crate) struct SceneManager { 24 | scenes: Vec>>, 25 | } 26 | 27 | impl SceneManager { 28 | pub fn new() -> Self { 29 | Self { scenes: vec![] } 30 | } 31 | 32 | pub fn push(&mut self, scene: Box>) { 33 | self.scenes.push(scene) 34 | } 35 | 36 | pub fn tick(&mut self, state: &mut T, ctx: &mut BTerm) { 37 | if self.scenes.is_empty() { 38 | ctx.quit(); 39 | return; 40 | } 41 | match self.scenes.last_mut().unwrap().tick(state, ctx) { 42 | SceneResult::Continue => (), 43 | SceneResult::Pop => { 44 | self.scenes.pop(); 45 | } 46 | SceneResult::Push(new_scene) => { 47 | self.scenes.push(new_scene); 48 | } 49 | SceneResult::Replace(new_scene) => { 50 | self.scenes.pop(); 51 | self.scenes.push(new_scene); 52 | } 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /langgen_english/tests/test_output_queue.rs: -------------------------------------------------------------------------------- 1 | mod common; 2 | 3 | use common::*; 4 | use langgen_english::*; 5 | use std::collections::vec_deque::VecDeque; 6 | use std::sync::Mutex; 7 | 8 | type DebQueue = Mutex>>; 9 | 10 | type DebOutputQueue = langgen_english::OutputQueue; 11 | 12 | #[test] 13 | fn output_kim() { 14 | let mut oq = DebOutputQueue::new(Mutex::new(VecDeque::new()), 0); 15 | oq.the(1); 16 | let mut dea = DebugEntityAdapter::new(); 17 | 18 | oq.process_queue(&mut dea); 19 | 20 | assert_eq!("Kim.\n", dea.buffer); 21 | } 22 | 23 | #[test] 24 | fn output_the_apple() { 25 | let mut oq = DebOutputQueue::new(Mutex::new(VecDeque::new()), 16); 26 | oq.the(8); 27 | 28 | let mut dea = DebugEntityAdapter::new(); 29 | dea.mock_short_name = "apple"; 30 | dea.mock_has_short_proper = false; 31 | oq.process_queue(&mut dea); 32 | 33 | assert_eq!("The apple.\n", dea.buffer); 34 | } 35 | 36 | #[test] 37 | fn output_advanced_sentance() { 38 | let mut oq = DebOutputQueue::new(Mutex::new(VecDeque::new()), 16); 39 | oq.the(8) 40 | .v(8, "look") 41 | .s("like a \"") 42 | .s("GMO") 43 | .s("\" apple") 44 | .s("someone said"); 45 | 46 | let mut dea = DebugEntityAdapter::new(); 47 | dea.mock_short_name = "apple"; 48 | dea.mock_has_short_proper = false; 49 | oq.process_queue(&mut dea); 50 | 51 | assert_eq!( 52 | "The apple looks like a \"GMO\" apple someone said.\n", 53 | dea.buffer 54 | ); 55 | } 56 | -------------------------------------------------------------------------------- /src/scenes/show_text.rs: -------------------------------------------------------------------------------- 1 | use bracket_lib::prelude::*; 2 | 3 | pub(crate) struct ShowText { 4 | text: &'static str, 5 | } 6 | 7 | impl super::Scene for ShowText { 8 | fn tick(&mut self, _: &mut T, ctx: &mut BTerm) -> super::SceneResult { 9 | let (width, height) = ctx.get_char_size(); 10 | 11 | let mut draw_batch = DrawBatch::new(); 12 | 13 | draw_batch.draw_double_box( 14 | Rect::with_size(8, 1, width - 18, height - 3), 15 | ColorPair::new(BLUE, BLACK), 16 | ); 17 | draw_batch.print_color_centered(1, "HELP", ColorPair::new(YELLOW, BLUE)); 18 | let mut block = TextBlock::new(10, 3, width as i32 - 20, height as i32 - 5); 19 | let mut buf = TextBuilder::empty(); 20 | buf.fg(GREEN).bg(BLACK); 21 | 22 | for line in self.text.split('\n') { 23 | buf.append(line).ln(); 24 | } 25 | let _ = block.print(&buf); 26 | block.render_to_draw_batch(&mut draw_batch); 27 | 28 | draw_batch.print_color_centered( 29 | height as i32 - 2, 30 | "Press ENTER", 31 | ColorPair::new(YELLOW, BLUE), 32 | ); 33 | 34 | draw_batch.submit(0).unwrap(); 35 | render_draw_buffer(ctx).unwrap(); 36 | 37 | if let Some(VirtualKeyCode::Return) = ctx.key { 38 | super::SceneResult::Pop 39 | } else { 40 | super::SceneResult::Continue 41 | } 42 | } 43 | } 44 | 45 | impl ShowText { 46 | pub(crate) fn new(text: &'static str) -> Self { 47 | Self { text } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /.github/workflows/create_new_release.yml: -------------------------------------------------------------------------------- 1 | name: Release for tag 2 | 3 | on: 4 | push: 5 | tags: 6 | - 'v*' # For tags starting with v 7 | 8 | jobs: 9 | release_it: 10 | name: Create release from tag 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Checkout code 15 | uses: actions/checkout@v3 16 | with: 17 | submodules: 'true' 18 | 19 | - name: Create Release 20 | id: create_release 21 | uses: actions/create-release@v1 22 | env: 23 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 24 | with: 25 | tag_name: ${{ github.ref }} 26 | release_name: Release ${{ github.ref }} 27 | draft: true 28 | prerelease: true 29 | 30 | - name: Repository dispatch tag created event 31 | uses: peter-evans/repository-dispatch@v1 32 | with: 33 | token: ${{ secrets.REPO_ACCESS_TOKEN }} 34 | event-type: release-created 35 | client-payload: '{"upload_url": "${{ steps.create_release.outputs.upload_url }}"}' 36 | 37 | # Automatically tag on 38 | # - name: Bump version and push tag/create release point 39 | # id: bump_version 40 | # uses: anothrNick/github-tag-action@1.17.2 41 | # env: 42 | # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 43 | # WITH_V: true 44 | 45 | # - name: Repository dispatch tag created event 46 | # uses: peter-evans/repository-dispatch@v1 47 | # with: 48 | # token: ${{ secrets.REPO_ACCESS_TOKEN }} 49 | # event-type: tag-created 50 | # client-payload: '{"new_version": "${{ steps.bump_version.outputs.new_tag }}"}' 51 | -------------------------------------------------------------------------------- /langgen_english/src/queue_adapter_impls.rs: -------------------------------------------------------------------------------- 1 | use crate::{FragmentEntry, QueueAdapter}; 2 | use ::std::cell::RefCell; 3 | use ::std::collections::{LinkedList, VecDeque}; 4 | use ::std::sync::Mutex; 5 | 6 | /// A suitable `QueueAdapter` when different threads read/write to the same `Queue`. 7 | /// 8 | /// Note: there is no locking employed for the whole sentance so 9 | /// different systems' output can interleave. 10 | impl QueueAdapter for Mutex>> { 11 | fn push(&self, frag: FragmentEntry) { 12 | self.lock().unwrap().push_back(frag); 13 | } 14 | 15 | fn pop(&self) -> Option> { 16 | self.lock().unwrap().pop_front() 17 | } 18 | } 19 | 20 | /// A suitable `QueueAdapter` when different threads read/write to the same `Queue`. 21 | /// 22 | /// Note: there is no locking employed for the whole sentance so 23 | /// different systems' output can interleave. 24 | impl QueueAdapter for Mutex>> { 25 | fn push(&self, frag: FragmentEntry) { 26 | self.lock().unwrap().push_back(frag); 27 | } 28 | 29 | fn pop(&self) -> Option> { 30 | self.lock().unwrap().pop_front() 31 | } 32 | } 33 | 34 | /// A suitable `QueueAdapter` when only one thread can read/write to the same `Queue`. 35 | impl QueueAdapter for RefCell>> { 36 | fn push(&self, frag: FragmentEntry) { 37 | self.borrow_mut().push_back(frag); 38 | } 39 | 40 | fn pop(&self) -> Option> { 41 | self.borrow_mut().pop_front() 42 | } 43 | } 44 | 45 | /// A suitable `QueueAdapter` when only one thread can read/write to the same `Queue`. 46 | impl QueueAdapter for RefCell>> { 47 | fn push(&self, frag: FragmentEntry) { 48 | self.borrow_mut().push_back(frag); 49 | } 50 | 51 | fn pop(&self) -> Option> { 52 | self.borrow_mut().pop_front() 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/scenes/main_menu.rs: -------------------------------------------------------------------------------- 1 | use super::*; 2 | use crate::gui::MainMenuResult::*; 3 | use crate::gui::MainMenuState::*; 4 | use crate::State; 5 | use legion::Schedule; 6 | 7 | pub(crate) struct MainMenuScene { 8 | state: crate::gui::MainMenuState, 9 | schedule: Schedule, 10 | } 11 | 12 | impl Scene for MainMenuScene { 13 | fn tick(&mut self, gs: &mut State, ctx: &mut BTerm) -> SceneResult { 14 | ctx.cls(); 15 | self.schedule 16 | .execute(&mut gs.ecs.world, &mut gs.ecs.resources); 17 | match crate::gui::show_main_menu(ctx, &mut gs.ecs, self.state) { 18 | Selected(New) => { 19 | crate::new(&mut gs.ecs); 20 | { 21 | let mut fil = std::fs::File::create("save.dat").unwrap(); 22 | crate::save(gs, &mut fil).unwrap(); 23 | } 24 | SceneResult::Replace(Box::new(super::game::GameScene::new(gs))) 25 | } 26 | Selected(Quit) => SceneResult::Pop, 27 | Selected(Load) => { 28 | match std::fs::File::open("save.dat") { Ok(mut fil) => { 29 | crate::load(&mut gs.ecs, &mut fil).unwrap(); 30 | std::mem::drop(fil); 31 | let _ = std::fs::remove_file("save.dat"); 32 | SceneResult::Replace(Box::new(super::game::GameScene::new(gs))) 33 | } _ => { 34 | SceneResult::Continue 35 | }} 36 | } 37 | NoSelection(state) => { 38 | self.state = state; 39 | SceneResult::Continue 40 | } 41 | } 42 | } 43 | } 44 | 45 | impl MainMenuScene { 46 | fn build_schedule() -> Schedule { 47 | let mut builder = Schedule::builder(); 48 | builder 49 | .add_system(crate::systems::delete_after_time_system()) 50 | .add_system(crate::systems::delete_after_tick_system()) 51 | .flush() 52 | .build() 53 | } 54 | 55 | pub fn new() -> MainMenuScene { 56 | MainMenuScene { 57 | state: crate::gui::MainMenuState::New, 58 | schedule: Self::build_schedule(), 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/resources/gamelog.rs: -------------------------------------------------------------------------------- 1 | use ::serde::*; 2 | use bracket_lib::prelude::{BTerm, BLACK, WHITE}; 3 | use legion::Entity; 4 | use std::collections::VecDeque; 5 | use std::sync::Mutex; 6 | 7 | pub(crate) type QueueAdapter = Mutex>>; 8 | pub(crate) type OutputQueue = langgen_english::OutputQueue; 9 | 10 | #[derive(Clone, Serialize, Deserialize)] 11 | enum LogEntry { 12 | Text(String), 13 | Color((u8, u8, u8)), 14 | } 15 | 16 | #[derive(Serialize, Deserialize)] 17 | pub(crate) struct GameLog { 18 | entries: Vec>, 19 | current_line: Vec, 20 | } 21 | 22 | impl GameLog { 23 | pub fn new() -> Self { 24 | Self { 25 | entries: vec![], 26 | current_line: vec![], 27 | } 28 | } 29 | 30 | pub fn write_text>(&mut self, s: T) { 31 | self.current_line.push(LogEntry::Text(s.into())); 32 | } 33 | 34 | pub fn set_color(&mut self, color: (u8, u8, u8)) { 35 | self.current_line.push(LogEntry::Color(color)); 36 | } 37 | 38 | pub fn end_of_line(&mut self) { 39 | self.entries.push(self.current_line.clone()); 40 | self.current_line.clear(); 41 | } 42 | 43 | pub fn draw_log(&self, ctx: &mut BTerm, last_line: u32, rows: u32) { 44 | let rows = rows as usize; 45 | let l = self.entries.len(); 46 | let entries = if rows < l { 47 | let (_, entries) = self.entries.split_at(l - rows); 48 | entries 49 | } else { 50 | &self.entries 51 | }; 52 | for (i, line) in entries.iter().rev().enumerate() { 53 | let y = last_line as i32 - i as i32; 54 | let mut x = 1; 55 | let mut color = WHITE; 56 | 57 | for entry in line { 58 | match entry { 59 | LogEntry::Text(text) => { 60 | ctx.print_color(x, y, color, BLACK, text); 61 | x += text.chars().count(); 62 | } 63 | LogEntry::Color(c) => { 64 | color = *c; 65 | } 66 | } 67 | } 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /langgen_english/src/traits.rs: -------------------------------------------------------------------------------- 1 | use crate::FragmentEntry; 2 | use crate::Gender; 3 | 4 | /// [`OutputQueue`](crate::OutputQueue)'s interface to the game's ECS Components and 5 | /// the games output routines. 6 | /// 7 | /// Entity is a Copy type identifying a player, character or thing. 8 | pub trait EntityAdapter 9 | where 10 | Entity: Copy, 11 | { 12 | /// Can who see obj? 13 | fn can_see(&self, who: Entity, obj: Entity) -> bool; 14 | /// Is obj me? 15 | fn is_me(&self, obj: Entity) -> bool; 16 | 17 | /// Returns obj's gender (which is also plural & uncountable for things). 18 | fn gender(&self, obj: Entity) -> Gender; 19 | 20 | /// Is obj a thing? 21 | fn is_thing(&self, obj: Entity) -> bool; 22 | 23 | /// Does obj have a proper name (ie Thomas)? 24 | fn has_short_proper(&self, obj: Entity) -> bool; 25 | 26 | /// The objects short name. Typically a single word, like "apple". 27 | fn append_short_name(&self, obj: Entity, s: &mut String); 28 | 29 | /// Is the object's long name a proper name (ie Ada Lovecraft)? 30 | fn has_long_proper(&self, obj: Entity) -> bool; 31 | 32 | /// The object's long name, ie "red apple". 33 | fn append_long_name(&self, obj: Entity, s: &mut String); 34 | 35 | /// The objects short, plural name. Typically a single word, like "apples". 36 | fn append_short_plural_name(&self, obj: Entity, s: &mut String); 37 | 38 | /// The object's long, plural name, ie "red apples". 39 | fn append_long_plural_name(&self, obj: Entity, s: &mut String); 40 | 41 | /// Writes the given text to the player. 42 | fn write_text(&mut self, text: &str); 43 | 44 | /// Sets the output color to the given color. 45 | fn set_color(&mut self, color: (u8, u8, u8)); 46 | 47 | /// Called when all the text for the current line/sentance has been 48 | /// written with `write_text`. 49 | /// 50 | /// Restores the color to the default color. 51 | fn done(&mut self); 52 | } 53 | 54 | /// `OutputQueue`'s interface against queues. 55 | pub trait QueueAdapter { 56 | /// Pushes an entry to the end of the queue. 57 | fn push(&self, f: FragmentEntry); 58 | 59 | /// Pops the next entry from the queue, or `None` if there are none. 60 | fn pop(&self) -> Option>; 61 | } 62 | -------------------------------------------------------------------------------- /langgen_english/src/output_queue/output_helper.rs: -------------------------------------------------------------------------------- 1 | use crate::Gender; 2 | 3 | pub(crate) fn last_char(s: &str) -> Option { 4 | s.chars().next_back() 5 | } 6 | 7 | pub(crate) fn needs_dot(s: &str) -> bool { 8 | if let Some(c) = last_char(s) { 9 | !matches!(c, '.' | '?' | '!' | ':' | ';' | '"') 10 | } else { 11 | false 12 | } 13 | } 14 | 15 | // Used to decide between a/an. 16 | pub(crate) fn is_vowel(c: char) -> bool { 17 | matches!(c, 'a' | 'e' | 'i' | 'o' | 'u' | 'A' | 'E' | 'I' | 'O' | 'U') 18 | // y is usually not pronounced like a vowel. 19 | } 20 | 21 | pub(crate) fn uppercase_first_char(s: &str, to: &mut String) { 22 | let mut c = s.chars(); 23 | if let Some(ch) = c.next() { 24 | for ch in ch.to_uppercase() { 25 | to.push(ch); 26 | } 27 | to.push_str(c.as_str()); 28 | } 29 | } 30 | 31 | pub(crate) fn is_singular(gender: Gender) -> bool { 32 | !matches!(gender, Gender::Plural | Gender::Uncountable) 33 | } 34 | 35 | pub(crate) fn add_verb_end_s(str: &mut String) { 36 | let mut add: &str = ""; 37 | let mut uc = false; 38 | let mut remove = 0; 39 | 40 | { 41 | let mut ci = str.chars().rev(); 42 | if let Some(ch) = ci.next() { 43 | if ch.is_uppercase() { 44 | uc = true; 45 | } 46 | add = match ch { 47 | 's' | 'o' | 'z' | 'x' | 'S' | 'O' | 'Z' | 'X' => "es", 48 | 'y' | 'Y' => { 49 | remove = 1; 50 | 51 | ci.next().map_or("ies", |c2| if is_vowel(c2) { 52 | remove = 0; 53 | "s" 54 | } else { 55 | "ies" 56 | }) 57 | } 58 | 'h' | 'H' => { 59 | 60 | ci.next().map_or("s", |c2| if c2 == 'c' || c2 == 's' || c2 == 'C' || c2 == 'S' { 61 | "es" 62 | } else { 63 | "s" 64 | }) 65 | } 66 | _ => "s", 67 | } 68 | } 69 | while remove > 0 { 70 | str.pop(); 71 | remove -= 1; 72 | } 73 | if uc { 74 | str.push_str(&add.to_uppercase()); 75 | } else { 76 | str.push_str(add); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/systems/melee_combat_system.rs: -------------------------------------------------------------------------------- 1 | use crate::components::{CombatStats, Energy}; 2 | use crate::messages::{SufferDamageMessage, WantsToMeleeMessage}; 3 | use crate::queues::{SufferDamageQueue, WantsToMeleeQueue}; 4 | use crate::resources::OutputQueue; 5 | use legion::world::SubWorld; 6 | use legion::*; 7 | 8 | #[system] 9 | #[read_component(CombatStats)] 10 | #[write_component(Energy)] 11 | pub(crate) fn melee_combat( 12 | world: &mut SubWorld, 13 | #[resource] suffer_damage_queue: &SufferDamageQueue, 14 | #[resource] wants_to_melee_queue: &mut WantsToMeleeQueue, 15 | #[resource] output: &OutputQueue, 16 | ) { 17 | for WantsToMeleeMessage { 18 | attacker: attacker_entity, 19 | target: melee_target_entity, 20 | } in wants_to_melee_queue.try_iter() 21 | { 22 | if let Ok(attacker_entry) = world.entry_ref(attacker_entity) { 23 | let attacker_power = attacker_entry.get_component::().unwrap().power; 24 | let target = world.entry_ref(melee_target_entity); 25 | match target { Ok(target) => { 26 | let target_stats = target.get_component::().unwrap(); 27 | 28 | if target_stats.hp > 0 { 29 | let damage = i32::max(0, attacker_power - target_stats.defense); 30 | 31 | if damage == 0 { 32 | output 33 | .the(attacker_entity) 34 | .is(attacker_entity) 35 | .s("unable to hurt") 36 | .the(melee_target_entity); 37 | } else { 38 | output 39 | .the(attacker_entity) 40 | .v(attacker_entity, "hit") 41 | .the(melee_target_entity) 42 | .string(format!(", for {damage} hp")); 43 | suffer_damage_queue.send(SufferDamageMessage { 44 | target: melee_target_entity, 45 | amount: damage, 46 | }); 47 | } 48 | } 49 | } _ => { 50 | output 51 | .the(attacker_entity) 52 | .v(attacker_entity, "want") 53 | .s("to attak a ghost?"); 54 | }} 55 | let mut entry = world.entry_mut(attacker_entity).unwrap(); 56 | entry.get_component_mut::().unwrap().energy = -120; 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/systems/monster_ai_systems.rs: -------------------------------------------------------------------------------- 1 | use crate::components::{Energy, Monster, Position, Viewshed}; 2 | use crate::messages::WantsToMeleeMessage; 3 | use crate::queues::WantsToMeleeQueue; 4 | use crate::resources::{Map, PlayerEntity, PlayerPosition}; 5 | use crate::RunState; 6 | use bracket_lib::prelude::*; 7 | use legion::{system, world::SubWorld, Entity, IntoQuery}; 8 | 9 | #[system] 10 | #[read_component(Monster)] 11 | #[write_component(Viewshed)] 12 | #[write_component(Position)] 13 | #[write_component(Energy)] 14 | pub(crate) fn monster_ai( 15 | world: &mut SubWorld, 16 | #[resource] rs: &RunState, 17 | #[resource] map: &mut Map, 18 | #[resource] player_pos: &mut PlayerPosition, 19 | #[resource] player_entity: &mut PlayerEntity, 20 | #[resource] wants_to_melee_queue: &WantsToMeleeQueue, 21 | ) { 22 | if *rs != RunState::Tick && *rs != RunState::EnergylessTick { 23 | return; 24 | } 25 | 26 | let player_pos = player_pos.0; 27 | let player_entity = player_entity.0; 28 | 29 | let mut ready: Vec<_> = <(Entity, &mut Viewshed, &mut Position, &mut Energy)>::query() 30 | .filter(legion::query::component::()) 31 | .iter_mut(world) 32 | .filter(|(_, _, _, energy)| energy.energy >= 0) 33 | .collect(); 34 | 35 | ready.sort_by_key(|(_, _, _, energy)| -energy.energy); 36 | 37 | for (entity, viewshed, pos, energy) in ready { 38 | let distance = 39 | DistanceAlg::Chebyshev.distance2d(Point::new(pos.0.x, pos.0.y), player_pos.into()); 40 | if distance < 1.5 { 41 | // Attack goes here 42 | wants_to_melee_queue.send(WantsToMeleeMessage { 43 | attacker: *entity, 44 | target: player_entity, 45 | }); 46 | } else if viewshed.visible_tiles.contains(&player_pos) { 47 | let path = a_star_search( 48 | map.pos_to_idx(*pos) as i32, 49 | map.map_pos_to_idx(player_pos) as i32, 50 | &*map, 51 | ); 52 | if path.success && path.steps.len() > 1 { 53 | // TODO: Move to some action system. 54 | // Walk towards player: 55 | energy.energy = -100; 56 | let old_idx = map.pos_to_idx(*pos); 57 | let new_idx = path.steps[1]; 58 | let new_pos = map.index_to_point2d(new_idx); 59 | if !map.blocked[new_idx] { 60 | pos.0.x = new_pos.x; 61 | pos.0.y = new_pos.y; 62 | map.blocked[old_idx] = false; 63 | map.blocked[new_idx] = true; 64 | map.dangerous[old_idx] = false; 65 | map.dangerous[new_idx] = true; 66 | viewshed.dirty = true; 67 | } 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/systems/camera_system.rs: -------------------------------------------------------------------------------- 1 | use crate::positions::{MapPosition, ScreenPosition}; 2 | use crate::resources::{Camera, PlayerPosition}; 3 | use crate::resources::{MAP_HEIGHT, MAP_WIDTH}; 4 | use ::legion::*; 5 | 6 | fn diff_to_interval(v: i32, min: i32, max: i32) -> i32 { 7 | if v < min { 8 | min - v 9 | } else if v > max { 10 | max - v 11 | } else { 12 | 0 13 | } 14 | } 15 | 16 | #[system] 17 | pub(crate) fn camera_update( 18 | #[resource] camera: &mut Camera, 19 | #[resource] player_position: &PlayerPosition, 20 | ) { 21 | let pos: MapPosition = player_position.0; 22 | 23 | if !camera.is_in_view(pos) { 24 | camera.center(*player_position); 25 | } else if camera.old_player_pos != pos { 26 | let screen_pos = pos - camera.offset; 27 | let (dx, dy); 28 | dx = diff_to_interval(screen_pos.x, camera.w / 3, 2 * camera.w / 3); 29 | dy = diff_to_interval(screen_pos.y, camera.h / 3, 2 * camera.h / 3); 30 | 31 | camera.move_view(-dx, -dy); 32 | 33 | camera.old_player_pos = pos; 34 | } 35 | } 36 | 37 | impl Camera { 38 | pub fn new(width: i32, height: i32) -> Self { 39 | Self { 40 | w: width, 41 | h: height, 42 | offset: MapPosition { x: -1, y: -1 }, 43 | sub_tile_offset: (0.0, 0.0), 44 | old_player_pos: MapPosition { x: -1, y: -1 }, 45 | } 46 | } 47 | 48 | // Hard jump to new position 49 | pub fn center(&mut self, pos: PlayerPosition) { 50 | self.old_player_pos = pos.0; 51 | self.sub_tile_offset = (0.0, 0.0); 52 | 53 | let (x, y) = ( 54 | i32::min(MAP_WIDTH - self.w, i32::max(0, (pos.0).x - self.w / 2)), 55 | i32::min(MAP_HEIGHT - self.h, i32::max(0, (pos.0).y - self.h / 2)), 56 | ); 57 | 58 | self.offset = MapPosition { x, y }; 59 | } 60 | 61 | pub fn move_view(&mut self, dx: i32, dy: i32) { 62 | let (x, y) = ( 63 | i32::min(MAP_WIDTH - self.w, i32::max(0, self.offset.x + dx)), 64 | i32::min(MAP_HEIGHT - self.h, i32::max(0, self.offset.y + dy)), 65 | ); 66 | 67 | self.offset = MapPosition { x, y }; 68 | } 69 | 70 | pub fn transform_screen_pos(&self, p: ScreenPosition) -> MapPosition { 71 | MapPosition { 72 | x: p.x + self.offset.x, 73 | y: p.y + self.offset.y, 74 | } 75 | } 76 | 77 | pub fn transform_map_pos(&self, p: MapPosition) -> ScreenPosition { 78 | ScreenPosition { 79 | x: p.x - self.offset.x, 80 | y: p.y - self.offset.y, 81 | } 82 | } 83 | 84 | pub fn is_in_view(&self, p: MapPosition) -> bool { 85 | !(p.x < self.offset.x 86 | || p.x >= (self.offset.x + self.w) 87 | || p.y < self.offset.y 88 | || p.y >= (self.offset.y + self.h)) 89 | } 90 | 91 | pub fn width(&self) -> i32 { 92 | self.w 93 | } 94 | 95 | pub fn height(&self) -> i32 { 96 | self.h 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/systems/visibility_system.rs: -------------------------------------------------------------------------------- 1 | use crate::components::{Player, Position, Viewshed}; 2 | use crate::positions::MapPosition; 3 | use crate::resources::{Map, PlayerEntity, PlayerTarget}; 4 | use ::bracket_lib::prelude::field_of_view; 5 | use ::legion::world::SubWorld; 6 | use ::legion::*; 7 | 8 | struct ViewshedPlayerUpdate(bool); 9 | 10 | pub(crate) fn add_viewshed_system( 11 | ecs: &mut crate::ecs::Ecs, 12 | schedule_builder: &mut systems::Builder, 13 | ) { 14 | ecs.resources.insert(ViewshedPlayerUpdate(false)); 15 | 16 | let system = SystemBuilder::new("Viewshed") 17 | .read_resource::() 18 | .write_resource::() 19 | .write_resource::() 20 | .with_query(<(Entity, Write, Read)>::query()) 21 | .build( 22 | move |_commands, world, (player_entity, map, viewshed_player_update), query| { 23 | viewshed_player_update.0 = false; 24 | for (ent, viewshed, pos) in query.iter_mut(world) { 25 | if viewshed.dirty { 26 | viewshed.visible_tiles.clear(); 27 | 28 | /* The points here are in map space */ 29 | viewshed.visible_tiles = 30 | field_of_view(pos.0.into(), viewshed.range, &**map) 31 | .iter() 32 | .filter_map(|p| { 33 | if p.x >= 0 && p.x < map.width && p.y >= 0 && p.y < map.height { 34 | Some(MapPosition { x: p.x, y: p.y }) 35 | } else { 36 | None 37 | } 38 | }) 39 | .collect(); 40 | 41 | // If this is the player, reveal what they can see 42 | if *ent == player_entity.0 { 43 | viewshed_player_update.0 = true; 44 | } 45 | viewshed.dirty = false; 46 | } 47 | } 48 | }, 49 | ); 50 | schedule_builder.add_system(system); 51 | 52 | schedule_builder.add_system(update_map_for_player_system()); 53 | } 54 | 55 | #[system] 56 | #[read_component(Player)] 57 | #[write_component(Viewshed)] 58 | fn update_map_for_player( 59 | world: &mut SubWorld, 60 | #[resource] player_update: &ViewshedPlayerUpdate, 61 | #[resource] map: &mut Map, 62 | #[resource] player_target: &mut PlayerTarget, 63 | ) { 64 | if player_update.0 { 65 | for vt in &mut map.visible_tiles { 66 | *vt = false; 67 | } 68 | 69 | for (viewshed, _player) in <(&mut Viewshed, &Player)>::query().iter_mut(world) { 70 | for vis in &viewshed.visible_tiles { 71 | let idx = map.map_pos_to_idx(*vis); 72 | map.revealed_tiles[idx] = true; 73 | map.visible_tiles[idx] = true; 74 | if map.dangerous[idx] { 75 | *player_target = PlayerTarget::None; 76 | } 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /langgen_english/tests/common/mod.rs: -------------------------------------------------------------------------------- 1 | use langgen_english::*; 2 | use std::cell::Cell; 3 | 4 | pub struct DebugEntityAdapter { 5 | pub buffer: String, 6 | pub mock_can_see: bool, 7 | pub mock_is_me: bool, 8 | pub mock_gender: Gender, 9 | pub mock_is_thing: bool, 10 | pub mock_has_short_proper: bool, 11 | pub mock_short_name: &'static str, 12 | pub mock_has_long_proper: bool, 13 | pub mock_long_name: &'static str, 14 | pub mock_short_plural_name: &'static str, 15 | pub mock_long_plural_name: &'static str, 16 | 17 | pub last_who: Cell, 18 | pub last_obj: Cell, 19 | } 20 | 21 | impl DebugEntityAdapter { 22 | pub fn new() -> Self { 23 | Self { 24 | buffer: String::new(), 25 | mock_can_see: true, 26 | mock_is_me: false, 27 | mock_gender: Gender::Neuter, 28 | mock_is_thing: false, 29 | mock_has_short_proper: true, 30 | mock_short_name: "Kim", 31 | mock_has_long_proper: false, 32 | mock_long_name: "spirit of Kim", 33 | mock_short_plural_name: "Kims", 34 | mock_long_plural_name: "spirits of Kim", 35 | last_obj: Cell::new(-1), 36 | last_who: Cell::new(-2), 37 | } 38 | } 39 | } 40 | 41 | impl EntityAdapter for DebugEntityAdapter { 42 | fn can_see(&self, who: i32, obj: i32) -> bool { 43 | self.last_who.set(who); 44 | self.last_obj.set(obj); 45 | self.mock_can_see 46 | } 47 | 48 | fn is_me(&self, obj: i32) -> bool { 49 | self.last_obj.set(obj); 50 | self.mock_is_me 51 | } 52 | 53 | fn gender(&self, obj: i32) -> Gender { 54 | self.last_obj.set(obj); 55 | self.mock_gender.clone() 56 | } 57 | 58 | fn is_thing(&self, obj: i32) -> bool { 59 | self.last_obj.set(obj); 60 | self.mock_is_thing 61 | } 62 | 63 | fn has_short_proper(&self, obj: i32) -> bool { 64 | self.last_obj.set(obj); 65 | self.mock_has_short_proper 66 | } 67 | 68 | fn append_short_name(&self, obj: i32, s: &mut String) { 69 | self.last_obj.set(obj); 70 | 71 | s.push_str(self.mock_short_name); 72 | } 73 | 74 | fn has_long_proper(&self, obj: i32) -> bool { 75 | self.last_obj.set(obj); 76 | self.mock_has_long_proper 77 | } 78 | fn append_long_name(&self, obj: i32, s: &mut String) { 79 | self.last_obj.set(obj); 80 | s.push_str(self.mock_long_name); 81 | } 82 | 83 | fn append_short_plural_name(&self, obj: i32, s: &mut String) { 84 | self.last_obj.set(obj); 85 | s.push_str(self.mock_short_plural_name); 86 | } 87 | 88 | fn append_long_plural_name(&self, obj: i32, s: &mut String) { 89 | self.last_obj.set(obj); 90 | s.push_str(self.mock_long_plural_name); 91 | } 92 | 93 | fn write_text(&mut self, text: &str) { 94 | self.buffer.push_str(text); 95 | } 96 | 97 | fn set_color(&mut self, color: (u8, u8, u8)) { 98 | self.write_text(&format!("{:?}", color)); 99 | } 100 | 101 | fn done(&mut self) { 102 | self.write_text(&"\n"); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/entity_adapter.rs: -------------------------------------------------------------------------------- 1 | use crate::components::{Item, Name, Position, Viewshed}; 2 | use crate::resources::GameLog; 3 | use ::langgen_english::*; 4 | use ::legion::*; 5 | use legion::world::SubWorld; 6 | 7 | pub(crate) struct EntityAdapterImpl<'a, 'w> { 8 | world: &'a mut SubWorld<'w>, 9 | gamelog: &'a mut GameLog, 10 | player: Entity, 11 | } 12 | 13 | impl<'a, 'w> EntityAdapterImpl<'a, 'w> { 14 | pub(crate) fn new( 15 | world: &'a mut SubWorld<'w>, 16 | gamelog: &'a mut GameLog, 17 | player: Entity, 18 | ) -> Self { 19 | Self { 20 | world, 21 | gamelog, 22 | player, 23 | } 24 | } 25 | } 26 | 27 | impl EntityAdapter for EntityAdapterImpl<'_, '_> { 28 | fn is_me(&self, who: Entity) -> bool { 29 | who == self.player 30 | } 31 | fn can_see(&self, who: Entity, obj: Entity) -> bool { 32 | match self.world.entry_ref(who) { Ok(who_entry) => { 33 | match self.world.entry_ref(obj) { Ok(obj_entry) => { 34 | match obj_entry.get_component::() { Ok(pos) => { 35 | match who_entry.get_component::() { Ok(vs) => { 36 | vs.visible_tiles.contains(&pos.0) 37 | } _ => { 38 | true 39 | }} 40 | } _ => { 41 | true 42 | }} 43 | } _ => { 44 | true 45 | }} 46 | } _ => { 47 | true 48 | }} 49 | } 50 | fn gender(&self, _: Entity) -> langgen_english::Gender { 51 | // TODO: 52 | langgen_english::Gender::Male 53 | } 54 | fn is_thing(&self, who: Entity) -> bool { 55 | self.world 56 | .entry_ref(who).is_ok_and(|e| e.get_component::().is_ok()) 57 | } 58 | fn has_short_proper(&self, who: Entity) -> bool { 59 | self.world.entry_ref(who).is_ok_and(|e| { 60 | e.get_component::().is_ok_and(|n| n.proper_name) 61 | }) 62 | } 63 | fn append_short_name(&self, who: Entity, s: &mut String) { 64 | if let Ok(entry) = self.world.entry_ref(who) { 65 | if let Ok(name) = entry.get_component::() { 66 | s.push_str(&name.name); 67 | return; 68 | } 69 | } 70 | s.push_str(""); 71 | } 72 | fn has_long_proper(&self, _: Entity) -> bool { 73 | todo!() 74 | } 75 | fn append_long_name(&self, who: Entity, s: &mut String) { 76 | // TODO 77 | if let Ok(entry) = self.world.entry_ref(who) { 78 | if let Ok(name) = entry.get_component::() { 79 | s.push_str(&name.name); 80 | return; 81 | } 82 | } 83 | s.push_str(""); 84 | } 85 | fn append_short_plural_name(&self, _: Entity, _s: &mut String) { 86 | todo!() 87 | } 88 | fn append_long_plural_name(&self, _: Entity, _s: &mut String) { 89 | todo!() 90 | } 91 | fn write_text(&mut self, text: &str) { 92 | self.gamelog.write_text(text); 93 | } 94 | fn set_color(&mut self, color: (u8, u8, u8)) { 95 | self.gamelog.set_color(color); 96 | } 97 | fn done(&mut self) { 98 | self.gamelog.end_of_line(); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/systems/damage_system.rs: -------------------------------------------------------------------------------- 1 | use crate::components::*; 2 | use crate::messages::{ReceiveHealthMessage, RemoveItemMessage, SufferDamageMessage}; 3 | use crate::queues::{ReceiveHealthQueue, RemoveItemQueue, SufferDamageQueue}; 4 | use crate::resources::{Map, OutputQueue, PlayerEntity, Time}; 5 | use legion::world::SubWorld; 6 | use legion::{system, systems::CommandBuffer, Entity, EntityStore}; 7 | 8 | #[system] 9 | #[write_component(CombatStats)] 10 | pub(crate) fn damage(world: &mut SubWorld, #[resource] queue: &SufferDamageQueue) { 11 | for SufferDamageMessage { target, amount } in queue.try_iter() { 12 | if let Ok(ref mut entry) = world.entry_mut(target) { 13 | if let Ok(stats) = entry.get_component_mut::() { 14 | stats.hp -= amount; 15 | } 16 | } 17 | } 18 | } 19 | 20 | #[system] 21 | #[write_component(CombatStats)] 22 | pub(crate) fn health(world: &mut SubWorld, #[resource] receive_health_queue: &ReceiveHealthQueue) { 23 | for ReceiveHealthMessage { target, amount } in receive_health_queue.try_iter() { 24 | if let Ok(ref mut entry) = world.entry_mut(target) { 25 | if let Ok(stats) = entry.get_component_mut::() { 26 | if stats.max_hp == stats.hp { 27 | stats.max_hp += 1 + amount / 8; 28 | stats.hp = stats.max_hp; 29 | } else { 30 | stats.hp = i32::min(stats.max_hp, stats.hp + amount); 31 | } 32 | } 33 | } 34 | } 35 | } 36 | 37 | #[system(for_each)] 38 | pub(crate) fn output_die( 39 | entity: &Entity, 40 | stats: &mut CombatStats, 41 | #[resource] output: &OutputQueue, 42 | #[resource] player_entity: &PlayerEntity, 43 | ) { 44 | if stats.hp < 1 { 45 | if player_entity.0 == *entity { 46 | output.s("You are dead"); 47 | } else { 48 | output.the(*entity).v(*entity, "die"); 49 | } 50 | } 51 | } 52 | 53 | #[system(for_each)] 54 | pub(crate) fn delete_the_dead( 55 | entity: &Entity, 56 | stats: &mut CombatStats, 57 | pos: &Position, 58 | cb: &mut CommandBuffer, 59 | #[resource] player_entity: &PlayerEntity, 60 | #[resource] map: &mut Map, 61 | ) { 62 | if stats.hp < 1 && player_entity.0 != *entity { 63 | let idx = map.pos_to_idx(pos.0.into()); 64 | // TODO: Handle via Events instead 65 | map.blocked[idx] = false; 66 | map.dangerous[idx] = false; 67 | cb.remove(*entity); 68 | } 69 | } 70 | 71 | #[system] 72 | #[write_component(Item)] 73 | pub(crate) fn delete_items(cb: &mut CommandBuffer, #[resource] queue: &mut RemoveItemQueue) { 74 | for RemoveItemMessage { target } in queue.try_iter() { 75 | cb.remove(target); 76 | } 77 | } 78 | 79 | #[system(for_each)] 80 | pub(crate) fn delete_after_tick( 81 | entity: &Entity, 82 | end_tick: &EndTick, 83 | cb: &mut CommandBuffer, 84 | #[resource] time: &Time, 85 | ) { 86 | if end_tick.end_tick <= time.tick { 87 | cb.remove(*entity); 88 | } 89 | } 90 | 91 | #[system(for_each)] 92 | pub(crate) fn delete_after_time( 93 | entity: &Entity, 94 | end_time: &EndTime, 95 | cb: &mut CommandBuffer, 96 | #[resource] time: &Time, 97 | ) { 98 | if end_time.end_time_ms <= time.real_time_ms { 99 | cb.remove(*entity); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /langgen_english/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! ECS friendly way of sending correct English texts to players. 2 | //! 3 | //! Example: 4 | //! ```ignore 5 | //! 6 | //! // This is put as a resource or component in the ECS: 7 | //! let mut output_queue = OutputQueue::new(Mutex::new(VecDeque::new()), PLAYER_ENTITY); 8 | //! 9 | //! // In systems you write things like this: 10 | //! output_queue.the_(monster).v(monster, "swing").my(monster, object); 11 | //! 12 | //! // At the end of the tick/frame, run output_queue to actually process the message. 13 | //! // Do it before entities are removed. 14 | //! output_queue.process_queue(&mut entity_adapter); 15 | //! ``` 16 | //! The `entity_adapter` will in the end be asked out output strings like this: 17 | //! ```text 18 | //! The tall goblin swings her club. (Correct pronoun before the object's name). 19 | //! Gandalf the great swings his staff. (No the before proper names). 20 | //! The band of brothers swing something. (The player can't see the object). 21 | //! You swing your fist. (The player won't see herself in third person). 22 | //! ``` 23 | //! 24 | //! `OutputQueue` queues messages until `process_queue` is called. 25 | //! This is needed to avoid lifetime/concurrency issues when one system 26 | //! is running and the `EntityAdapter` needs to lookup some `Entity`'s Component. 27 | //! 28 | //! The game will have to be architectured with this in mind whenever the results from 29 | //! the `EntityAdapter` might change between creating a message and calling `process_queue`. 30 | //! Instead of changing the attributes directly, use some temporary marker, have a system 31 | //! that runs `process_queue` and then update the primary components. Same when removing 32 | //! an `Entity`. 33 | //! 34 | //! To get a working system, provide: 35 | //! 36 | //! * `Entity` - Copy type that represents all the characters, things and players. 37 | //! * [`EntityAdapter`](EntityAdapter) - looks up info about the entity and outputs text to the player. 38 | //! * [`QueueAdapter`](QueueAdapter) - handles queueing of messages between threads. 39 | //! 40 | //! The crate provide implementations of `QueueAdapter` for `RefCell/Mutex` together with `LinkedList`/`VecDeque`. 41 | 42 | #![warn(missing_docs)] // warn if there is missing docs 43 | 44 | mod output_queue; 45 | mod queue_adapter_impls; 46 | mod traits; 47 | 48 | pub use output_queue::*; 49 | pub use traits::*; 50 | 51 | /// Messages between `OutputBuilder` and `OutputQueue.process` 52 | #[derive(Debug)] 53 | enum Fragment { 54 | The(Entity), 55 | A(Entity), 56 | The_(Entity), 57 | A_(Entity), 58 | My(Entity, Entity), 59 | My_(Entity, Entity), 60 | 61 | Is(Entity), // Send is/are 62 | Has(Entity), // Send is/are 63 | 64 | Thes(Entity), // Your/The X's 65 | Thes_(Entity), // Your/The X's 66 | Thess(Entity), // Yours/The X's 67 | Thess_(Entity), // Yours/The X's 68 | 69 | Word(Entity), // Just the name 70 | Word_(Entity), // Just the name 71 | 72 | Color((u8, u8, u8)), 73 | 74 | VerbRef(Entity, &'static str), 75 | VerbString(Entity, String), 76 | 77 | TextRef(&'static str), 78 | Text(String), 79 | 80 | SupressSpace(bool), // Weather to not automatically add a space or not. 81 | SupressDot(bool), // Weather to automatically add a dot or not. 82 | Capitalize(bool), // Capitalize the next word or not. 83 | 84 | EndOfLine, 85 | } 86 | 87 | /// Encapsulates messages sent via [`QueueAdapter`](QueueAdapter)s. 88 | pub struct FragmentEntry(Fragment); 89 | 90 | /// Represents the gender & uncountability of an `Entity` 91 | #[derive(Copy, Clone)] 92 | #[allow(missing_docs)] 93 | pub enum Gender { 94 | Male, 95 | Female, 96 | Neuter, 97 | Plural, 98 | Uncountable, 99 | } 100 | -------------------------------------------------------------------------------- /src/systems/inventory_system.rs: -------------------------------------------------------------------------------- 1 | use crate::components::{Energy, InBackpack, ItemIndex, Position}; 2 | use crate::messages::{WantsToDropMessage, WantsToPickupMessage}; 3 | use crate::queues::{WantsToDropQueue, WantsToPickupQueue}; 4 | use crate::resources::{OutputQueue, PlayerEntity, PlayerPosition}; 5 | use ::bracket_lib::prelude::YELLOW; 6 | use ::legion::systems::CommandBuffer; 7 | use ::legion::world::SubWorld; 8 | use ::legion::*; 9 | 10 | #[system] 11 | #[write_component(Energy)] 12 | pub(crate) fn drop( 13 | world: &mut SubWorld, 14 | cb: &mut CommandBuffer, 15 | #[resource] player_position: &PlayerPosition, 16 | #[resource] player_entity: &PlayerEntity, 17 | #[resource] wants_to_drop_queue: &mut WantsToDropQueue, 18 | #[resource] output: &OutputQueue, 19 | ) { 20 | let player_position = player_position.0; 21 | let player_entity = player_entity.0; 22 | 23 | for WantsToDropMessage { 24 | who: dropper_entity, 25 | item, 26 | } in wants_to_drop_queue.try_iter() 27 | { 28 | // TODO: Use Dropper's position. 29 | cb.add_component(item, Position(player_position)); 30 | cb.remove_component::(item); 31 | if dropper_entity == player_entity { 32 | output 33 | .the(dropper_entity) 34 | .v(dropper_entity, "drop") 35 | .the(item); 36 | } 37 | let mut who_entity = world.entry_mut(dropper_entity).unwrap(); 38 | who_entity.get_component_mut::().unwrap().energy = -50; 39 | } 40 | } 41 | 42 | #[system] 43 | #[write_component(Energy)] 44 | #[write_component(InBackpack)] 45 | #[write_component(ItemIndex)] 46 | pub(crate) fn pickup( 47 | world: &mut SubWorld, 48 | cb: &mut CommandBuffer, 49 | #[resource] player_entity: &PlayerEntity, 50 | #[resource] wants_to_pickup_queue: &mut WantsToPickupQueue, 51 | #[resource] output: &OutputQueue, 52 | ) { 53 | let player_entity = player_entity.0; 54 | 55 | for WantsToPickupMessage { 56 | who: who_entity, 57 | item: item_entity, 58 | } in wants_to_pickup_queue.try_iter() 59 | { 60 | if who_entity == player_entity { 61 | let mut possible_indexes = std::collections::HashSet::new(); 62 | for c in 0..52 { 63 | possible_indexes.insert(c); 64 | } 65 | for (item_idx, in_backpack) in <(&ItemIndex, &InBackpack)>::query().iter(world) { 66 | if in_backpack.owner == player_entity { 67 | possible_indexes.remove(&item_idx.index); 68 | } 69 | } 70 | let mut possible_indexes: Vec<_> = possible_indexes.drain().collect(); 71 | possible_indexes.sort_unstable(); 72 | 73 | let mut idx = 255_u8; 74 | let item_entry = world.entry_mut(item_entity).unwrap(); 75 | if let Ok(ItemIndex { index }) = item_entry.get_component::() { 76 | if possible_indexes.contains(index) { 77 | idx = *index; 78 | } 79 | } 80 | if idx == 255_u8 { 81 | if possible_indexes.is_empty() { 82 | output.s("Your backpack is full."); 83 | continue; 84 | } 85 | idx = possible_indexes[0]; 86 | cb.add_component(item_entity, ItemIndex { index: idx }); 87 | } 88 | output 89 | .the(who_entity) 90 | .v(who_entity, "pick") 91 | .s("up") 92 | .a(item_entity) 93 | .color(YELLOW) 94 | .string(format!(" ({})", crate::gui::index_to_letter(idx))); 95 | } else { 96 | output 97 | .the(who_entity) 98 | .v(who_entity, "pick") 99 | .s("up") 100 | .a(item_entity); 101 | } 102 | 103 | cb.remove_component::(item_entity); 104 | cb.add_component(item_entity, InBackpack { owner: who_entity }); 105 | 106 | let mut who_entity = world.entry_mut(who_entity).unwrap(); 107 | who_entity.get_component_mut::().unwrap().energy = -90; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/resources/mod.rs: -------------------------------------------------------------------------------- 1 | mod camera; 2 | mod gamelog; 3 | mod map; 4 | 5 | pub(crate) use camera::*; 6 | pub(crate) use gamelog::*; 7 | pub(crate) use map::*; 8 | 9 | use crate::ecs::*; 10 | 11 | use ::bracket_lib::prelude::RandomNumberGenerator; 12 | use ::bracket_lib::prelude::RED; 13 | use ::legion::Entity; 14 | use ::serde::*; 15 | use ::std::collections::VecDeque; 16 | use ::std::io::Read; 17 | use ::std::io::Write; 18 | use ::std::sync::Mutex; 19 | 20 | use crate::components::Position; 21 | use crate::positions::{Direction, MapPosition}; 22 | 23 | #[derive(Serialize, Deserialize)] 24 | pub(crate) struct PlayerEntity(pub Entity); 25 | 26 | #[derive(PartialEq, Debug, Copy, Clone, Serialize, Deserialize)] 27 | pub(crate) enum PlayerTarget { 28 | None, 29 | Position(MapPosition), 30 | Dir(Direction), 31 | } 32 | 33 | #[derive(Debug, Copy, Clone, Serialize, Deserialize)] 34 | pub(crate) struct PlayerPosition(pub MapPosition); 35 | 36 | impl From for Position { 37 | fn from(pos: PlayerPosition) -> Self { 38 | Self(pos.0) 39 | } 40 | } 41 | 42 | #[derive(Debug, Default, Copy, Clone)] 43 | pub(crate) struct Time { 44 | pub real_time_ms: i64, 45 | pub last_real_time_ms: i64, 46 | pub tick: i64, 47 | } 48 | 49 | type Result = std::result::Result>; 50 | 51 | pub(crate) fn new(ecs: &mut Ecs) { 52 | ecs.resources.insert(PlayerTarget::None); 53 | 54 | let map = Map::new_map_rooms_and_corridors(); 55 | let player_pos = map.rooms[0].center(); 56 | 57 | ecs.resources.insert(RandomNumberGenerator::new()); 58 | ecs.resources.insert(GameLog::new()); 59 | 60 | for room in map.rooms.iter().skip(1) { 61 | crate::spawner::spawn_room(ecs, room); 62 | } 63 | let player_entity = crate::spawner::player(ecs, player_pos.x, player_pos.y); 64 | 65 | let output_queue = OutputQueue::new(Mutex::new(VecDeque::new()), player_entity); 66 | output_queue.s("Welcome to ").color(RED).s("Rouge"); 67 | ecs.resources.insert(output_queue); 68 | 69 | let player_pos = PlayerPosition(MapPosition { 70 | x: player_pos.x, 71 | y: player_pos.y, 72 | }); 73 | { 74 | let mut camera = resource_get_mut!(ecs, Camera); 75 | camera.center(player_pos); 76 | } 77 | 78 | ecs.resources.insert(map); 79 | ecs.resources.insert(player_pos); 80 | ecs.resources.insert(PlayerEntity(player_entity)); 81 | crate::queues::register_queues(&mut ecs.resources); 82 | } 83 | 84 | fn save_resource(ecs: &Ecs, writer: &mut dyn Write) -> Result<()> { 85 | let obj = &*resource_get!(ecs, T); 86 | let data = bincode::serialize(&obj)?; 87 | writer.write_all(&data.len().to_le_bytes())?; 88 | writer.write_all(&data)?; 89 | 90 | Ok(()) 91 | } 92 | 93 | pub(crate) fn save(ecs: &Ecs, writer: &mut dyn Write) -> Result<()> { 94 | save_resource::(ecs, writer)?; 95 | save_resource::(ecs, writer)?; 96 | save_resource::(ecs, writer)?; 97 | save_resource::(ecs, writer)?; 98 | // save_resource::<'static, OutputQueue>(ecs, writer)?; 99 | save_resource::(ecs, writer)?; 100 | save_resource::(ecs, writer)?; 101 | // save_resource::(ecs, writer)?; 102 | 103 | // crate::queues::register_queues(&mut ecs.resources); 104 | 105 | Ok(()) 106 | } 107 | 108 | fn load_resource<'de, T: 'static + Deserialize<'de>>( 109 | ecs: &mut Ecs, 110 | reader: &mut dyn Read, 111 | ) -> Result<()> { 112 | let mut data = [0_u8; 8]; 113 | reader.read_exact(&mut data)?; 114 | let len = usize::from_le_bytes(data); 115 | let mut data = Box::new(vec![0_u8; len]); 116 | reader.read_exact(&mut data)?; 117 | dbg!("Loading resource "); 118 | let obj = bincode::deserialize::(data.leak())?; 119 | 120 | dbg!("Loaded resource "); 121 | 122 | ecs.resources.insert::(obj); 123 | 124 | Ok(()) 125 | } 126 | 127 | pub(crate) fn load(ecs: &mut Ecs, reader: &mut dyn Read) -> Result<()> { 128 | load_resource::(ecs, reader)?; 129 | load_resource::(ecs, reader)?; 130 | load_resource::(ecs, reader)?; 131 | load_resource::(ecs, reader)?; 132 | load_resource::(ecs, reader)?; 133 | load_resource::(ecs, reader)?; 134 | 135 | Ok(()) 136 | } 137 | -------------------------------------------------------------------------------- /langgen_english/src/output_queue/output_builder.rs: -------------------------------------------------------------------------------- 1 | use super::{FragmentEntry, PhantomData, QueueAdapter}; 2 | 3 | #[allow(missing_docs)] 4 | /// `OutputBuilder` helps output queue building whole sentences. 5 | /// 6 | /// This struct has a subset of [`OutputQueue`](crate::OutputQueue)'s functions 7 | /// and they are described there. 8 | pub struct OutputBuilder<'a, QA, Entity> 9 | where 10 | QA: QueueAdapter, 11 | { 12 | queue_adapter: &'a QA, 13 | _lock: std::sync::LockResult>, 14 | _entity: PhantomData, 15 | } 16 | 17 | #[allow(missing_docs)] 18 | impl<'a, Entity, QA> OutputBuilder<'a, QA, Entity> 19 | where 20 | QA: QueueAdapter, 21 | { 22 | pub(crate) fn new(queue_adapter: &'a QA, lock: std::sync::LockResult>) -> Self { 23 | Self { 24 | queue_adapter, 25 | _lock: lock, 26 | _entity: PhantomData, 27 | } 28 | } 29 | 30 | fn push_fragment(self, frag: crate::Fragment) -> Self { 31 | self.queue_adapter.push(FragmentEntry::(frag)); 32 | self 33 | } 34 | 35 | pub fn a(self, obj: Entity) -> Self { 36 | self.push_fragment(crate::Fragment::A(obj)) 37 | } 38 | 39 | pub fn a_(self, obj: Entity) -> Self { 40 | self.push_fragment(crate::Fragment::A_(obj)) 41 | } 42 | 43 | pub fn the(self, obj: Entity) -> Self { 44 | self.push_fragment(crate::Fragment::The(obj)) 45 | } 46 | 47 | pub fn the_(self, obj: Entity) -> Self { 48 | self.push_fragment(crate::Fragment::The_(obj)) 49 | } 50 | 51 | pub fn thes(self, obj: Entity) -> Self { 52 | self.push_fragment(crate::Fragment::Thes(obj)) 53 | } 54 | 55 | pub fn thes_(self, obj: Entity) -> Self { 56 | self.push_fragment(crate::Fragment::Thes_(obj)) 57 | } 58 | 59 | pub fn thess(self, obj: Entity) -> Self { 60 | self.push_fragment(crate::Fragment::Thess(obj)) 61 | } 62 | 63 | pub fn thess_(self, obj: Entity) -> Self { 64 | self.push_fragment(crate::Fragment::Thess_(obj)) 65 | } 66 | 67 | pub fn my(self, who: Entity, obj: Entity) -> Self { 68 | self.push_fragment(crate::Fragment::My(who, obj)) 69 | } 70 | 71 | pub fn my_(self, who: Entity, obj: Entity) -> Self { 72 | self.push_fragment(crate::Fragment::My_(who, obj)) 73 | } 74 | 75 | pub fn word(self, who: Entity) -> Self { 76 | self.push_fragment(crate::Fragment::Word(who)) 77 | } 78 | 79 | pub fn word_(self, who: Entity) -> Self { 80 | self.push_fragment(crate::Fragment::Word_(who)) 81 | } 82 | 83 | pub fn is(self, who: Entity) -> Self { 84 | self.push_fragment(crate::Fragment::Is(who)) 85 | } 86 | 87 | pub fn has(self, who: Entity) -> Self { 88 | self.push_fragment(crate::Fragment::Has(who)) 89 | } 90 | 91 | pub fn s(self, s: &'static str) -> Self { 92 | self.push_fragment(crate::Fragment::TextRef(s)) 93 | } 94 | 95 | pub fn string(self, s: String) -> Self { 96 | self.push_fragment(crate::Fragment::Text(s)) 97 | } 98 | 99 | pub fn v(self, who: Entity, verb: &'static str) -> Self { 100 | self.push_fragment(crate::Fragment::VerbRef(who, verb)) 101 | } 102 | 103 | pub fn verb(self, who: Entity, verb: String) -> Self { 104 | self.push_fragment(crate::Fragment::VerbString(who, verb)) 105 | } 106 | 107 | pub fn supress_space(self) -> Self { 108 | self.push_fragment(crate::Fragment::SupressSpace(true)) 109 | } 110 | 111 | pub fn supress_capitalize(self) -> Self { 112 | self.push_fragment(crate::Fragment::Capitalize(false)) 113 | } 114 | 115 | pub fn capitalize(self) -> Self { 116 | self.push_fragment(crate::Fragment::Capitalize(true)) 117 | } 118 | 119 | pub fn supress_dot(self) -> Self { 120 | self.push_fragment(crate::Fragment::SupressDot(true)) 121 | } 122 | 123 | pub fn color(self, color: (u8, u8, u8)) -> Self { 124 | self.push_fragment(crate::Fragment::Color(color)) 125 | } 126 | } 127 | 128 | /// Drop implementation to send the end of line message. 129 | impl Drop for OutputBuilder<'_, QA, Entity> 130 | where 131 | QA: QueueAdapter, 132 | { 133 | fn drop(&mut self) { 134 | self.queue_adapter 135 | .push(FragmentEntry::(crate::Fragment::EndOfLine)); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /src/positions.rs: -------------------------------------------------------------------------------- 1 | use crate::resources::PlayerPosition; 2 | use ::bracket_lib::prelude::Point; 3 | use ::legion_typeuuid::*; 4 | use ::serde::*; 5 | use ::type_uuid::*; 6 | 7 | #[derive(Serialize, Deserialize, PartialEq, Debug, Copy, Clone, TypeUuid)] 8 | #[uuid = "042e6d67-a9dc-47da-89e8-3151a8f96606"] 9 | pub(crate) struct MapPosition { 10 | pub x: i32, 11 | pub y: i32, 12 | } 13 | register_serialize!(MapPosition); 14 | 15 | impl From for Point { 16 | fn from(pos: MapPosition) -> Self { 17 | Point::new(pos.x, pos.y) 18 | } 19 | } 20 | 21 | impl From for MapPosition { 22 | fn from(pos: PlayerPosition) -> Self { 23 | pos.0 24 | } 25 | } 26 | 27 | impl std::ops::Add<(i32, i32)> for MapPosition { 28 | type Output = MapPosition; 29 | 30 | fn add(self, rhs: (i32, i32)) -> Self::Output { 31 | MapPosition { 32 | x: self.x + rhs.0, 33 | y: self.y + rhs.1, 34 | } 35 | } 36 | } 37 | 38 | impl std::ops::Add for MapPosition { 39 | type Output = MapPosition; 40 | 41 | fn add(self, rhs: Point) -> Self::Output { 42 | MapPosition { 43 | x: self.x + rhs.x, 44 | y: self.y + rhs.y, 45 | } 46 | } 47 | } 48 | 49 | impl std::ops::Sub for MapPosition { 50 | type Output = Point; 51 | 52 | fn sub(self, rhs: MapPosition) -> Self::Output { 53 | Point::new(self.x - rhs.x, self.y - rhs.y) 54 | } 55 | } 56 | 57 | #[derive(Serialize, Deserialize, PartialEq, Debug, Copy, Clone, TypeUuid)] 58 | #[uuid = "ec3131b4-ee4d-4536-8b07-a4384aa6a9bc"] 59 | pub(crate) struct ScreenPosition { 60 | pub x: i32, 61 | pub y: i32, 62 | } 63 | register_serialize!(ScreenPosition); 64 | 65 | impl From for Point { 66 | fn from(pos: ScreenPosition) -> Point { 67 | Point::new(pos.x, pos.y) 68 | } 69 | } 70 | 71 | impl From for (i32, i32) { 72 | fn from(pos: ScreenPosition) -> Self { 73 | (pos.x, pos.y) 74 | } 75 | } 76 | 77 | impl From for (usize, usize) { 78 | fn from(pos: ScreenPosition) -> (usize, usize) { 79 | let x = if pos.x > 0 { pos.x as usize } else { 0 }; 80 | let y = if pos.y > 0 { pos.y as usize } else { 0 }; 81 | (x, y) 82 | } 83 | } 84 | 85 | impl From for ScreenPosition { 86 | fn from(pos: Point) -> Self { 87 | Self { x: pos.x, y: pos.y } 88 | } 89 | } 90 | 91 | #[derive(PartialEq, Debug, Copy, Clone, Serialize, Deserialize)] 92 | pub(crate) enum Direction { 93 | West = 1, 94 | East = 2, 95 | South = 4, 96 | SouthWest = 5, 97 | SouthEast = 6, 98 | North = 8, 99 | NorthWest = 9, 100 | NorthEast = 10, 101 | } 102 | 103 | impl Direction { 104 | pub(crate) fn iter() -> impl Iterator { 105 | use Direction::*; 106 | [ 107 | North, NorthEast, East, SouthEast, South, SouthWest, West, NorthWest, 108 | ] 109 | .iter() 110 | } 111 | } 112 | 113 | fn dir_to_dx_dy(dir: Direction) -> (i32, i32) { 114 | match dir { 115 | Direction::West => (-1, 0), 116 | Direction::East => (1, 0), 117 | Direction::South => (0, 1), 118 | Direction::SouthWest => (-1, 1), 119 | Direction::SouthEast => (1, 1), 120 | Direction::North => (0, -1), 121 | Direction::NorthWest => (-1, -1), 122 | Direction::NorthEast => (1, -1), 123 | } 124 | } 125 | 126 | impl From<(i32, i32)> for Direction { 127 | fn from(coord: (i32, i32)) -> Self { 128 | match coord { 129 | (-1, 0) => Direction::West, 130 | (1, 0) => Direction::East, 131 | (0, 1) => Direction::South, 132 | (-1, 1) => Direction::SouthWest, 133 | (1, 1) => Direction::SouthEast, 134 | (0, -1) => Direction::North, 135 | (-1, -1) => Direction::NorthWest, 136 | (1, -1) => Direction::NorthEast, 137 | _ => panic!("Incorrect direction"), 138 | } 139 | } 140 | } 141 | 142 | impl From for (i32, i32) { 143 | fn from(dir: Direction) -> Self { 144 | dir_to_dx_dy(dir) 145 | } 146 | } 147 | 148 | impl From for Point { 149 | fn from(dir: Direction) -> Self { 150 | dir_to_dx_dy(dir).into() 151 | } 152 | } 153 | 154 | impl std::ops::Add for Point { 155 | type Output = Point; 156 | 157 | fn add(self, rhs: Direction) -> Self::Output { 158 | let rhs: Point = rhs.into(); 159 | self + rhs 160 | } 161 | } 162 | 163 | impl std::ops::Add for MapPosition { 164 | type Output = MapPosition; 165 | 166 | fn add(self, rhs: Direction) -> Self::Output { 167 | let rhs: Point = rhs.into(); 168 | self + rhs 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /src/components.rs: -------------------------------------------------------------------------------- 1 | use crate::MapPosition; 2 | use ::bracket_lib::prelude::RGB; 3 | use ::legion::Entity; 4 | use ::legion_typeuuid::*; 5 | use ::serde::*; 6 | use ::type_uuid::*; 7 | 8 | #[derive(Serialize, Deserialize, Clone, Debug, TypeUuid)] 9 | #[uuid = "0ba9a288-a1a7-45b5-8964-44cbc0a8b953"] 10 | pub(crate) struct AreaOfEffect { 11 | pub radius: i32, 12 | } 13 | register_serialize!(AreaOfEffect); 14 | 15 | #[derive(Serialize, Deserialize, Clone, Debug, TypeUuid)] 16 | #[uuid = "b7e17796-b15d-4498-b3b0-4eeb79af3878"] 17 | pub(crate) struct BlocksTile {} 18 | register_serialize!(BlocksTile); 19 | 20 | #[derive(Serialize, Deserialize, Clone, Debug, TypeUuid)] 21 | #[uuid = "7b5aa67d-1cff-49f6-bdab-6f446f9d22a1"] 22 | pub(crate) struct CombatStats { 23 | pub max_hp: i32, 24 | pub hp: i32, 25 | pub defense: i32, 26 | pub power: i32, 27 | } 28 | register_serialize!(CombatStats); 29 | 30 | #[derive(Serialize, Deserialize, Clone, Debug, TypeUuid)] 31 | #[uuid = "f149f629-12cd-4a04-a158-ad4fbfd221d7"] 32 | pub(crate) struct Consumable {} 33 | register_serialize!(Consumable); 34 | 35 | /// The object is removed at the given tick. 36 | #[derive(Serialize, Deserialize, Clone, Debug, TypeUuid)] 37 | #[uuid = "3993ee01-ce19-4a06-aa23-b0b500d61d18"] 38 | pub(crate) struct EndTick { 39 | pub end_tick: i64, 40 | } 41 | register_serialize!(EndTick); 42 | 43 | /// The object is removed at the given time. 44 | #[derive(Serialize, Deserialize, Clone, Debug, TypeUuid)] 45 | #[uuid = "9fe4c623-7dcd-45f1-bd63-16254360c5ec"] 46 | pub(crate) struct EndTime { 47 | pub end_time_ms: i64, 48 | } 49 | register_serialize!(EndTime); 50 | 51 | /// Animated objects need energy to perform actions. 52 | /// The more an action cost, the more energy it drains. 53 | /// Energy >= 0 means the object can act, the new energy becomes -action_cost. 54 | /// If the player has energy >= 0, it makes a turn. 55 | /// Then monster with the highest energy go first. If it can't do anything, it will have more energy 56 | /// next time. 57 | #[derive(Serialize, Deserialize, Clone, Debug, TypeUuid)] 58 | #[uuid = "9225dc28-62ff-4e46-be43-76436da77561"] 59 | pub(crate) struct Energy { 60 | pub energy: i32, 61 | } 62 | register_serialize!(Energy); 63 | 64 | #[derive(Serialize, Deserialize, Clone, Debug, TypeUuid)] 65 | #[uuid = "9ea2eda5-8e86-48ca-a831-8044fe7f4064"] 66 | pub(crate) struct HealthProvider { 67 | pub heal_amount: i32, 68 | } 69 | register_serialize!(HealthProvider); 70 | 71 | #[derive(Serialize, Deserialize, Debug, Clone, TypeUuid)] 72 | #[uuid = "6f3fedb4-3dd9-4a2d-a2a6-51149b614254"] 73 | pub(crate) struct InBackpack { 74 | pub owner: Entity, 75 | } 76 | register_serialize!(InBackpack); 77 | 78 | #[derive(Serialize, Deserialize, Clone, Debug, TypeUuid)] 79 | #[uuid = "0d38045c-4cb0-46f6-aec3-92c478e4a6db"] 80 | pub(crate) struct InflictsDamage { 81 | pub damage: i32, 82 | } 83 | register_serialize!(InflictsDamage); 84 | 85 | #[derive(Serialize, Deserialize, Clone, Debug, TypeUuid)] 86 | #[uuid = "3fe6f537-42ab-4ea7-868b-06dd465ec123"] 87 | pub(crate) struct Item {} 88 | register_serialize!(Item); 89 | 90 | #[derive(Serialize, Deserialize, Debug, Clone, TypeUuid)] 91 | #[uuid = "e34d9ba1-6289-4c1c-95fb-0075ee34fa09"] 92 | pub(crate) struct ItemIndex { 93 | pub index: u8, 94 | } 95 | register_serialize!(ItemIndex); 96 | 97 | #[derive(Serialize, Deserialize, Clone, Debug, TypeUuid)] 98 | #[uuid = "974bf33c-2dd4-4317-9747-680e4ecefb54"] 99 | pub(crate) struct Monster {} 100 | register_serialize!(Monster); 101 | 102 | #[derive(Serialize, Deserialize, Clone, Debug, TypeUuid)] 103 | #[uuid = "d866e77f-91de-4917-a65d-c16d8b858543"] 104 | pub(crate) struct Name { 105 | pub name: String, 106 | pub proper_name: bool, 107 | } 108 | register_serialize!(Name); 109 | 110 | #[derive(Serialize, Deserialize, Clone, Debug, TypeUuid)] 111 | #[uuid = "c186ed8d-325b-4adc-a5de-2ae2a6f0ce25"] 112 | pub(crate) struct Player {} 113 | register_serialize!(Player); 114 | 115 | #[derive(Serialize, Deserialize, PartialEq, Copy, Clone, Debug, TypeUuid)] 116 | #[uuid = "7a11cab0-db87-48b0-acfc-74056cd9a625"] 117 | pub(crate) struct Position(pub MapPosition); 118 | register_serialize!(Position); 119 | 120 | impl From for Position { 121 | fn from(pos: MapPosition) -> Self { 122 | Position(pos) 123 | } 124 | } 125 | 126 | #[derive(Serialize, Deserialize, Clone, Debug, TypeUuid)] 127 | #[uuid = "6d29666a-c126-44d9-a90d-864890f804ee"] 128 | pub(crate) struct Ranged { 129 | pub range: i32, 130 | } 131 | register_serialize!(Ranged); 132 | 133 | #[derive(Serialize, Deserialize, Clone, TypeUuid)] 134 | #[uuid = "6315dfee-74b9-42f4-91dc-145b17723c2e"] 135 | pub(crate) struct Renderable { 136 | pub glyph: u16, 137 | pub fg: RGB, 138 | pub bg: RGB, 139 | pub render_order: i32, 140 | } 141 | register_serialize!(Renderable); 142 | 143 | #[derive(Serialize, Deserialize, Clone, TypeUuid)] 144 | #[uuid = "92d745b2-217a-426f-b6e4-2b0c2811fcd9"] 145 | pub(crate) struct Viewshed { 146 | pub visible_tiles: Vec, 147 | pub range: i32, 148 | pub dirty: bool, 149 | } 150 | register_serialize!(Viewshed); 151 | -------------------------------------------------------------------------------- /src/systems/consume_system.rs: -------------------------------------------------------------------------------- 1 | use crate::components::*; 2 | use crate::messages::{ReceiveHealthMessage, RemoveItemMessage, SufferDamageMessage}; 3 | use crate::queues::{ReceiveHealthQueue, RemoveItemQueue, SufferDamageQueue, WantsToUseQueue}; 4 | use crate::resources::{Camera, Map, OutputQueue}; 5 | use crate::PlayerEntity; 6 | use crate::ScreenPosition; 7 | use legion::*; 8 | 9 | #[allow(clippy::too_many_arguments)] 10 | #[system] 11 | #[read_component(HealthProvider)] 12 | #[read_component(InflictsDamage)] 13 | #[read_component(Item)] 14 | #[read_component(AreaOfEffect)] 15 | pub(crate) fn consume( 16 | world: &legion::world::SubWorld, 17 | #[resource] receive_health_queue: &ReceiveHealthQueue, 18 | #[resource] remove_item_queue: &RemoveItemQueue, 19 | #[resource] suffer_damage_queue: &SufferDamageQueue, 20 | #[resource] wants_to_use_queue: &mut WantsToUseQueue, 21 | #[resource] player_entity: &PlayerEntity, 22 | #[resource] output: &OutputQueue, 23 | #[resource] camera: &Camera, 24 | #[resource] map: &Map, 25 | ) { 26 | for (user_entity, wants_to_use_item, wants_to_use_target) in wants_to_use_queue 27 | .try_iter() 28 | .map(|msg| (msg.who, msg.item, msg.target)) 29 | { 30 | let item_entry = world.entry_ref(wants_to_use_item); 31 | 32 | match item_entry { Ok(item_entry) => { 33 | output 34 | .the(user_entity) 35 | .v(user_entity, "consume") 36 | .the(wants_to_use_item); 37 | 38 | let mut targets: Vec = Vec::new(); 39 | match wants_to_use_target { 40 | None => { 41 | targets.push(player_entity.0); 42 | } 43 | Some(target) => { 44 | let area_effect = item_entry.get_component::(); 45 | if let Ok(area_effect) = area_effect { 46 | // AoE 47 | let screen_point = camera.transform_map_pos(target).into(); 48 | for tile_point in bracket_lib::prelude::field_of_view( 49 | screen_point, 50 | area_effect.radius, 51 | map, 52 | ) 53 | .iter() 54 | .filter_map(|p| { 55 | if p.x >= 0 && p.x < camera.width() && p.y >= 0 && p.y < camera.height() 56 | { 57 | Some(ScreenPosition { x: p.x, y: p.y }) 58 | } else { 59 | None 60 | } 61 | }) { 62 | let idx = map.map_pos_to_idx(camera.transform_screen_pos(tile_point)); 63 | for mob in &map.tile_content[idx] { 64 | targets.push(*mob); 65 | } 66 | } 67 | } else { 68 | // Single target in tile 69 | let idx = map.map_pos_to_idx(target); 70 | for mob in &map.tile_content[idx] { 71 | targets.push(*mob); 72 | } 73 | } 74 | } 75 | } 76 | let heal_amount: Option<_> = { 77 | match item_entry.get_component::() { Ok(health) => { 78 | Some(health.heal_amount) 79 | } _ => { 80 | None 81 | }} 82 | }; 83 | if let Some(heal_amount) = heal_amount { 84 | for target in targets { 85 | if target == player_entity.0 { 86 | output.s("You feel better."); 87 | } else { 88 | output.the(target).v(target, "feel").s("better"); 89 | } 90 | 91 | receive_health_queue.send(ReceiveHealthMessage { 92 | target, 93 | amount: heal_amount, 94 | }); 95 | } 96 | } else { 97 | let item_damage: Option<_> = { 98 | match item_entry.get_component::() { Ok(damage) => { 99 | Some(damage.damage) 100 | } _ => { 101 | None 102 | }} 103 | }; 104 | if let Some(item_damage) = item_damage { 105 | for target in targets { 106 | output 107 | .the(target) 108 | .v(target, "lose") 109 | .string(format!("{item_damage} hp")); 110 | suffer_damage_queue.send(SufferDamageMessage { 111 | target, 112 | amount: item_damage, 113 | }); 114 | } 115 | } 116 | } 117 | remove_item_queue.send(RemoveItemMessage { 118 | target: wants_to_use_item, 119 | }); 120 | } _ => if user_entity == player_entity.0 { 121 | output.s("You cannot use").the(wants_to_use_item); 122 | }} 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | bracket_lib::prelude::add_wasm_support!(); 2 | 3 | #[macro_use] 4 | mod ecs; 5 | 6 | mod components; 7 | mod entity_adapter; 8 | mod gui; 9 | mod messages; 10 | mod player; 11 | mod positions; 12 | mod queues; 13 | mod resources; 14 | mod scenes; 15 | mod spawner; 16 | mod systems; 17 | 18 | use crate::components::Player; 19 | use crate::positions::{Direction, MapPosition, ScreenPosition}; 20 | use crate::resources::OutputQueue; 21 | use crate::resources::{Camera, GameLog, PlayerEntity}; 22 | use ::bracket_lib::prelude::*; 23 | use ::legion::Entity; 24 | use ::legion_typeuuid::collect_registry; 25 | use bincode::Options; 26 | use legion::IntoQuery; 27 | use legion_typeuuid::SerializableTypeUuid; 28 | use std::collections::VecDeque; 29 | use std::io::Read; 30 | use std::io::Write; 31 | use std::sync::Mutex; 32 | 33 | type Result = std::result::Result>; 34 | 35 | #[derive(Debug, PartialEq, Copy, Clone)] 36 | pub(crate) enum InventoryType { 37 | Apply, 38 | Drop, 39 | } 40 | 41 | #[derive(Debug, PartialEq, Copy, Clone)] 42 | pub(crate) enum RunState { 43 | AwaitingInput, 44 | ReallyQuit, 45 | PreRun, 46 | Tick, 47 | EnergylessTick, 48 | ShowInventory(InventoryType), 49 | ShowTargeting(gui::TargetingInfo, Entity), 50 | SaveGame, 51 | } 52 | 53 | struct OuterState { 54 | state: State, 55 | scene_manager: scenes::SceneManager, 56 | } 57 | 58 | pub(crate) struct State { 59 | ecs: ecs::Ecs, 60 | registry: legion::Registry, 61 | old_shift: bool, 62 | } 63 | 64 | impl GameState for OuterState { 65 | fn tick(&mut self, ctx: &mut BTerm) { 66 | { 67 | let mut time = self 68 | .state 69 | .ecs 70 | .resources 71 | .get_mut_or_default::(); 72 | time.last_real_time_ms = time.real_time_ms; 73 | time.real_time_ms += ctx.frame_time_ms as i64; 74 | } 75 | 76 | { 77 | let mut input = INPUT.lock(); 78 | 79 | ctx.shift = input.key_pressed_set().contains(&VirtualKeyCode::LShift) 80 | || input.key_pressed_set().contains(&VirtualKeyCode::RShift); 81 | if !ctx.shift && self.state.old_shift != ctx.shift && ctx.key.is_none() { 82 | ctx.key = Some(VirtualKeyCode::LShift); 83 | } 84 | self.state.old_shift = ctx.shift; 85 | 86 | let ctrl = input.key_pressed_set().contains(&VirtualKeyCode::LControl) 87 | || input.key_pressed_set().contains(&VirtualKeyCode::RControl); 88 | 89 | if let Some(VirtualKeyCode::P) = ctx.key { 90 | if ctrl { 91 | ctx.screenshot("screenshot.png"); 92 | let mut gamelog = resource_get_mut!(self.state.ecs, GameLog); 93 | gamelog.set_color(GREEN); 94 | gamelog.write_text("Screenshot taken."); 95 | gamelog.end_of_line(); 96 | } 97 | } 98 | 99 | #[allow(clippy::single_match)] 100 | input.for_each_message(|event| match event { 101 | BEvent::CloseRequested => ctx.quitting = true, 102 | _ => (), 103 | }); 104 | } 105 | 106 | self.scene_manager.tick(&mut self.state, ctx); 107 | } 108 | } 109 | 110 | impl State {} 111 | 112 | const LAYERS: usize = 7; 113 | const SCREEN_WIDTH: i32 = 80; 114 | const SCREEN_HEIGHT: i32 = 50; 115 | 116 | fn main() -> Result<()> { 117 | let mut builder = BTermBuilder::simple(SCREEN_WIDTH, SCREEN_HEIGHT)? 118 | .with_title("Rouge World") 119 | .with_font("terminal8x8.png", 8, 8) 120 | .with_advanced_input(true) 121 | .with_resource_path("resources") 122 | .with_vsync(true); 123 | // Add layers for walls. 124 | for _i in 0..LAYERS - 1 { 125 | builder = builder.with_sparse_console_no_bg(SCREEN_WIDTH, SCREEN_HEIGHT, "terminal8x8.png"); 126 | } 127 | // Layer for GUI: 128 | builder = builder.with_sparse_console(SCREEN_WIDTH, SCREEN_HEIGHT, "terminal8x8.png"); 129 | let mut context = builder.build()?; 130 | context.set_active_console(LAYERS); 131 | 132 | context.with_post_scanlines(true); 133 | 134 | let mut gs = OuterState { 135 | state: State { 136 | ecs: ecs::Ecs::new(), 137 | registry: collect_registry(), 138 | old_shift: false, 139 | }, 140 | scene_manager: scenes::SceneManager::new(), 141 | }; 142 | 143 | gs.state 144 | .ecs 145 | .resources 146 | .insert(Camera::new(SCREEN_WIDTH, SCREEN_HEIGHT - 7)); 147 | 148 | gs.scene_manager 149 | .push(Box::new(scenes::MainMenuScene::new())); 150 | 151 | main_loop(context, gs)?; 152 | Ok(()) 153 | } 154 | 155 | fn bincode_options() -> bincode::DefaultOptions { 156 | bincode::DefaultOptions::default() 157 | } 158 | 159 | pub(crate) fn new(ecs: &mut ecs::Ecs) { 160 | resources::new(ecs); 161 | } 162 | 163 | pub(crate) fn save(gs: &State, writer: &mut dyn Write) -> Result<()> { 164 | resources::save(&gs.ecs, writer)?; 165 | 166 | let entity_serializer = legion::serialize::Canon::default(); 167 | 168 | let serializable = 169 | gs.ecs 170 | .world 171 | .as_serializable(legion::query::any(), &gs.registry, &entity_serializer); 172 | // let encoder = flate2::write::GzEncoder::new(writer, flate2::Compression::fast()); 173 | bincode_options().serialize_into(writer, &serializable)?; 174 | 175 | Ok(()) 176 | } 177 | 178 | pub(crate) fn load(ecs: &mut ecs::Ecs, reader: &mut dyn Read) -> Result<()> { 179 | // let mut decoder = flate2::read::GzDecoder::new(reader); 180 | 181 | resources::load(ecs, reader)?; 182 | queues::register_queues(&mut ecs.resources); 183 | 184 | let mut deser = bincode::Deserializer::with_reader(reader, bincode_options()); 185 | let registry = collect_registry(); 186 | use serde::de::DeserializeSeed; 187 | let entity_serializer = legion::serialize::Canon::default(); 188 | let world = registry 189 | .as_deserialize(&entity_serializer) 190 | .deserialize(&mut deser) 191 | .unwrap(); 192 | ecs.world = world; 193 | 194 | let mut query = <(Entity, &Player)>::query(); 195 | 196 | let (entity, _player) = query.iter(&ecs.world).next().expect("Player"); 197 | 198 | let output_queue = OutputQueue::new(Mutex::new(VecDeque::new()), *entity); 199 | output_queue.s("Welcome back."); 200 | ecs.resources.insert(output_queue); 201 | 202 | ecs.resources.insert(PlayerEntity(*entity)); 203 | 204 | dbg!("All Loaded"); 205 | 206 | Ok(()) 207 | } 208 | -------------------------------------------------------------------------------- /src/spawner.rs: -------------------------------------------------------------------------------- 1 | use crate::components::*; 2 | use crate::ecs::Ecs; 3 | use crate::resources::MAP_WIDTH; 4 | use crate::MapPosition; 5 | use bracket_lib::prelude::*; 6 | use legion::*; 7 | 8 | pub(crate) const MAX_MONSTERS: i32 = 3; 9 | pub(crate) const MAX_ITEMS: i32 = 4; 10 | 11 | pub(crate) fn player(ecs: &mut Ecs, player_x: i32, player_y: i32) -> Entity { 12 | ecs.world.push(( 13 | Energy { energy: 0 }, 14 | Position(MapPosition { 15 | x: player_x, 16 | y: player_y, 17 | }), 18 | Renderable { 19 | glyph: to_cp437('@'), 20 | fg: RGB::named(YELLOW), 21 | bg: RGB::named(BLACK), 22 | render_order: 0, 23 | }, 24 | Player {}, 25 | Viewshed { 26 | visible_tiles: Vec::new(), 27 | range: 8, 28 | dirty: true, 29 | }, 30 | Name { 31 | name: "player".to_string(), 32 | proper_name: false, 33 | }, 34 | CombatStats { 35 | hp: 30, 36 | max_hp: 30, 37 | power: 5, 38 | defense: 2, 39 | }, 40 | )) 41 | } 42 | 43 | /// Spawns a random monster at a given location 44 | pub(crate) fn random_monster(ecs: &mut Ecs, x: i32, y: i32) { 45 | let roll: i32; 46 | { 47 | let mut rng = resource_get_mut!(ecs, RandomNumberGenerator); 48 | roll = rng.roll_dice(1, 2); 49 | } 50 | match roll { 51 | 1 => lamotte(ecs, x, y), 52 | _ => janouch(ecs, x, y), 53 | } 54 | } 55 | 56 | fn lamotte(ecs: &mut Ecs, x: i32, y: i32) { 57 | monster(ecs, x, y, to_cp437('l'), "Lamotte"); 58 | } 59 | fn janouch(ecs: &mut Ecs, x: i32, y: i32) { 60 | monster(ecs, x, y, to_cp437('j'), "Janouch"); 61 | } 62 | 63 | fn monster(ecs: &mut Ecs, x: i32, y: i32, glyph: u16, name: S) { 64 | ecs.world.push(( 65 | Energy { energy: 0 }, 66 | Position(MapPosition { x, y }), 67 | Renderable { 68 | glyph, 69 | fg: RGB::named(RED), 70 | bg: RGB::named(BLACK), 71 | render_order: 1, 72 | }, 73 | Viewshed { 74 | visible_tiles: Vec::new(), 75 | range: 8, 76 | dirty: true, 77 | }, 78 | Monster {}, 79 | Name { 80 | name: name.to_string(), 81 | proper_name: true, 82 | }, 83 | BlocksTile {}, 84 | CombatStats { 85 | max_hp: 16, 86 | hp: 16, 87 | defense: 1, 88 | power: 4, 89 | }, 90 | )); 91 | } 92 | 93 | /// Spawns a random monster at a given location 94 | pub(crate) fn random_item(ecs: &mut Ecs, x: i32, y: i32) { 95 | let roll = { 96 | let mut rng = resource_get_mut!(ecs, RandomNumberGenerator); 97 | rng.roll_dice(1, 5) 98 | }; 99 | match roll { 100 | 1 => health_potion(ecs, x, y), 101 | 2 => magic_missile_scroll(ecs, x, y), 102 | 3 => fireball_scroll(ecs, x, y), 103 | 4 => apple(ecs, x, y), 104 | _ => ball(ecs, x, y), 105 | } 106 | } 107 | 108 | fn health_potion(ecs: &mut Ecs, x: i32, y: i32) { 109 | ecs.world.push(( 110 | Position(MapPosition { x, y }), 111 | Renderable { 112 | glyph: to_cp437('¡'), 113 | fg: RGB::named(MAGENTA), 114 | bg: RGB::named(BLACK), 115 | render_order: 2, 116 | }, 117 | Name { 118 | name: "health potion".to_string(), 119 | proper_name: false, 120 | }, 121 | Item {}, 122 | Consumable {}, 123 | HealthProvider { heal_amount: 8 }, 124 | )); 125 | } 126 | 127 | fn apple(ecs: &mut Ecs, x: i32, y: i32) { 128 | ecs.world.push(( 129 | Position(MapPosition { x, y }), 130 | Renderable { 131 | glyph: to_cp437('°'), 132 | fg: RGB::named(YELLOW), 133 | bg: RGB::named(BLACK), 134 | render_order: 2, 135 | }, 136 | Name { 137 | name: "apple".to_string(), 138 | proper_name: false, 139 | }, 140 | Item {}, 141 | Consumable {}, 142 | HealthProvider { heal_amount: 5 }, 143 | )); 144 | } 145 | 146 | fn ball(ecs: &mut Ecs, x: i32, y: i32) { 147 | ecs.world.push(( 148 | Position(MapPosition { x, y }), 149 | Renderable { 150 | glyph: to_cp437('*'), 151 | fg: RGB::named(PURPLE), 152 | bg: RGB::named(BLACK), 153 | render_order: 2, 154 | }, 155 | Name { 156 | name: "ball".to_string(), 157 | proper_name: false, 158 | }, 159 | Item {}, 160 | )); 161 | } 162 | 163 | fn magic_missile_scroll(ecs: &mut Ecs, x: i32, y: i32) { 164 | ecs.world.push(( 165 | Position(MapPosition { x, y }), 166 | Renderable { 167 | glyph: to_cp437('?'), 168 | fg: RGB::named(CYAN), 169 | bg: RGB::named(BLACK), 170 | render_order: 2, 171 | }, 172 | Name { 173 | name: "magic missile scroll".to_string(), 174 | proper_name: false, 175 | }, 176 | Item {}, 177 | Consumable {}, 178 | Ranged { range: 6 }, 179 | InflictsDamage { damage: 8 }, 180 | )); 181 | } 182 | 183 | fn fireball_scroll(ecs: &mut Ecs, x: i32, y: i32) { 184 | ecs.world.push(( 185 | Position(MapPosition { x, y }), 186 | Renderable { 187 | glyph: to_cp437('?'), 188 | fg: RGB::named(ORANGE), 189 | bg: RGB::named(BLACK), 190 | render_order: 2, 191 | }, 192 | Name { 193 | name: "fireball scroll".to_string(), 194 | proper_name: false, 195 | }, 196 | Item {}, 197 | Consumable {}, 198 | Ranged { range: 6 }, 199 | InflictsDamage { damage: 20 }, 200 | AreaOfEffect { radius: 3 }, 201 | )); 202 | } 203 | 204 | /// Fills a room with stuff! 205 | pub(crate) fn spawn_room(ecs: &mut Ecs, room: &Rect) { 206 | let mut monster_spawn_points: Vec = Vec::new(); 207 | let mut item_spawn_points: Vec = Vec::new(); 208 | 209 | // Scope to keep the borrow checker happy 210 | { 211 | let mut rng = resource_get_mut!(ecs, RandomNumberGenerator); 212 | let num_monsters = rng.roll_dice(1, MAX_MONSTERS + 2) - 3; 213 | let num_items = rng.roll_dice(1, MAX_ITEMS + 2) - 3; 214 | 215 | for _i in 0..num_monsters { 216 | let mut added = false; 217 | while !added { 218 | let x = room.x1 + rng.roll_dice(1, i32::abs(room.x2 - room.x1)); 219 | let y = room.y1 + rng.roll_dice(1, i32::abs(room.y2 - room.y1)); 220 | let idx = ((y * MAP_WIDTH) + x) as usize; 221 | if !monster_spawn_points.contains(&idx) { 222 | monster_spawn_points.push(idx); 223 | added = true; 224 | } 225 | } 226 | } 227 | 228 | for _i in 0..num_items { 229 | let mut added = false; 230 | while !added { 231 | let x = room.x1 + rng.roll_dice(1, i32::abs(room.x2 - room.x1)); 232 | let y = room.y1 + rng.roll_dice(1, i32::abs(room.y2 - room.y1)); 233 | let idx = (y * MAP_WIDTH + x) as usize; 234 | if !item_spawn_points.contains(&idx) { 235 | item_spawn_points.push(idx); 236 | added = true; 237 | } 238 | } 239 | } 240 | } 241 | 242 | // Actually spawn the monsters 243 | for idx in monster_spawn_points.iter() { 244 | let x = *idx % MAP_WIDTH as usize; 245 | let y = *idx / MAP_WIDTH as usize; 246 | random_monster(ecs, x as i32, y as i32); 247 | } 248 | // Actually spawn the items 249 | for idx in item_spawn_points.iter() { 250 | let x = *idx % MAP_WIDTH as usize; 251 | let y = *idx / MAP_WIDTH as usize; 252 | random_item(ecs, x as i32, y as i32); 253 | } 254 | } 255 | -------------------------------------------------------------------------------- /src/scenes/game.rs: -------------------------------------------------------------------------------- 1 | use crate::components::*; 2 | use crate::ecs::Ecs; 3 | use crate::messages::{WantsToDropMessage, WantsToUseMessage}; 4 | use crate::player::player_input; 5 | use crate::queues::{WantsToDropQueue, WantsToUseQueue}; 6 | use crate::resources::{Camera, Map, PlayerEntity, PlayerPosition}; 7 | use crate::State; 8 | use crate::{gui, RunState}; 9 | use ::bracket_lib::prelude::*; 10 | use ::legion::*; 11 | 12 | use super::{Scene, SceneResult}; 13 | 14 | pub(crate) struct GameScene { 15 | schedule: Schedule, 16 | } 17 | 18 | impl Scene for GameScene { 19 | fn tick(&mut self, gs: &mut State, ctx: &mut BTerm) -> SceneResult { 20 | let ecs = &mut gs.ecs; 21 | 22 | if let Some(VirtualKeyCode::F1) = ctx.key { 23 | return SceneResult::Push(Box::new(super::show_text::ShowText::new(include_str!( 24 | "../../assets/help.txt" 25 | )))); 26 | } 27 | 28 | for i in 0..=crate::LAYERS { 29 | ctx.set_active_console(i); 30 | ctx.cls(); 31 | } 32 | 33 | self.draw_map(ecs, ctx); 34 | 35 | ctx.print(0, 0, format!("{} fps", ctx.fps as u32)); 36 | 37 | let oldrunstate = { *resource_get!(ecs, RunState) }; 38 | let mut newrunstate = oldrunstate; 39 | 40 | match newrunstate { 41 | RunState::SaveGame => { 42 | // TODO: Implement save 43 | // return SceneResult::Push(Box::new(crate::scenes::SaveScene::new())); 44 | newrunstate = RunState::AwaitingInput; 45 | } 46 | RunState::PreRun => { 47 | self.run_systems(ecs); 48 | newrunstate = RunState::AwaitingInput; 49 | } 50 | RunState::AwaitingInput => { 51 | newrunstate = player_input(ecs, ctx); 52 | let mut schedule = legion::Schedule::builder() 53 | .add_system(crate::systems::output_system()) 54 | .build(); 55 | schedule.execute(&mut ecs.world, &mut ecs.resources); 56 | } 57 | RunState::ReallyQuit => match gui::ask_bool(ctx, "Really quit?") { 58 | (gui::ItemMenuResult::Selected, false) | (gui::ItemMenuResult::Cancel, _) => { 59 | newrunstate = RunState::AwaitingInput 60 | } 61 | (gui::ItemMenuResult::Selected, true) => ctx.quit(), 62 | _ => (), 63 | }, 64 | RunState::EnergylessTick | RunState::Tick => { 65 | self.run_systems(ecs); 66 | let entity = resource_get!(ecs, PlayerEntity).0; 67 | newrunstate = ecs 68 | .world 69 | .entry(entity) 70 | .map_or(RunState::ReallyQuit, |entry| { 71 | if entry.get_component::().unwrap().energy >= 0 { 72 | RunState::AwaitingInput 73 | } else { 74 | RunState::Tick 75 | } 76 | }); 77 | } 78 | RunState::ShowInventory(inv_type) => match gui::show_inventory(ecs, ctx, inv_type) { 79 | (gui::ItemMenuResult::Cancel, _) => newrunstate = RunState::AwaitingInput, 80 | (gui::ItemMenuResult::Selected, Some(item_entity)) => { 81 | let player_entity = resource_get!(ecs, PlayerEntity).0; 82 | match inv_type { 83 | crate::InventoryType::Apply => { 84 | let should_add_wants_to_use = { 85 | let entry = ecs.world.entry(item_entity).unwrap(); 86 | if let Ok(range) = entry.get_component::() { 87 | let player_position = resource_get!(ecs, PlayerPosition).0; 88 | let camera = resource_get!(ecs, Camera); 89 | let start_pos = camera.transform_map_pos(player_position); 90 | let targeting_info = 91 | gui::TargetingInfo::new(range.range, start_pos, ctx); 92 | newrunstate = 93 | RunState::ShowTargeting(targeting_info, item_entity); 94 | false 95 | } else { 96 | true 97 | } 98 | }; 99 | if should_add_wants_to_use { 100 | resource_get!(ecs, WantsToUseQueue).send(WantsToUseMessage { 101 | who: player_entity, 102 | item: item_entity, 103 | target: None, 104 | }); 105 | 106 | newrunstate = RunState::Tick; 107 | } 108 | } 109 | crate::InventoryType::Drop => { 110 | resource_get!(ecs, WantsToDropQueue).send(WantsToDropMessage { 111 | who: player_entity, 112 | item: item_entity, 113 | }); 114 | newrunstate = RunState::Tick; 115 | } 116 | } 117 | } 118 | _ => (), 119 | }, 120 | RunState::ShowTargeting(ref mut targeting_info, item_entity) => { 121 | match targeting_info.show_targeting(ecs, ctx) { 122 | (gui::ItemMenuResult::Cancel, _) => newrunstate = RunState::AwaitingInput, 123 | (gui::ItemMenuResult::Selected, Some(target_position)) => { 124 | let player_entity = resource_get!(ecs, PlayerEntity).0; 125 | 126 | resource_get!(ecs, WantsToUseQueue).send(WantsToUseMessage { 127 | who: player_entity, 128 | item: item_entity, 129 | target: Some(target_position), 130 | }); 131 | 132 | newrunstate = RunState::Tick; 133 | } 134 | _ => (), 135 | } 136 | } 137 | } 138 | 139 | gui::draw_ui(ecs, ctx); 140 | 141 | ecs.resources.insert(newrunstate); 142 | 143 | SceneResult::Continue 144 | } 145 | } 146 | 147 | impl GameScene { 148 | pub(crate) fn new(gs: &mut State) -> Self { 149 | let ecs = &mut gs.ecs; 150 | 151 | ecs.resources.insert(RunState::PreRun); 152 | let mut builder = Schedule::builder(); 153 | builder 154 | .add_system(crate::systems::regain_energy_system()) 155 | .add_system(crate::systems::monster_ai_system()) 156 | .add_system(crate::systems::melee_combat_system()) 157 | .add_system(crate::systems::drop_system()) 158 | .add_system(crate::systems::pickup_system()); 159 | crate::systems::add_viewshed_system(ecs, &mut builder); 160 | builder 161 | .flush() 162 | .add_system(crate::systems::consume_system()) 163 | .flush() 164 | .add_system(crate::systems::damage_system()) 165 | .add_system(crate::systems::health_system()) 166 | .flush() 167 | .add_system(crate::systems::output_die_system()) 168 | .flush() 169 | .add_system(crate::systems::output_system()) 170 | .flush() 171 | .add_system(crate::systems::delete_the_dead_system()) 172 | .add_system(crate::systems::delete_items_system()) 173 | .add_system(crate::systems::delete_after_time_system()) 174 | .add_system(crate::systems::delete_after_tick_system()) 175 | .flush() 176 | .add_system(crate::systems::map_indexing_clear_system()) 177 | .add_system(crate::systems::map_indexing_system()); 178 | Self { 179 | schedule: builder.build(), 180 | } 181 | } 182 | 183 | fn run_systems(&mut self, ecs: &mut Ecs) { 184 | self.schedule.execute(&mut ecs.world, &mut ecs.resources); 185 | } 186 | 187 | fn draw_map(&mut self, ecs: &mut Ecs, ctx: &mut BTerm) { 188 | let player_position = resource_get!(ecs, PlayerPosition); 189 | { 190 | let mut camera = resource_get_mut!(ecs, Camera); 191 | crate::systems::camera_update(&mut camera, &player_position); 192 | } 193 | 194 | crate::resources::draw_map(ecs, ctx); 195 | 196 | let camera = resource_get!(ecs, Camera); 197 | 198 | let screen_pos = camera.transform_map_pos(player_position.0); 199 | 200 | for i in 0..crate::LAYERS { 201 | ctx.set_active_console(i); 202 | ctx.set_scale(1.0 + i as f32 * 0.01, screen_pos.x, screen_pos.y); 203 | } 204 | ctx.set_active_console(crate::LAYERS); 205 | 206 | let mut data = <(&Position, &Renderable)>::query() 207 | .iter(&ecs.world) 208 | .filter(|(p, _)| camera.is_in_view(p.0)) 209 | .collect::>(); 210 | data.sort_by(|&a, &b| b.1.render_order.cmp(&a.1.render_order)); 211 | 212 | let map = resource_get!(ecs, Map); 213 | for (pos, render) in data.iter() { 214 | if map.visible_tiles[map.pos_to_idx(**pos)] { 215 | let point = camera.transform_map_pos(pos.0); 216 | ctx.set(point.x, point.y, render.fg, render.bg, render.glyph); 217 | } 218 | } 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /src/player.rs: -------------------------------------------------------------------------------- 1 | use crate::{ 2 | components::{CombatStats, Energy, Item, Position, Viewshed}, 3 | messages::{WantsToMeleeMessage, WantsToPickupMessage}, 4 | queues::{WantsToMeleeQueue, WantsToPickupQueue}, 5 | resources::{Camera, Map, OutputQueue, PlayerEntity, PlayerPosition, PlayerTarget}, 6 | }; 7 | // use crate::components::*; 8 | use crate::ecs::Ecs; 9 | use crate::positions::{Direction, ScreenPosition}; 10 | use crate::{InventoryType, RunState}; 11 | use bracket_lib::prelude::*; 12 | use legion::*; 13 | 14 | pub(crate) fn try_move_player(dir: Direction, ecs: &mut Ecs) -> RunState { 15 | let (delta_x, delta_y) = dir.into(); 16 | let player_entity = resource_get!(ecs, PlayerEntity).0; 17 | 18 | let mut ret = RunState::AwaitingInput; 19 | 20 | let pos = { 21 | let map = resource_get_mut!(ecs, Map); 22 | 23 | let (x, y, idx) = { 24 | let player_entry = ecs.world.entry(player_entity).unwrap(); 25 | let pos = player_entry.into_component::().unwrap().0; 26 | 27 | let (x, y) = (pos.x + delta_x, pos.y + delta_y); 28 | (x, y, map.xy_to_idx(x, y)) 29 | }; 30 | 31 | for potential_target in map.tile_content[idx].iter() { 32 | if ecs 33 | .world 34 | .entry(*potential_target) 35 | .unwrap() 36 | .get_component::() 37 | .is_ok() 38 | { 39 | // Attack it 40 | // let mut output = resource_get_mut!(ecs, OutputQueue); 41 | // output.s("From Hell's Heart, I stab thee!"); 42 | let wants_to_melee_queue = resource_get!(ecs, WantsToMeleeQueue); 43 | wants_to_melee_queue.send(WantsToMeleeMessage { 44 | attacker: player_entity, 45 | target: *potential_target, 46 | }); 47 | return RunState::EnergylessTick; 48 | } 49 | } 50 | 51 | if map.blocked[idx] { 52 | None 53 | } else { 54 | let mut player_entry = ecs.world.entry(player_entity).unwrap(); 55 | let pos = { 56 | let pos = player_entry.get_component_mut::().unwrap(); 57 | pos.0.x = x.clamp(0, map.width - 1); 58 | pos.0.y = y.clamp(0, map.height - 1); 59 | pos.0 60 | }; 61 | let viewshed = player_entry.get_component_mut::().unwrap(); 62 | viewshed.dirty = true; 63 | player_entry.get_component_mut::().unwrap().energy = -100; 64 | ret = RunState::EnergylessTick; 65 | Some(pos) 66 | } 67 | }; 68 | if let Some(pos) = pos { 69 | // Update player position: 70 | ecs.resources.insert(PlayerPosition(pos)); 71 | } 72 | ret 73 | } 74 | 75 | pub(crate) fn get_item(ecs: &mut Ecs) -> RunState { 76 | let player_pos = resource_get!(ecs, PlayerPosition).0; 77 | let player_entity = resource_get!(ecs, PlayerEntity).0; 78 | let output = resource_get!(ecs, OutputQueue); 79 | 80 | let mut query = <(Entity, &Position, &Item)>::query(); 81 | 82 | let mut found_entity: Option = None; 83 | 84 | for (item_entity, pos, _item) in query.iter(&ecs.world) { 85 | if pos.0 == player_pos { 86 | found_entity = Some(*item_entity); 87 | break; 88 | } 89 | } 90 | if let Some(found_entity) = found_entity { 91 | let queue = resource_get!(ecs, WantsToPickupQueue); 92 | queue.send(WantsToPickupMessage { 93 | who: player_entity, 94 | item: found_entity, 95 | }); 96 | RunState::EnergylessTick 97 | } else { 98 | output.s("There is nothing you can pickup here!"); 99 | 100 | RunState::AwaitingInput 101 | } 102 | } 103 | 104 | fn init_auto_walk(ecs: &Ecs, pos: ScreenPosition) { 105 | let camera = resource_get!(ecs, Camera); 106 | let map = resource_get!(ecs, Map); 107 | let map_pos = camera.transform_screen_pos(pos); 108 | let idx = map.map_pos_to_idx(map_pos); 109 | 110 | let mut target_pos = resource_get_mut!(ecs, PlayerTarget); 111 | if camera.is_in_view(map_pos) && map.revealed_tiles[idx] { 112 | *target_pos = PlayerTarget::Position(map_pos); 113 | } else { 114 | *target_pos = PlayerTarget::None; 115 | } 116 | } 117 | 118 | pub(crate) fn try_auto_walk_player(dir: Direction, ecs: &mut Ecs) { 119 | let mut player_target = resource_get_mut!(ecs, PlayerTarget); 120 | 121 | *player_target = PlayerTarget::Dir(dir); 122 | } 123 | 124 | fn get_auto_walk_dest(ecs: &mut Ecs) -> Option<(i32, i32)> { 125 | let player_target = resource_get_mut!(ecs, PlayerTarget); 126 | match *player_target { 127 | PlayerTarget::Position(map_pos) => { 128 | let mut map = resource_get_mut!(ecs, Map); 129 | let player_pos = resource_get_mut!(ecs, PlayerPosition).0; 130 | 131 | let old_idx = map.map_pos_to_idx(player_pos) as i32; 132 | map.search_only_revealed(); 133 | let path = a_star_search(old_idx, map.map_pos_to_idx(map_pos) as i32, &*map); 134 | map.search_also_revealed(); 135 | 136 | if path.success && path.steps.len() > 1 { 137 | let new_idx = path.steps[1]; 138 | let new_pos = map.index_to_point2d(new_idx); 139 | let dir = (new_pos.x - player_pos.x, new_pos.y - player_pos.y); 140 | return Some(dir); 141 | } 142 | } 143 | PlayerTarget::Dir(dir) => { 144 | let player_pos = resource_get!(ecs, PlayerPosition).0; 145 | let map = resource_get!(ecs, Map); 146 | let (dx, dy) = dir.into(); 147 | let new_pos = player_pos + (dx, dy); 148 | if map.is_exit_valid(new_pos.x, new_pos.y) { 149 | return Some((dx, dy)); 150 | } 151 | } 152 | PlayerTarget::None => (), 153 | } 154 | None 155 | } 156 | 157 | fn auto_walk(ecs: &mut Ecs) -> RunState { 158 | let dest = get_auto_walk_dest(ecs); 159 | 160 | if let Some((dx, dy)) = dest { 161 | if try_move_player((dx, dy).into(), ecs) == RunState::EnergylessTick { 162 | return RunState::EnergylessTick; 163 | } 164 | } 165 | clear_auto_walk(ecs); 166 | RunState::AwaitingInput 167 | } 168 | 169 | fn clear_auto_walk(ecs: &mut Ecs) { 170 | let mut player_target = resource_get_mut!(ecs, PlayerTarget); 171 | *player_target = PlayerTarget::None; 172 | } 173 | 174 | pub(crate) fn player_input(ecs: &mut Ecs, ctx: &mut BTerm) -> RunState { 175 | if ctx.left_click { 176 | let pos = ctx.mouse_point(); 177 | let pos: ScreenPosition = pos.into(); 178 | init_auto_walk(ecs, pos); 179 | auto_walk(ecs) 180 | } else if ctx.shift { 181 | match ctx.key { 182 | Some(VirtualKeyCode::Q) => { 183 | return RunState::SaveGame; 184 | } 185 | Some(VirtualKeyCode::X) => { 186 | let target = { 187 | let map = resource_get!(ecs, Map); 188 | let player_pos = resource_get!(ecs, PlayerPosition).0; 189 | map.find_closest_unknown(player_pos) 190 | }; 191 | if let Some(target) = target { 192 | let mut target_pos = resource_get_mut!(ecs, PlayerTarget); 193 | *target_pos = PlayerTarget::Position(target); 194 | } 195 | return auto_walk(ecs); 196 | } 197 | 198 | Some(key) => { 199 | clear_auto_walk(ecs); 200 | if let Some(dir) = crate::gui::key_to_dir(key) { 201 | try_auto_walk_player(dir, ecs) 202 | } 203 | } 204 | _ => (), 205 | } 206 | auto_walk(ecs) 207 | } else { 208 | match ctx.key { 209 | Some(key) => { 210 | clear_auto_walk(ecs); 211 | match key { 212 | // Player movement 213 | VirtualKeyCode::H | VirtualKeyCode::Left => { 214 | try_move_player(Direction::West, ecs) 215 | } 216 | VirtualKeyCode::L | VirtualKeyCode::Right => { 217 | try_move_player(Direction::East, ecs) 218 | } 219 | VirtualKeyCode::K | VirtualKeyCode::Up => { 220 | try_move_player(Direction::North, ecs) 221 | } 222 | VirtualKeyCode::J | VirtualKeyCode::Down => { 223 | try_move_player(Direction::South, ecs) 224 | } 225 | VirtualKeyCode::Y => try_move_player(Direction::NorthWest, ecs), 226 | VirtualKeyCode::U => try_move_player(Direction::NorthEast, ecs), 227 | VirtualKeyCode::B => try_move_player(Direction::SouthWest, ecs), 228 | VirtualKeyCode::N => try_move_player(Direction::SouthEast, ecs), 229 | 230 | VirtualKeyCode::Space => { 231 | let player_entity = resource_get!(ecs, PlayerEntity).0; 232 | let mut player_entry = ecs.world.entry(player_entity).unwrap(); 233 | player_entry.get_component_mut::().unwrap().energy = -50; 234 | RunState::EnergylessTick 235 | } 236 | VirtualKeyCode::Comma => get_item(ecs), 237 | 238 | VirtualKeyCode::A => RunState::ShowInventory(InventoryType::Apply), 239 | VirtualKeyCode::D => RunState::ShowInventory(InventoryType::Drop), 240 | 241 | VirtualKeyCode::Escape => RunState::ReallyQuit, 242 | _ => RunState::AwaitingInput, 243 | } 244 | } 245 | _ => auto_walk(ecs), 246 | } 247 | } 248 | } 249 | -------------------------------------------------------------------------------- /langgen_english/src/output_queue/mod.rs: -------------------------------------------------------------------------------- 1 | mod output_builder; 2 | mod output_helper; 3 | 4 | use std::sync::Mutex; 5 | use crate::traits::EntityAdapter; 6 | use crate::traits::QueueAdapter; 7 | use crate::FragmentEntry; 8 | pub use output_builder::*; 9 | use output_helper::*; 10 | use std::marker::PhantomData; 11 | 12 | /// `OutputQueue` is used to create sentances that should be sent to a player. 13 | /// 14 | /// It can adapt the sentances based on the involved objects' genders, 15 | /// plural/uncountability and if the player can see them or not. 16 | /// 17 | /// 18 | /// The first word in a sentance will become capitalized, unless `supress_capitalize` is called before. 19 | /// 20 | /// At the end of a sentance, a dot will be added if the message didn't already end with a punctuation mark. 21 | /// Use `supress_dot` to supress it. 22 | /// 23 | /// Between each fragment a space is normally added. The next space can be supressed by called `supress_space`. 24 | /// If the text being added starts with ',' or '"' no space will be added before it. 25 | /// If the text being added ends with '"' no space will be added after it, use "\" ", if needed. 26 | /// 27 | pub struct OutputQueue 28 | where 29 | Entity: Copy, 30 | QA: QueueAdapter, 31 | { 32 | queue_adapter: QA, 33 | supress_dot: bool, 34 | supress_capitalize: bool, 35 | add_space: bool, 36 | output_string: String, 37 | clear_output: bool, 38 | who: Entity, 39 | lock: Mutex<()>, 40 | } 41 | 42 | impl OutputQueue 43 | where 44 | QA: QueueAdapter, 45 | Entity: std::fmt::Debug + Copy, 46 | { 47 | /// Create a new `OutputQueue` for player `who`, using 48 | /// the given [`QueueAdapter`](QueueAdapter) 49 | /// to store messages before they are processed 50 | /// with `process_queue`. 51 | pub fn new(queue_adapter: QA, who: Entity) -> Self { 52 | Self { 53 | queue_adapter, 54 | supress_dot: false, 55 | supress_capitalize: false, 56 | add_space: false, 57 | output_string: String::new(), 58 | clear_output: false, 59 | who, 60 | lock: Mutex::new(()), 61 | } 62 | } 63 | 64 | fn make_output_builder(&self) -> OutputBuilder<'_, QA, Entity> { 65 | OutputBuilder::new(&self.queue_adapter, self.lock.lock()) 66 | } 67 | 68 | /// Output a/an short-name, Proper-name or something/someone/some/you. 69 | pub fn a(&self, who: Entity) -> OutputBuilder<'_, QA, Entity> { 70 | self.make_output_builder().a(who) 71 | } 72 | 73 | /// Output a/an long name, Proper-long-name or something/someone/some/you. 74 | pub fn a_(&self, who: Entity) -> OutputBuilder<'_, QA, Entity> { 75 | self.make_output_builder().a_(who) 76 | } 77 | 78 | /// Output the short-name, Proper-name or something/someone/some/you. 79 | pub fn the(&self, who: Entity) -> OutputBuilder<'_, QA, Entity> { 80 | self.make_output_builder().the(who) 81 | } 82 | 83 | /// Output the long-name, Proper-name or something/someone/some/you. 84 | pub fn the_(&self, who: Entity) -> OutputBuilder<'_, QA, Entity> { 85 | self.make_output_builder().the_(who) 86 | } 87 | 88 | /// Output "the 's". 89 | /// If the viewer can't see it, "something's"/"someone's" is used. 90 | pub fn thes(&self, who: Entity) -> OutputBuilder<'_, QA, Entity> { 91 | self.make_output_builder().thes(who) 92 | } 93 | 94 | /// Output "the 's". 95 | /// If the viewer can't see it, "something's"/"someone's" is used. 96 | pub fn thes_(&self, who: Entity) -> OutputBuilder<'_, QA, Entity> { 97 | self.make_output_builder().thes_(who) 98 | } 99 | 100 | /// Output "yours"/"the 's". 101 | /// If the viewer can't see it, "something's"/"someone's" is used. 102 | pub fn thess(&self, who: Entity) -> OutputBuilder<'_, QA, Entity> { 103 | self.make_output_builder().thess(who) 104 | } 105 | 106 | /// Output "yours"/"the 's". 107 | /// If the viewer can't see it, "something's"/"someone's" is used. 108 | pub fn thess_(&self, who: Entity) -> OutputBuilder<'_, QA, Entity> { 109 | self.make_output_builder().thess_(who) 110 | } 111 | 112 | /// Output "my/his/her/their/its ". 113 | /// If the viewer can't see it, a() is used instead. 114 | pub fn my(&self, who: Entity, obj: Entity) -> OutputBuilder<'_, QA, Entity> { 115 | self.make_output_builder().my(who, obj) 116 | } 117 | 118 | /// Output "my/his/her/their/its ". 119 | /// If the viewer can't see it, a_() is used instead. 120 | pub fn my_(&self, who: Entity, obj: Entity) -> OutputBuilder<'_, QA, Entity> { 121 | self.make_output_builder().my_(who, obj) 122 | } 123 | 124 | /// Output "you"/. 125 | /// If the viewer can't see it, "something"/"someone" is used. 126 | pub fn word(&self, obj: Entity) -> OutputBuilder<'_, QA, Entity> { 127 | self.make_output_builder().word(obj) 128 | } 129 | 130 | /// Output "you"/. 131 | /// If the viewer can't see it, "something"/"someone" is used. 132 | pub fn word_(&self, obj: Entity) -> OutputBuilder<'_, QA, Entity> { 133 | self.make_output_builder().word_(obj) 134 | } 135 | 136 | /// Output "is"/"are". 137 | pub fn is(&self, obj: Entity) -> OutputBuilder<'_, QA, Entity> { 138 | self.make_output_builder().is(obj) 139 | } 140 | 141 | /// Output "has"/"have". 142 | pub fn has(&self, obj: Entity) -> OutputBuilder<'_, QA, Entity> { 143 | self.make_output_builder().has(obj) 144 | } 145 | 146 | /// Output the string. 147 | pub fn s(&self, s: &'static str) -> OutputBuilder<'_, QA, Entity> { 148 | self.make_output_builder().s(s) 149 | } 150 | 151 | /// Output the string. 152 | pub fn string(&self, s: String) -> OutputBuilder<'_, QA, Entity> { 153 | self.make_output_builder().string(s) 154 | } 155 | 156 | /// Output the verb and adds "s"/"es" as needed. 157 | pub fn v(&self, who: Entity, verb: &'static str) -> OutputBuilder<'_, QA, Entity> { 158 | self.make_output_builder().v(who, verb) 159 | } 160 | 161 | /// Output the verb and adds "s"/"es" as needed. 162 | pub fn verb(&self, who: Entity, verb: String) -> OutputBuilder<'_, QA, Entity> { 163 | self.make_output_builder().verb(who, verb) 164 | } 165 | 166 | /// Don't capitalize the next word. 167 | /// 168 | /// Only relevant for the first word. 169 | pub fn supress_capitalize(&self) -> OutputBuilder<'_, QA, Entity> { 170 | self.make_output_builder().supress_capitalize() 171 | } 172 | 173 | /// Don't add a space before the next word. 174 | pub fn supress_space(&self) -> OutputBuilder<'_, QA, Entity> { 175 | self.make_output_builder().supress_space() 176 | } 177 | 178 | /// Capitalize the next word. 179 | pub fn capitalize(&self) -> OutputBuilder<'_, QA, Entity> { 180 | self.make_output_builder().capitalize() 181 | } 182 | 183 | /// Supress automatic addition of an dot at the end of the sentance when needed. 184 | pub fn supress_dot(&self) -> OutputBuilder<'_, QA, Entity> { 185 | self.make_output_builder().supress_dot() 186 | } 187 | 188 | /// Change the output color. 189 | pub fn color(&self, color: (u8, u8, u8)) -> OutputBuilder<'_, QA, Entity> { 190 | self.make_output_builder().color(color) 191 | } 192 | 193 | fn maybe_clear_output(&mut self) { 194 | if self.clear_output { 195 | self.output_string.clear(); 196 | self.clear_output = false; 197 | } 198 | } 199 | 200 | fn push_char(&mut self, c: char) { 201 | self.maybe_clear_output(); 202 | self.output_string.push(c); 203 | } 204 | 205 | fn push_str(&mut self, s: &str) { 206 | self.maybe_clear_output(); 207 | self.output_string.push_str(s); 208 | } 209 | 210 | fn add_string(&mut self, text: &str) { 211 | if self.add_space && !(text.starts_with(',') || text.starts_with('"')) { 212 | self.push_char(' '); 213 | } 214 | if self.supress_capitalize { 215 | self.push_str(text); 216 | } else { 217 | self.supress_capitalize = true; 218 | self.maybe_clear_output(); 219 | uppercase_first_char(text, &mut self.output_string); 220 | } 221 | self.add_space = !text.ends_with('"'); 222 | } 223 | 224 | fn add_a_word>( 225 | &mut self, 226 | entity_adapter: &A, 227 | obj: Entity, 228 | name: &str, 229 | is_prop: bool, 230 | ) { 231 | if entity_adapter.is_me(obj) { 232 | self.add_string("you"); 233 | } else if entity_adapter.can_see(self.who, obj) { 234 | if !is_prop && is_singular(entity_adapter.gender(obj)) { 235 | let mut should_be_an = false; 236 | if let Some(c) = name.chars().next() { 237 | if is_vowel(c) { 238 | should_be_an = true; 239 | } 240 | } 241 | if should_be_an { 242 | self.add_string("an"); 243 | } else { 244 | self.add_string("a"); 245 | } 246 | } else if !is_prop { 247 | self.add_string("some"); 248 | } 249 | self.add_string(name); 250 | } else if is_prop { 251 | self.add_string("someone"); 252 | } else { 253 | self.add_string("something"); 254 | } 255 | } 256 | 257 | fn add_the_word>( 258 | &mut self, 259 | entity_adapter: &A, 260 | obj: Entity, 261 | name: &str, 262 | is_proper: bool, 263 | ) { 264 | if entity_adapter.is_me(obj) { 265 | self.add_string("you"); 266 | } else if entity_adapter.can_see(self.who, obj) { 267 | if !is_proper { 268 | self.add_string("the"); 269 | } 270 | self.add_string(name); 271 | } else if is_proper { 272 | self.add_string("someone"); 273 | } else { 274 | self.add_string("something"); 275 | } 276 | } 277 | 278 | fn sing_plur>( 279 | &mut self, 280 | entity_adapter: &A, 281 | who: Entity, 282 | singular: &'static str, 283 | plural: &'static str, 284 | ) { 285 | let mut g = entity_adapter.gender(who); 286 | if entity_adapter.is_me(who) { 287 | g = crate::Gender::Plural; 288 | } else if !entity_adapter.can_see(self.who, who) { 289 | g = crate::Gender::Male; 290 | } 291 | self.add_string(match g { 292 | crate::Gender::Plural => plural, 293 | _ => singular, 294 | }); 295 | } 296 | 297 | fn add_verb>(&mut self, entity_adapter: &A, who: Entity, verb: &str) { 298 | if !self.supress_capitalize { 299 | unimplemented!(); 300 | } 301 | if self.add_space { 302 | self.push_char(' '); 303 | } 304 | self.push_str(verb); 305 | self.supress_capitalize = true; 306 | self.add_space = false; 307 | if is_singular(entity_adapter.gender(who)) && !entity_adapter.is_me(who) { 308 | add_verb_end_s(&mut self.output_string); 309 | } 310 | self.add_string(""); 311 | } 312 | 313 | /// Process all the queued output with the `entity_adapter`. 314 | pub fn process_queue>(&mut self, entity_adapter: &mut A) { 315 | while let Some(FragmentEntry(frag)) = self.queue_adapter.pop() { 316 | use crate::Fragment::*; 317 | match frag { 318 | A(obj) => { 319 | // TODO; Fix add_a_word to take function. 320 | let mut s = String::new(); 321 | entity_adapter.append_short_name(obj, &mut s); 322 | self.add_a_word( 323 | entity_adapter, 324 | obj, 325 | &s, 326 | entity_adapter.has_short_proper(obj), 327 | ); 328 | } 329 | A_(obj) => { 330 | let mut s = String::new(); 331 | entity_adapter.append_long_name(obj, &mut s); 332 | self.add_a_word(entity_adapter, obj, &s, entity_adapter.has_long_proper(obj)); 333 | } 334 | The(obj) => { 335 | let mut s = String::new(); 336 | entity_adapter.append_short_name(obj, &mut s); 337 | self.add_the_word( 338 | entity_adapter, 339 | obj, 340 | &s, 341 | entity_adapter.has_short_proper(obj), 342 | ); 343 | } 344 | The_(obj) => { 345 | let mut s = String::new(); 346 | entity_adapter.append_long_name(obj, &mut s); 347 | self.add_the_word(entity_adapter, obj, &s, entity_adapter.has_long_proper(obj)); 348 | } 349 | Thes(obj) => { 350 | if entity_adapter.is_me(self.who) { 351 | self.add_string("your"); 352 | } else if entity_adapter.can_see(self.who, obj) { 353 | let mut s = String::new(); 354 | entity_adapter.append_short_name(obj, &mut s); 355 | // TODO; just append string to s. 356 | if let Some(ch) = s.chars().next_back() { 357 | let uc = ch.is_uppercase(); 358 | let add = match ch { 359 | 's' | 'S' => "'", 360 | _ => { 361 | if uc { 362 | "'S" 363 | } else { 364 | "'s" 365 | } 366 | } 367 | }; 368 | self.add_the_word( 369 | entity_adapter, 370 | obj, 371 | &s, 372 | entity_adapter.has_short_proper(obj), 373 | ); 374 | self.add_space = false; 375 | self.add_string(add); 376 | } else { 377 | // Error, short_name() == "" 378 | } 379 | } else if entity_adapter.has_short_proper(obj) { 380 | self.add_string("someone's"); 381 | } else { 382 | self.add_string("something's"); 383 | } 384 | } 385 | Thes_(obj) => { 386 | if entity_adapter.is_me(self.who) { 387 | self.add_string("your"); 388 | } else if entity_adapter.can_see(self.who, obj) { 389 | let mut s = String::new(); 390 | entity_adapter.append_long_name(obj, &mut s); 391 | if let Some(ch) = s.chars().next_back() { 392 | let uc = ch.is_uppercase(); 393 | let add = match ch { 394 | 's' | 'S' => "'", 395 | _ => { 396 | if uc { 397 | "'S" 398 | } else { 399 | "'s" 400 | } 401 | } 402 | }; 403 | self.add_the_word( 404 | entity_adapter, 405 | obj, 406 | &s, 407 | entity_adapter.has_long_proper(obj), 408 | ); 409 | self.add_space = false; 410 | self.add_string(add); 411 | } else { 412 | // Error, long_name() == "" 413 | } 414 | } else if entity_adapter.has_long_proper(obj) { 415 | self.add_string("someone's"); 416 | } else { 417 | self.add_string("something's"); 418 | } 419 | } 420 | Thess(_obj) => { 421 | /* TODO */ 422 | unimplemented!(); 423 | } 424 | Thess_(_obj) => { 425 | /* TODO */ 426 | unimplemented!(); 427 | } 428 | My(_who, _obj) => { 429 | /* TODO */ 430 | unimplemented!(); 431 | } 432 | My_(_who, _obj) => { 433 | /* TODO */ 434 | unimplemented!(); 435 | } 436 | Word(_obj) => { 437 | /* TODO */ 438 | unimplemented!(); 439 | } 440 | Word_(_obj) => { 441 | /* TODO */ 442 | unimplemented!(); 443 | } 444 | Is(obj) => { 445 | self.sing_plur(entity_adapter, obj, "is", "are"); 446 | } 447 | Has(obj) => { 448 | self.sing_plur(entity_adapter, obj, "has", "have"); 449 | } 450 | TextRef(s) => { 451 | self.add_string(s); 452 | } 453 | Text(s) => { 454 | self.add_string(&s); 455 | } 456 | VerbRef(who, verb) => { 457 | self.add_verb(entity_adapter, who, verb); 458 | } 459 | VerbString(who, verb) => { 460 | self.add_verb(entity_adapter, who, &verb); 461 | } 462 | Capitalize(capitalize) => { 463 | self.supress_capitalize = !capitalize; 464 | } 465 | SupressDot(supress_dot) => { 466 | self.supress_dot = supress_dot; 467 | } 468 | SupressSpace(supress_space) => { 469 | self.add_space = !supress_space; 470 | } 471 | Color(rgb) => { 472 | entity_adapter.write_text(&self.output_string); 473 | entity_adapter.set_color(rgb); 474 | self.clear_output = true; 475 | self.add_space = false; 476 | } 477 | EndOfLine => { 478 | if !self.supress_dot && needs_dot(&self.output_string) { 479 | self.push_char('.'); 480 | } else { 481 | self.maybe_clear_output(); 482 | } 483 | entity_adapter.write_text(&self.output_string); 484 | entity_adapter.done(); 485 | self.supress_dot = false; 486 | self.supress_dot = false; 487 | self.supress_capitalize = false; 488 | self.add_space = false; 489 | self.output_string.clear(); 490 | self.clear_output = false; 491 | } 492 | } 493 | } 494 | } 495 | } 496 | -------------------------------------------------------------------------------- /src/gui.rs: -------------------------------------------------------------------------------- 1 | use crate::components::*; 2 | use crate::ecs::*; 3 | use crate::resources::{Camera, GameLog, Map, PlayerEntity, PlayerPosition}; 4 | use crate::InventoryType; 5 | use crate::{Direction, MapPosition, ScreenPosition}; 6 | use bracket_lib::prelude::*; 7 | use legion::*; 8 | 9 | const BOTTOM_HEIGHT: i32 = 7; 10 | 11 | #[derive(PartialEq, Copy, Clone)] 12 | pub(crate) enum ItemMenuResult { 13 | Cancel, 14 | NoResponse, 15 | Selected, 16 | } 17 | 18 | #[derive(PartialEq, Copy, Clone, Debug)] 19 | pub(crate) enum MainMenuState { 20 | New, 21 | Load, 22 | Quit, 23 | } 24 | 25 | #[derive(PartialEq, Copy, Clone)] 26 | pub(crate) enum MainMenuResult { 27 | Selected(MainMenuState), 28 | NoSelection(MainMenuState), 29 | } 30 | 31 | pub(crate) fn key_to_dir(key: VirtualKeyCode) -> Option { 32 | match key { 33 | VirtualKeyCode::H | VirtualKeyCode::Left => Some(Direction::West), 34 | VirtualKeyCode::L | VirtualKeyCode::Right => Some(Direction::East), 35 | VirtualKeyCode::K | VirtualKeyCode::Up => Some(Direction::North), 36 | VirtualKeyCode::J | VirtualKeyCode::Down => Some(Direction::South), 37 | VirtualKeyCode::Y => Some(Direction::NorthWest), 38 | VirtualKeyCode::U => Some(Direction::NorthEast), 39 | VirtualKeyCode::B => Some(Direction::SouthWest), 40 | VirtualKeyCode::N => Some(Direction::SouthEast), 41 | _ => None, 42 | } 43 | } 44 | 45 | pub(crate) fn index_to_letter(idx: u8) -> char { 46 | if idx > 25 { 47 | index_to_letter(idx - 26).to_ascii_uppercase() 48 | } else { 49 | match idx { 50 | 0 => 'a', 51 | 1 => 'b', 52 | 2 => 'c', 53 | 3 => 'd', 54 | 4 => 'e', 55 | 5 => 'f', 56 | 6 => 'g', 57 | 7 => 'h', 58 | 8 => 'i', 59 | 9 => 'j', 60 | 10 => 'k', 61 | 11 => 'l', 62 | 12 => 'm', 63 | 13 => 'n', 64 | 14 => 'o', 65 | 15 => 'p', 66 | 16 => 'q', 67 | 17 => 'r', 68 | 18 => 's', 69 | 19 => 't', 70 | 20 => 'u', 71 | 21 => 'b', 72 | 22 => 'w', 73 | 23 => 'x', 74 | 24 => 'y', 75 | 25 => 'z', 76 | _ => panic!("Too large index"), 77 | } 78 | } 79 | } 80 | 81 | #[derive(Debug, PartialEq, Copy, Clone)] 82 | pub(crate) struct TargetingInfo { 83 | range: i32, 84 | last_mouse_point: Point, 85 | current_point: Point, 86 | } 87 | 88 | impl TargetingInfo { 89 | pub fn new(range: i32, start_pos: ScreenPosition, ctx: &mut BTerm) -> Self { 90 | Self { 91 | range, 92 | last_mouse_point: ctx.mouse_point(), 93 | current_point: start_pos.into(), 94 | } 95 | } 96 | 97 | pub fn show_targeting( 98 | &mut self, 99 | ecs: &mut Ecs, 100 | ctx: &mut BTerm, 101 | ) -> (ItemMenuResult, Option) { 102 | if Some(VirtualKeyCode::Escape) == ctx.key { 103 | return (ItemMenuResult::Cancel, None); 104 | } 105 | 106 | if self.last_mouse_point != ctx.mouse_point() { 107 | self.last_mouse_point = ctx.mouse_point(); 108 | self.current_point = ctx.mouse_point(); 109 | } else if ctx.left_click { 110 | self.current_point = ctx.mouse_point(); 111 | } else if let Some(key) = ctx.key { 112 | if let Some(dir) = key_to_dir(key) { 113 | let temp_pos: Point = self.current_point + dir; 114 | let (screen_width, screen_height) = ctx.get_char_size(); 115 | if temp_pos.x >= 0 116 | && temp_pos.x < screen_width as i32 117 | && temp_pos.y >= 0 118 | && temp_pos.y < (screen_height as i32 - BOTTOM_HEIGHT) 119 | { 120 | self.current_point = temp_pos; 121 | } 122 | } 123 | } 124 | 125 | ctx.print_color( 126 | 5, 127 | 0, 128 | RGB::named(YELLOW), 129 | RGB::named(BLACK), 130 | "Select Target:", 131 | ); 132 | 133 | let camera = *resource_get!(ecs, Camera); 134 | let player_entity = resource_get!(ecs, PlayerEntity).0; 135 | let player_entry = ecs.world.entry(player_entity).unwrap(); 136 | 137 | // Highlight available target cells 138 | let mut available_cells = Vec::new(); 139 | if let Ok(visible) = player_entry.into_component::() { 140 | let player_pos = *resource_get!(ecs, PlayerPosition); 141 | // We have a viewshed 142 | for pos in visible.visible_tiles.iter() { 143 | let point = camera.transform_map_pos(*pos); 144 | let distance = DistanceAlg::Pythagoras 145 | .distance2d(camera.transform_map_pos(player_pos.0).into(), point.into()); 146 | if distance <= self.range as f32 { 147 | ctx.set_bg(point.x, point.y, RGB::named(BLUE)); 148 | available_cells.push(point); 149 | } 150 | } 151 | } else { 152 | return (ItemMenuResult::Cancel, None); 153 | } 154 | 155 | // Draw mouse cursor 156 | let mut valid_target = false; 157 | for idx in available_cells.iter() { 158 | if self.current_point == (*idx).into() { 159 | valid_target = true; 160 | } 161 | } 162 | if valid_target { 163 | ctx.set_bg(self.current_point.x, self.current_point.y, RGB::named(CYAN)); 164 | 165 | match (ctx.key, ctx.left_click) { 166 | (_, true) 167 | | (Some(VirtualKeyCode::Return), _) 168 | | (Some(VirtualKeyCode::Space), _) => { 169 | return ( 170 | ItemMenuResult::Selected, 171 | Some(camera.transform_screen_pos(self.current_point.into())), 172 | ); 173 | } 174 | _ => (), 175 | } 176 | } else { 177 | ctx.set_bg(self.current_point.x, self.current_point.y, RGB::named(RED)); 178 | match (ctx.key, ctx.left_click) { 179 | (Some(VirtualKeyCode::Return), _) | (_, true) => { 180 | return (ItemMenuResult::Cancel, None) 181 | } 182 | _ => (), 183 | } 184 | } 185 | 186 | (ItemMenuResult::NoResponse, None) 187 | } 188 | } 189 | 190 | pub(crate) fn show_main_menu( 191 | ctx: &mut BTerm, 192 | ecs: &mut Ecs, 193 | current_state: MainMenuState, 194 | ) -> MainMenuResult { 195 | let (screen_width, screen_height) = ctx.get_char_size(); 196 | let (screen_width, screen_height) = (screen_width as i32, screen_height as i32); 197 | let text_width = 7; 198 | let x = screen_width / 2 - text_width / 2; 199 | let y = (screen_height / 2) - 1; 200 | 201 | let mut rnd = RandomNumberGenerator::new(); 202 | { 203 | let time = resource_get!(ecs, crate::resources::Time); 204 | if time.real_time_ms % 2000 < 1000 { 205 | let x = rnd.roll_dice(2, screen_width / 2) - 1; 206 | let y = rnd.roll_dice(2, screen_height / 2) - 1; 207 | 208 | let s = "*x+..."; 209 | for i in 0..=5 { 210 | ecs.world.push(( 211 | ScreenPosition { x, y }, 212 | Renderable { 213 | glyph: to_cp437(s.chars().nth(i).unwrap()), 214 | fg: RGB::named(WHITE).lerp(RGB::named(YELLOW), i as f32 / 5.), 215 | bg: RGB::named(BLACK), 216 | render_order: i as i32, 217 | }, 218 | EndTime { 219 | end_time_ms: time.real_time_ms + 100 * i as i64, 220 | }, 221 | )); 222 | } 223 | } 224 | } 225 | 226 | draw_renderables(ecs, ctx); 227 | 228 | ctx.print_color( 229 | (80 - 14) / 2, 230 | 11, 231 | RGBA::named(YELLOW), 232 | RGBA::named(BLACK), 233 | "Welcome to ...", 234 | ); 235 | 236 | for (y, line) in [ 237 | "########...#######..##....##..######...########", 238 | "##.....##.##.....##.##....##.##....##..##......", 239 | "##.....##.##.....##.##....##.##........##......", 240 | "########..##.....##.##....##.##...####.######..", 241 | "##...##...##.....##.##....##.##....##..##......", 242 | "##....##..##.....##.##....##.##....##..##......", 243 | "##.....##..#######...######...######...########", 244 | ] 245 | .iter() 246 | .enumerate() 247 | { 248 | ctx.print_color( 249 | 17, 250 | 14 + y as i32, 251 | RGB::named(ORANGERED2), 252 | RGB::named(BLACK), 253 | line, 254 | ); 255 | } 256 | 257 | ctx.draw_box_double( 258 | x, 259 | y, 260 | text_width, 261 | 5, 262 | RGB::named(DEEPSKYBLUE), 263 | RGB::named(BLACK), 264 | ); 265 | 266 | let x = x + 1; 267 | 268 | let black = RGB::named(BLACK); 269 | let white = RGB::named(WHITE); 270 | 271 | let (fg, bg) = if current_state == MainMenuState::New { 272 | (black, white) 273 | } else { 274 | (white, black) 275 | }; 276 | ctx.print_color(x, y + 1, fg, bg, " New "); 277 | let (fg, bg) = if current_state == MainMenuState::Load { 278 | (black, white) 279 | } else { 280 | (white, black) 281 | }; 282 | ctx.print_color(x, y + 2, fg, bg, " Load "); 283 | let (fg, bg) = if current_state == MainMenuState::Quit { 284 | (black, white) 285 | } else { 286 | (white, black) 287 | }; 288 | ctx.print_color(x, y + 4, fg, bg, " Quit "); 289 | 290 | match ctx.key { 291 | Some(VirtualKeyCode::Down) | Some(VirtualKeyCode::J) => { 292 | use MainMenuState::*; 293 | let current_state = match current_state { 294 | New => Load, 295 | Load => Quit, 296 | Quit => New, 297 | }; 298 | MainMenuResult::NoSelection(current_state) 299 | } 300 | Some(VirtualKeyCode::Up) | Some(VirtualKeyCode::K) => { 301 | use MainMenuState::*; 302 | let current_state = match current_state { 303 | New => Quit, 304 | Load => New, 305 | Quit => Load, 306 | }; 307 | MainMenuResult::NoSelection(current_state) 308 | } 309 | Some(VirtualKeyCode::Return) | Some(VirtualKeyCode::Space) => { 310 | MainMenuResult::Selected(current_state) 311 | } 312 | _ => MainMenuResult::NoSelection(current_state), 313 | } 314 | } 315 | 316 | pub(crate) fn ask_bool(ctx: &mut BTerm, question: &str) -> (ItemMenuResult, bool) { 317 | let width = question.len() as i32; 318 | 319 | let (screen_width, screen_height) = ctx.get_char_size(); 320 | 321 | ctx.draw_box_double( 322 | screen_width as i32 / 2 - width - 1, 323 | screen_height as i32 / 2 - 2, 324 | width + 3, 325 | 2, 326 | RGB::named(YELLOW), 327 | RGB::named(BLACK), 328 | ); 329 | 330 | ctx.print_color( 331 | screen_width as i32 / 2 - width + 1, 332 | screen_height as i32 / 2 - 1, 333 | RGB::named(YELLOW), 334 | RGB::named(BLACK), 335 | question, 336 | ); 337 | 338 | match ctx.key { 339 | Some(VirtualKeyCode::Y) => (ItemMenuResult::Selected, true), 340 | Some(VirtualKeyCode::N) => (ItemMenuResult::Selected, false), 341 | Some(VirtualKeyCode::Escape) => (ItemMenuResult::Cancel, false), 342 | _ => (ItemMenuResult::NoResponse, false), 343 | } 344 | } 345 | 346 | /// For A-Z menus, translates the keys A through Z into 0..25 347 | pub(crate) fn letter_to_option(shift: bool, key: VirtualKeyCode) -> i32 { 348 | let val = match key { 349 | VirtualKeyCode::A => 0, 350 | VirtualKeyCode::B => 1, 351 | VirtualKeyCode::C => 2, 352 | VirtualKeyCode::D => 3, 353 | VirtualKeyCode::E => 4, 354 | VirtualKeyCode::F => 5, 355 | VirtualKeyCode::G => 6, 356 | VirtualKeyCode::H => 7, 357 | VirtualKeyCode::I => 8, 358 | VirtualKeyCode::J => 9, 359 | VirtualKeyCode::K => 10, 360 | VirtualKeyCode::L => 11, 361 | VirtualKeyCode::M => 12, 362 | VirtualKeyCode::N => 13, 363 | VirtualKeyCode::O => 14, 364 | VirtualKeyCode::P => 15, 365 | VirtualKeyCode::Q => 16, 366 | VirtualKeyCode::R => 17, 367 | VirtualKeyCode::S => 18, 368 | VirtualKeyCode::T => 19, 369 | VirtualKeyCode::U => 20, 370 | VirtualKeyCode::V => 21, 371 | VirtualKeyCode::W => 22, 372 | VirtualKeyCode::X => 23, 373 | VirtualKeyCode::Y => 24, 374 | VirtualKeyCode::Z => 25, 375 | _ => return -1, 376 | }; 377 | if shift { 378 | return val + 26; 379 | } 380 | val 381 | } 382 | 383 | pub(crate) fn show_inventory( 384 | ecs: &mut Ecs, 385 | ctx: &mut BTerm, 386 | inv_type: InventoryType, 387 | ) -> (ItemMenuResult, Option) { 388 | let player_entity = resource_get!(ecs, PlayerEntity); 389 | 390 | let mut query = <(Entity, &Name, &InBackpack, &ItemIndex)>::query(); 391 | 392 | let mut inventory: Vec<_> = query 393 | .iter(&ecs.world) 394 | .filter(|item| item.2.owner == player_entity.0) 395 | .map(|(entity, name, _inbackpack, idx)| (*entity, idx.index, name)) 396 | .collect(); 397 | 398 | let count = inventory.len() as i32; 399 | inventory.sort_by(|a, b| a.1.cmp(&b.1)); 400 | 401 | if count == 0 { 402 | let gamelog = resource_get!(ecs, crate::resources::OutputQueue); 403 | gamelog.s("Your backpack is empty"); 404 | return (ItemMenuResult::Cancel, None); 405 | } 406 | 407 | let mut y = 25 - (count / 2); 408 | ctx.draw_box( 409 | 15, 410 | y - 2, 411 | 31, 412 | count + 3, 413 | RGB::named(WHITE), 414 | RGB::named(BLACK), 415 | ); 416 | let title = match inv_type { 417 | InventoryType::Apply => "Use", 418 | InventoryType::Drop => "Drop", 419 | }; 420 | ctx.print_color(18, y - 2, RGB::named(YELLOW), RGB::named(BLACK), title); 421 | ctx.print_color( 422 | 18, 423 | y + count + 1, 424 | RGB::named(YELLOW), 425 | RGB::named(BLACK), 426 | "ESCAPE to cancel", 427 | ); 428 | 429 | let mut items = std::collections::HashMap::new(); 430 | for (entities, index, name) in inventory { 431 | items.insert(index as i32, entities); 432 | ctx.set(17, y, RGB::named(WHITE), RGB::named(BLACK), to_cp437('(')); 433 | ctx.set( 434 | 18, 435 | y, 436 | RGB::named(YELLOW), 437 | RGB::named(BLACK), 438 | to_cp437(index_to_letter(index)), 439 | ); 440 | ctx.set(19, y, RGB::named(WHITE), RGB::named(BLACK), to_cp437(')')); 441 | 442 | ctx.print(21, y, name.name.to_string()); 443 | y += 1; 444 | } 445 | 446 | match ctx.key { 447 | None => (ItemMenuResult::NoResponse, None), 448 | Some(key) => match key { 449 | VirtualKeyCode::Escape => (ItemMenuResult::Cancel, None), 450 | _ => { 451 | let selected = letter_to_option(ctx.shift, key); 452 | if selected < 0 { 453 | (ItemMenuResult::NoResponse, None) 454 | } else if items.contains_key(&selected) { 455 | ( 456 | ItemMenuResult::Selected, 457 | Some(*items.get(&selected).unwrap()), 458 | ) 459 | } else { 460 | (ItemMenuResult::NoResponse, None) 461 | } 462 | } 463 | }, 464 | } 465 | } 466 | 467 | pub(crate) fn draw_renderables(ecs: &Ecs, ctx: &mut BTerm) { 468 | let camera = resource_get!(ecs, Camera); 469 | 470 | let height = camera.height(); 471 | let width = camera.width(); 472 | 473 | let mut data = <(&ScreenPosition, &Renderable)>::query() 474 | .iter(&ecs.world) 475 | .filter(|(p, _)| p.x >= 0 && p.x < width && p.y >= 0 && p.y < height) 476 | .collect::>(); 477 | data.sort_by(|&a, &b| b.1.render_order.cmp(&a.1.render_order)); 478 | 479 | for (pos, render) in data.iter() { 480 | ctx.set(pos.x, pos.y, render.fg, render.bg, render.glyph); 481 | } 482 | } 483 | 484 | pub(crate) fn draw_ui(ecs: &Ecs, ctx: &mut BTerm) { 485 | let (screen_width, screen_height) = ctx.get_char_size(); 486 | let (screen_width, screen_height) = (screen_width as i32, screen_height as i32); 487 | let bottom_start = screen_height - BOTTOM_HEIGHT; 488 | ctx.draw_box( 489 | 0, 490 | bottom_start, 491 | screen_width - 1, 492 | 6, 493 | RGB::named(WHITE), 494 | RGB::named(BLACK), 495 | ); 496 | 497 | let mut query = <(&CombatStats, &Player)>::query(); 498 | for (stats, _player) in query.iter(&ecs.world) { 499 | let health = format!(" HP: {} / {} ", stats.hp, stats.max_hp); 500 | ctx.print_color( 501 | 12, 502 | bottom_start, 503 | RGB::named(YELLOW), 504 | RGB::named(BLACK), 505 | &health, 506 | ); 507 | 508 | let bar_color = if stats.hp < stats.max_hp / 3 { 509 | RGB::named(RED) 510 | } else if stats.hp < 3 * stats.max_hp / 4 { 511 | RGB::named(YELLOW) 512 | } else { 513 | RGB::named(GREEN) 514 | }; 515 | 516 | ctx.draw_bar_horizontal( 517 | 28, 518 | bottom_start, 519 | 51, 520 | stats.hp, 521 | stats.max_hp, 522 | bar_color, 523 | RGB::named(BLACK), 524 | ); 525 | } 526 | 527 | let gamelog = resource_get!(ecs, GameLog); 528 | gamelog.draw_log(ctx, screen_height as u32 - 2, 4); 529 | 530 | draw_tooltips(ecs, ctx); 531 | } 532 | 533 | fn draw_tooltips(ecs: &Ecs, ctx: &mut BTerm) { 534 | let camera = *resource_get!(ecs, Camera); 535 | let map = resource_get!(ecs, Map); 536 | 537 | let mouse_pos = ctx.mouse_pos(); 538 | if mouse_pos.0 >= map.width || mouse_pos.1 >= map.height { 539 | return; 540 | } 541 | let mut tooltip: Vec = Vec::new(); 542 | let mut query = <(&Name, &Position)>::query(); 543 | for (name, position) in query.iter(&ecs.world) { 544 | let pos = camera.transform_map_pos(position.0); 545 | if pos.x == mouse_pos.0 && pos.y == mouse_pos.1 && map.is_visible(position.0) { 546 | tooltip.push(name.name.to_string()); 547 | } 548 | } 549 | 550 | if !tooltip.is_empty() { 551 | let mut width: i32 = 0; 552 | for s in tooltip.iter() { 553 | if width < s.len() as i32 { 554 | width = s.len() as i32; 555 | } 556 | } 557 | width += 3; 558 | 559 | if mouse_pos.0 > 40 { 560 | let arrow_pos = Point::new(mouse_pos.0 - 2, mouse_pos.1); 561 | let left_x = mouse_pos.0 - width; 562 | let mut y = mouse_pos.1; 563 | for s in tooltip.iter() { 564 | ctx.print_color( 565 | left_x, 566 | y, 567 | RGB::named(WHITE), 568 | RGB::named(GREY), 569 | s.to_string(), 570 | ); 571 | let padding = (width - s.len() as i32) - 1; 572 | for i in 0..padding { 573 | ctx.print_color( 574 | arrow_pos.x - i, 575 | y, 576 | RGB::named(WHITE), 577 | RGB::named(GREY), 578 | " ".to_string(), 579 | ); 580 | } 581 | y += 1; 582 | } 583 | ctx.print_color( 584 | arrow_pos.x, 585 | arrow_pos.y, 586 | RGB::named(WHITE), 587 | RGB::named(GREY), 588 | "->".to_string(), 589 | ); 590 | } else { 591 | let arrow_pos = Point::new(mouse_pos.0 + 1, mouse_pos.1); 592 | let left_x = mouse_pos.0 + 3; 593 | let mut y = mouse_pos.1; 594 | for s in tooltip.iter() { 595 | ctx.print_color( 596 | left_x + 1, 597 | y, 598 | RGB::named(WHITE), 599 | RGB::named(GREY), 600 | s.to_string(), 601 | ); 602 | let padding = (width - s.len() as i32) - 1; 603 | for i in 0..padding { 604 | ctx.print_color( 605 | arrow_pos.x + 1 + i, 606 | y, 607 | RGB::named(WHITE), 608 | RGB::named(GREY), 609 | " ".to_string(), 610 | ); 611 | } 612 | y += 1; 613 | } 614 | ctx.print_color( 615 | arrow_pos.x, 616 | arrow_pos.y, 617 | RGB::named(WHITE), 618 | RGB::named(GREY), 619 | "<-".to_string(), 620 | ); 621 | } 622 | } 623 | } 624 | -------------------------------------------------------------------------------- /src/resources/map.rs: -------------------------------------------------------------------------------- 1 | use crate::components::Position; 2 | use crate::ecs::Ecs; 3 | use crate::positions::{MapPosition, ScreenPosition}; 4 | use crate::resources::Camera; 5 | use crate::Direction; 6 | use ::bracket_lib::prelude::*; 7 | use ::legion::*; 8 | use ::serde::*; 9 | use std::cmp::{max, min}; 10 | 11 | pub(crate) const MAP_WIDTH: i32 = 120; 12 | pub(crate) const MAP_HEIGHT: i32 = 60; 13 | 14 | #[derive(Serialize, Deserialize, PartialEq, Copy, Clone, Debug)] 15 | pub(crate) enum WallType { 16 | Vertical, /* - */ 17 | Horizontal, /* | */ 18 | TopLeftCorner, /* ┌ */ 19 | TopRightCorner, /* ┐ */ 20 | BottomLeftCorner, /* └ */ 21 | BottomRightCorner, /* ┘ */ 22 | TeeDown, /* T */ 23 | TeeUp, /* ┴ */ 24 | TeeLeft, /* ├ */ 25 | TeeRight, /* ┤ */ 26 | Cross, /* + */ 27 | Pilar, /* ● */ 28 | } 29 | 30 | #[derive(Serialize, Deserialize, PartialEq, Copy, Clone, Debug)] 31 | pub(crate) enum TileType { 32 | Stone, 33 | Wall(WallType), 34 | Floor, 35 | } 36 | 37 | #[derive(Serialize, Deserialize, Default, Clone)] 38 | pub(crate) struct Map { 39 | pub tiles: Vec, 40 | pub rooms: Vec, 41 | pub width: i32, 42 | pub height: i32, 43 | pub revealed_tiles: Vec, 44 | pub visible_tiles: Vec, 45 | pub blocked: Vec, 46 | /// Does the tile contain anything that seems dangerous? 47 | pub dangerous: Vec, 48 | pub tile_content: Vec>, 49 | only_revealed: bool, 50 | } 51 | 52 | impl BaseMap for Map { 53 | fn is_opaque(&self, idx: usize) -> bool { 54 | matches!(self.tiles[idx], TileType::Wall(_) | TileType::Stone) 55 | } 56 | 57 | fn get_available_exits(&self, idx: usize) -> SmallVec<[(usize, f32); 10]> { 58 | let mut exits: SmallVec<[(usize, f32); 10]> = SmallVec::new(); 59 | let x = idx as i32 % self.width; 60 | let y = idx as i32 / self.width; 61 | 62 | let pos = MapPosition { x, y }; 63 | 64 | for dir in Direction::iter() { 65 | let pos = pos + *dir; 66 | if self.is_exit_valid(pos.x, pos.y) { 67 | let (dx, dy): (i32, i32) = (*dir).into(); 68 | if dx * dy == 0 { 69 | exits.push((self.map_pos_to_idx(pos), 1.0)); 70 | } else { 71 | exits.push((self.map_pos_to_idx(pos), 1.01)); 72 | } 73 | } 74 | } 75 | 76 | exits 77 | } 78 | 79 | fn get_pathing_distance(&self, idx1: usize, idx2: usize) -> f32 { 80 | let p1 = Point::new(idx1 as i32 % self.width, idx1 as i32 / self.width); 81 | let p2 = Point::new(idx2 as i32 % self.width, idx2 as i32 / self.width); 82 | DistanceAlg::Chebyshev.distance2d(p1, p2) 83 | } 84 | } 85 | 86 | impl Algorithm2D for Map { 87 | fn dimensions(&self) -> Point { 88 | Point { 89 | x: self.width, 90 | y: self.height, 91 | } 92 | } 93 | } 94 | 95 | impl Map { 96 | pub fn xy_to_idx(&self, x: i32, y: i32) -> usize { 97 | (y * self.width + x) as usize 98 | } 99 | 100 | pub fn pos_to_idx(&self, pos: Position) -> usize { 101 | (pos.0.y * self.width + pos.0.x) as usize 102 | } 103 | 104 | pub fn map_pos_to_idx(&self, pos: MapPosition) -> usize { 105 | (pos.y * self.width + pos.x) as usize 106 | } 107 | 108 | pub fn is_exit_valid(&self, x: i32, y: i32) -> bool { 109 | if x < 0 || x > self.width - 1 || y < 0 || y > self.height - 1 { 110 | return false; 111 | } 112 | let idx = self.xy_to_idx(x, y); 113 | if self.only_revealed && !self.revealed_tiles[idx] { 114 | return false; 115 | } 116 | !self.blocked[idx] 117 | } 118 | 119 | pub fn search_only_revealed(&mut self) { 120 | self.only_revealed = true 121 | } 122 | 123 | pub fn search_also_revealed(&mut self) { 124 | self.only_revealed = false 125 | } 126 | 127 | fn apply_room_to_map(&mut self, room: &Rect) { 128 | for y in room.y1 + 1..=room.y2 { 129 | for x in room.x1 + 1..=room.x2 { 130 | let idx = self.xy_to_idx(x, y); 131 | self.tiles[idx] = TileType::Floor; 132 | } 133 | } 134 | } 135 | 136 | fn apply_horizontal_tunnel(&mut self, x1: i32, x2: i32, y: i32) { 137 | for x in min(x1, x2)..=max(x1, x2) { 138 | let idx = self.xy_to_idx(x, y); 139 | if idx > 0 && idx < (self.width * self.height) as usize { 140 | self.tiles[idx] = TileType::Floor; 141 | } 142 | } 143 | } 144 | 145 | fn apply_vertical_tunnel(&mut self, y1: i32, y2: i32, x: i32) { 146 | for y in min(y1, y2)..=max(y1, y2) { 147 | let idx = self.xy_to_idx(x, y); 148 | if idx > 0 && idx < (self.width * self.height) as usize { 149 | self.tiles[idx] = TileType::Floor; 150 | } 151 | } 152 | } 153 | 154 | pub fn populate_blocked(&mut self) { 155 | for (i, tile) in self.tiles.iter_mut().enumerate() { 156 | self.blocked[i] = matches!(*tile, TileType::Wall(_) | TileType::Stone); 157 | } 158 | } 159 | 160 | pub fn is_solid(&self, pos: Point) -> bool { 161 | if !self.in_bounds(pos) { 162 | return true; 163 | } 164 | let idx = self.point2d_to_index(pos); 165 | matches!(self.tiles[idx], TileType::Wall(_) | TileType::Stone) 166 | } 167 | 168 | pub fn is_visible(&self, pos: MapPosition) -> bool { 169 | let idx = self.map_pos_to_idx(pos); 170 | self.visible_tiles[idx] 171 | } 172 | 173 | // Create points surrounding (x, y) 174 | fn points_around(x: i32, y: i32) -> Vec { 175 | vec![ 176 | Point::new(x - 1, y - 1), 177 | Point::new(x, y - 1), 178 | Point::new(x + 1, y - 1), 179 | Point::new(x + 1, y), 180 | Point::new(x + 1, y + 1), 181 | Point::new(x, y + 1), 182 | Point::new(x - 1, y + 1), 183 | Point::new(x - 1, y), 184 | ] 185 | } 186 | 187 | fn wall_continues(&self, pos: Point, dx: i32, dy: i32) -> bool { 188 | let new_pos = Point::new(pos.x + dx, pos.y + dy); 189 | if !self.is_solid(new_pos) { 190 | return false; 191 | } 192 | if dx != 0 { 193 | if !self.is_solid(Point::new(pos.x + dx, pos.y - 1)) 194 | || !self.is_solid(Point::new(pos.x + dx, pos.y)) 195 | || !self.is_solid(Point::new(pos.x + dx, pos.y + 1)) 196 | || !self.is_solid(Point::new(pos.x, pos.y - 1)) 197 | || !self.is_solid(Point::new(pos.x, pos.y + 1)) 198 | { 199 | return true; 200 | } 201 | } else if !self.is_solid(Point::new(pos.x - 1, pos.y + dy)) 202 | || !self.is_solid(Point::new(pos.x, pos.y + dy)) 203 | || !self.is_solid(Point::new(pos.x + 1, pos.y + dy)) 204 | || !self.is_solid(Point::new(pos.x - 1, pos.y)) 205 | || !self.is_solid(Point::new(pos.x + 1, pos.y)) 206 | { 207 | return true; 208 | } 209 | false 210 | } 211 | 212 | fn fix_walls(&mut self) { 213 | /* Remove single walls completely surrounded */ 214 | /* Change single walls completely lonely */ 215 | for y in 0..self.height { 216 | for x in 0..self.width { 217 | let pos = Point::new(x, y); 218 | if self.is_solid(pos) { 219 | let idx = self.point2d_to_index(pos); 220 | let count_walls = Self::points_around(x, y) 221 | .iter() 222 | .filter(|p| !self.is_solid(**p)) 223 | .count(); 224 | if count_walls == 0 { 225 | self.tiles[idx] = TileType::Stone; 226 | } else if count_walls == 8 { 227 | self.tiles[idx] = TileType::Wall(WallType::Pilar); 228 | } 229 | } 230 | } 231 | } 232 | for y in 0..self.height { 233 | for x in 0..self.width { 234 | let pos = Point::new(x, y); 235 | let idx = self.xy_to_idx(x, y); 236 | if let TileType::Wall(_) = self.tiles[idx] { 237 | let mut walls = 0; 238 | if self.wall_continues(pos, -1, 0) { 239 | walls += 1; 240 | } 241 | if self.wall_continues(pos, 1, 0) { 242 | walls += 2; 243 | } 244 | if self.wall_continues(pos, 0, -1) { 245 | walls += 4; 246 | } 247 | if self.wall_continues(pos, 0, 1) { 248 | walls += 8; 249 | } 250 | let walltype = match walls { 251 | 0 => WallType::Pilar, 252 | 1 => WallType::Horizontal, 253 | 2 => WallType::Horizontal, 254 | 3 => WallType::Horizontal, 255 | 4 => WallType::Vertical, 256 | 5 => WallType::BottomRightCorner, 257 | 6 => WallType::BottomLeftCorner, 258 | 7 => WallType::TeeUp, 259 | 8 => WallType::Vertical, 260 | 9 => WallType::TopRightCorner, 261 | 10 => WallType::TopLeftCorner, 262 | 11 => WallType::TeeDown, 263 | 12 => WallType::Vertical, 264 | 13 => WallType::TeeLeft, 265 | 14 => WallType::TeeRight, 266 | 15 => WallType::Cross, 267 | _ => unreachable!(), 268 | }; 269 | self.tiles[idx] = TileType::Wall(walltype); 270 | } 271 | } 272 | } 273 | } 274 | 275 | pub fn clear_content_index(&mut self) { 276 | for content in self.tile_content.iter_mut() { 277 | content.clear(); 278 | } 279 | } 280 | 281 | fn new(width: i32, height: i32) -> Map { 282 | let size = (width * height) as usize; 283 | let tiles = vec![TileType::Wall(WallType::Cross); size]; 284 | let rooms: Vec = Vec::new(); 285 | 286 | Map { 287 | tiles, 288 | rooms, 289 | width, 290 | height, 291 | revealed_tiles: vec![false; size], 292 | visible_tiles: vec![false; size], 293 | blocked: vec![false; size], 294 | dangerous: vec![false; size], 295 | tile_content: vec![vec![]; size], 296 | only_revealed: false, 297 | } 298 | } 299 | 300 | pub fn new_map_rooms_and_corridors() -> Map { 301 | const MAX_ROOMS: i32 = 30; 302 | const MIN_SIZE: i32 = 6; 303 | const MAX_SIZE: i32 = 10; 304 | 305 | let mut map = Map::new(MAP_WIDTH, MAP_HEIGHT); 306 | 307 | let mut rng = RandomNumberGenerator::new(); 308 | 309 | for _i in 0..MAX_ROOMS { 310 | let w = rng.range(MIN_SIZE, MAX_SIZE); 311 | let h = rng.range(MIN_SIZE, MAX_SIZE); 312 | let x = rng.roll_dice(1, map.width - w - 1) - 1; 313 | let y = rng.roll_dice(1, map.height - h - 1) - 1; 314 | let new_room = Rect::with_size(x, y, w, h); 315 | let mut ok = true; 316 | for other_room in map.rooms.iter() { 317 | if new_room.intersect(other_room) { 318 | ok = false 319 | } 320 | } 321 | if ok { 322 | map.apply_room_to_map(&new_room); 323 | if !map.rooms.is_empty() { 324 | let new_pos = new_room.center(); 325 | let prev_pos = map.rooms[map.rooms.len() - 1].center(); 326 | if rng.range(0, 2) == 1 { 327 | map.apply_horizontal_tunnel(prev_pos.x, new_pos.x, prev_pos.y); 328 | map.apply_vertical_tunnel(prev_pos.y, new_pos.y, new_pos.x); 329 | } else { 330 | map.apply_vertical_tunnel(prev_pos.y, new_pos.y, prev_pos.x); 331 | map.apply_horizontal_tunnel(prev_pos.x, new_pos.x, new_pos.y); 332 | } 333 | } 334 | map.rooms.push(new_room); 335 | } 336 | } 337 | 338 | map.fix_walls(); 339 | 340 | map.populate_blocked(); 341 | 342 | map 343 | } 344 | 345 | pub(crate) fn find_closest_unknown(&self, pos: MapPosition) -> Option { 346 | // TODO: Change to breadth first search, then return the position, 347 | // use autowalk to get there. 348 | 349 | let mut visited: Vec = Vec::with_capacity((self.height * self.width) as usize); 350 | for _y in 0..=self.height - 1 { 351 | for _x in 0..=self.width - 1 { 352 | visited.push(false); 353 | } 354 | } 355 | 356 | let mut expand = std::collections::VecDeque::new(); 357 | expand.push_back(pos); 358 | 359 | while let Some(curr_pos) = expand.pop_front() { 360 | let idx = self.pos_to_idx(curr_pos.into()); 361 | if !visited[idx] { 362 | visited[idx] = true; 363 | for dir in Direction::iter() { 364 | let pos = curr_pos + *dir; 365 | let idx = self.xy_to_idx(pos.x, pos.y); 366 | if !self.is_solid(pos.into()) && !self.revealed_tiles[idx] { 367 | return curr_pos.into(); 368 | } else if !self.is_solid(pos.into()) { 369 | expand.push_back(pos); 370 | } 371 | } 372 | } 373 | } 374 | 375 | None 376 | 377 | /* 378 | let mut starts = vec![]; 379 | for y in 1..self.height - 1 { 380 | for x in 1..self.width - 1 { 381 | let idx = self.xy_to_idx(x, y); 382 | let pos = Point::new(x, y); 383 | if !self.is_solid(pos) && !self.revealed_tiles[idx] { 384 | for dir in Direction::iter() { 385 | let pos = pos + *dir; 386 | let idx = self.xy_to_idx(pos.x, pos.y); 387 | if self.revealed_tiles[idx] && !self.is_solid(pos) { 388 | starts.push(idx); 389 | break; 390 | } 391 | } 392 | } 393 | } 394 | } 395 | 396 | let dijkstra_map = 397 | bracket_lib::prelude::DijkstraMap::new(self.width, self.height, &starts, self, 80.); 398 | 399 | let mut result = Direction::North; 400 | let mut min = f32::MAX; 401 | for dir in Direction::iter() { 402 | let pos = pos + *dir; 403 | if !self.is_solid(pos.into()) { 404 | let idx = self.xy_to_idx(pos.x, pos.y); 405 | let val = dijkstra_map.map[idx]; 406 | 407 | if val < min { 408 | result = *dir; 409 | min = val; 410 | } 411 | } 412 | } 413 | result 414 | */ 415 | } 416 | } 417 | 418 | fn get_glyph_for_wall(map: &Map, idx: usize, x: i32, y: i32, walltype: WallType) -> u16 { 419 | let mut walls = 0; 420 | 421 | if x > 0 && map.revealed_tiles[idx - 1_usize] { 422 | walls += 1 // Left 423 | } 424 | if x < map.width - 2 && map.revealed_tiles[idx + 1_usize] { 425 | walls += 2 // Right 426 | } 427 | if y > 0 && map.revealed_tiles[idx - map.width as usize] { 428 | walls += 4 // up 429 | } 430 | if y < map.height - 2 && map.revealed_tiles[idx + map.width as usize] { 431 | walls += 8 // Down 432 | } 433 | 434 | match walltype { 435 | WallType::Vertical => to_cp437('│'), 436 | WallType::Horizontal => to_cp437('─'), 437 | WallType::TopLeftCorner => to_cp437('┌'), 438 | WallType::TopRightCorner => to_cp437('┐'), 439 | WallType::BottomLeftCorner => to_cp437('└'), 440 | WallType::BottomRightCorner => to_cp437('┘'), 441 | WallType::TeeDown => match walls & (1 + 2 + 8) { 442 | 9 => to_cp437('┐'), 443 | 10 => to_cp437('┌'), 444 | 11 => to_cp437('┬'), 445 | _ => to_cp437('─'), 446 | }, 447 | WallType::TeeUp => match walls & (1 + 2 + 4) { 448 | 5 => to_cp437('┘'), 449 | 6 => to_cp437('└'), 450 | 7 => to_cp437('┴'), 451 | _ => to_cp437('─'), 452 | }, 453 | WallType::TeeRight => match walls & (2 + 4 + 8) { 454 | 6 => to_cp437('└'), 455 | 10 => to_cp437('┌'), 456 | 14 => to_cp437('├'), 457 | _ => to_cp437('│'), 458 | }, 459 | WallType::TeeLeft => match walls & (1 + 4 + 8) { 460 | 5 => to_cp437('┘'), 461 | 9 => to_cp437('┐'), 462 | 13 => to_cp437('┤'), 463 | _ => to_cp437('│'), 464 | }, 465 | WallType::Cross => match walls & (1 + 2 + 4 + 8) { 466 | 4 => to_cp437('┴'), 467 | 5 => to_cp437('┘'), 468 | 6 => to_cp437('└'), 469 | 7 => to_cp437('┴'), 470 | 8 => to_cp437('┬'), 471 | 9 => to_cp437('┐'), 472 | 10 => to_cp437('┌'), 473 | 11 => to_cp437('┬'), 474 | 12 => to_cp437('│'), 475 | 13 => to_cp437('┤'), 476 | 14 => to_cp437('├'), 477 | 15 => to_cp437('┼'), 478 | _ => to_cp437('─'), 479 | }, 480 | WallType::Pilar => 9, /* o */ 481 | } 482 | } 483 | 484 | pub(crate) fn draw_map(ecs: &Ecs, ctx: &mut BTerm) { 485 | let map = resource_get!(ecs, Map); 486 | let camera = resource_get!(ecs, Camera); 487 | 488 | for y in 0..camera.height() { 489 | for x in 0..camera.width() { 490 | let point = ScreenPosition { x, y }; 491 | let pos = camera.transform_screen_pos(point); 492 | if pos.x < 0 || pos.x >= map.width || pos.y < 0 || pos.y >= map.height { 493 | ctx.set( 494 | x, 495 | y, 496 | RGBA::from_f32(0., 0., 0., 1.), 497 | RGBA::from_f32(0., 0., 0., 1.), 498 | to_cp437('¿'), 499 | ); 500 | } else { 501 | let idx = map.map_pos_to_idx(pos); 502 | let tile = map.tiles[idx]; 503 | // Render a tile depending upon the tile type 504 | if map.revealed_tiles[idx] { 505 | let glyph; 506 | 507 | let bg = RGB::from_f32(0., 0., 0.); 508 | let mut fg; 509 | 510 | match tile { 511 | TileType::Floor => { 512 | fg = RGB::from_f32(0.5, 0.5, 0.5); 513 | glyph = to_cp437('·'); 514 | } 515 | TileType::Wall(walltype) => { 516 | fg = RGB::from_f32(0.7, 0.9, 0.7); 517 | glyph = get_glyph_for_wall(&map, idx, pos.x, pos.y, walltype) 518 | } 519 | TileType::Stone => { 520 | fg = RGB::from_f32(0.0, 1.0, 0.0); 521 | glyph = to_cp437('#'); 522 | } 523 | } 524 | if !map.visible_tiles[idx] { 525 | fg = fg.to_greyscale(); 526 | } 527 | for i in 0..crate::LAYERS { 528 | if i == 0 || tile != TileType::Floor { 529 | ctx.set_active_console(i); 530 | let mix = (crate::LAYERS - 1 - i) as f32 / (crate::LAYERS - 1) as f32; 531 | let mix = mix / 4.0; 532 | ctx.set(x, y, fg.lerp(RGB::from_f32(0., 0., 0.), mix), bg, glyph); 533 | } 534 | } 535 | ctx.set_active_console(0); 536 | } 537 | } 538 | } 539 | } 540 | } 541 | 542 | #[cfg(test)] 543 | mod tests { 544 | 545 | #[test] 546 | fn fix_walls() { 547 | use super::*; 548 | let mut map = Map::new(5, 5); 549 | map.fix_walls(); 550 | assert_eq!(map.tiles, vec![TileType::Stone; 5 * 5]); 551 | for tile in map.tiles.iter_mut() { 552 | *tile = TileType::Floor; 553 | } 554 | /* ..... 555 | * ...-- 556 | * .--- 557 | * .|... 558 | * ..... 559 | */ 560 | map.tiles[2 * 5 + 3] = TileType::Wall(WallType::Cross); 561 | map.tiles[2 * 5 + 4] = TileType::Wall(WallType::Cross); 562 | map.tiles[3 * 5 + 1] = TileType::Wall(WallType::Cross); 563 | map.tiles[3 * 5 + 2] = TileType::Wall(WallType::Cross); 564 | map.tiles[3 * 5 + 3] = TileType::Wall(WallType::Cross); 565 | map.tiles[3 * 5 + 4] = TileType::Wall(WallType::Cross); 566 | map.tiles[4 * 5 + 1] = TileType::Wall(WallType::Cross); 567 | map.fix_walls(); 568 | assert_eq!( 569 | map.tiles[2 * 5 + 3], 570 | TileType::Wall(WallType::TopLeftCorner) 571 | ); 572 | assert_eq!(map.tiles[2 * 5 + 4], TileType::Wall(WallType::Horizontal)); 573 | assert_eq!( 574 | map.tiles[3 * 5 + 1], 575 | TileType::Wall(WallType::TopLeftCorner) 576 | ); 577 | assert_eq!(map.tiles[3 * 5 + 2], TileType::Wall(WallType::Horizontal)); 578 | assert_eq!(map.tiles[3 * 5 + 3], TileType::Wall(WallType::TeeUp)); 579 | assert_eq!(map.tiles[4 * 5 + 1], TileType::Wall(WallType::Vertical)); 580 | } 581 | } 582 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (C) 2019 Sebastian Andersson 2 | 3 | This program is free software: you can redistribute it and/or modify 4 | it under the terms of the GNU General Public License as published by 5 | the Free Software Foundation, either version 3 of the License, or 6 | (at your option) any later version. 7 | 8 | This program is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 11 | 12 | GNU GENERAL PUBLIC LICENSE 13 | Version 3, 29 June 2007 14 | 15 | Copyright (C) 2007 Free Software Foundation, Inc. 16 | Everyone is permitted to copy and distribute verbatim copies 17 | of this license document, but changing it is not allowed. 18 | 19 | Preamble 20 | 21 | The GNU General Public License is a free, copyleft license for 22 | software and other kinds of works. 23 | 24 | The licenses for most software and other practical works are designed 25 | to take away your freedom to share and change the works. By contrast, 26 | the GNU General Public License is intended to guarantee your freedom to 27 | share and change all versions of a program--to make sure it remains free 28 | software for all its users. We, the Free Software Foundation, use the 29 | GNU General Public License for most of our software; it applies also to 30 | any other work released this way by its authors. You can apply it to 31 | your programs, too. 32 | 33 | When we speak of free software, we are referring to freedom, not 34 | price. Our General Public Licenses are designed to make sure that you 35 | have the freedom to distribute copies of free software (and charge for 36 | them if you wish), that you receive source code or can get it if you 37 | want it, that you can change the software or use pieces of it in new 38 | free programs, and that you know you can do these things. 39 | 40 | To protect your rights, we need to prevent others from denying you 41 | these rights or asking you to surrender the rights. Therefore, you have 42 | certain responsibilities if you distribute copies of the software, or if 43 | you modify it: responsibilities to respect the freedom of others. 44 | 45 | For example, if you distribute copies of such a program, whether 46 | gratis or for a fee, you must pass on to the recipients the same 47 | freedoms that you received. You must make sure that they, too, receive 48 | or can get the source code. And you must show them these terms so they 49 | know their rights. 50 | 51 | Developers that use the GNU GPL protect your rights with two steps: 52 | (1) assert copyright on the software, and (2) offer you this License 53 | giving you legal permission to copy, distribute and/or modify it. 54 | 55 | For the developers' and authors' protection, the GPL clearly explains 56 | that there is no warranty for this free software. For both users' and 57 | authors' sake, the GPL requires that modified versions be marked as 58 | changed, so that their problems will not be attributed erroneously to 59 | authors of previous versions. 60 | 61 | Some devices are designed to deny users access to install or run 62 | modified versions of the software inside them, although the manufacturer 63 | can do so. This is fundamentally incompatible with the aim of 64 | protecting users' freedom to change the software. The systematic 65 | pattern of such abuse occurs in the area of products for individuals to 66 | use, which is precisely where it is most unacceptable. Therefore, we 67 | have designed this version of the GPL to prohibit the practice for those 68 | products. If such problems arise substantially in other domains, we 69 | stand ready to extend this provision to those domains in future versions 70 | of the GPL, as needed to protect the freedom of users. 71 | 72 | Finally, every program is threatened constantly by software patents. 73 | States should not allow patents to restrict development and use of 74 | software on general-purpose computers, but in those that do, we wish to 75 | avoid the special danger that patents applied to a free program could 76 | make it effectively proprietary. To prevent this, the GPL assures that 77 | patents cannot be used to render the program non-free. 78 | 79 | The precise terms and conditions for copying, distribution and 80 | modification follow. 81 | 82 | TERMS AND CONDITIONS 83 | 84 | 0. Definitions. 85 | 86 | "This License" refers to version 3 of the GNU General Public License. 87 | 88 | "Copyright" also means copyright-like laws that apply to other kinds of 89 | works, such as semiconductor masks. 90 | 91 | "The Program" refers to any copyrightable work licensed under this 92 | License. Each licensee is addressed as "you". "Licensees" and 93 | "recipients" may be individuals or organizations. 94 | 95 | To "modify" a work means to copy from or adapt all or part of the work 96 | in a fashion requiring copyright permission, other than the making of an 97 | exact copy. The resulting work is called a "modified version" of the 98 | earlier work or a work "based on" the earlier work. 99 | 100 | A "covered work" means either the unmodified Program or a work based 101 | on the Program. 102 | 103 | To "propagate" a work means to do anything with it that, without 104 | permission, would make you directly or secondarily liable for 105 | infringement under applicable copyright law, except executing it on a 106 | computer or modifying a private copy. Propagation includes copying, 107 | distribution (with or without modification), making available to the 108 | public, and in some countries other activities as well. 109 | 110 | To "convey" a work means any kind of propagation that enables other 111 | parties to make or receive copies. Mere interaction with a user through 112 | a computer network, with no transfer of a copy, is not conveying. 113 | 114 | An interactive user interface displays "Appropriate Legal Notices" 115 | to the extent that it includes a convenient and prominently visible 116 | feature that (1) displays an appropriate copyright notice, and (2) 117 | tells the user that there is no warranty for the work (except to the 118 | extent that warranties are provided), that licensees may convey the 119 | work under this License, and how to view a copy of this License. If 120 | the interface presents a list of user commands or options, such as a 121 | menu, a prominent item in the list meets this criterion. 122 | 123 | 1. Source Code. 124 | 125 | The "source code" for a work means the preferred form of the work 126 | for making modifications to it. "Object code" means any non-source 127 | form of a work. 128 | 129 | A "Standard Interface" means an interface that either is an official 130 | standard defined by a recognized standards body, or, in the case of 131 | interfaces specified for a particular programming language, one that 132 | is widely used among developers working in that language. 133 | 134 | The "System Libraries" of an executable work include anything, other 135 | than the work as a whole, that (a) is included in the normal form of 136 | packaging a Major Component, but which is not part of that Major 137 | Component, and (b) serves only to enable use of the work with that 138 | Major Component, or to implement a Standard Interface for which an 139 | implementation is available to the public in source code form. A 140 | "Major Component", in this context, means a major essential component 141 | (kernel, window system, and so on) of the specific operating system 142 | (if any) on which the executable work runs, or a compiler used to 143 | produce the work, or an object code interpreter used to run it. 144 | 145 | The "Corresponding Source" for a work in object code form means all 146 | the source code needed to generate, install, and (for an executable 147 | work) run the object code and to modify the work, including scripts to 148 | control those activities. However, it does not include the work's 149 | System Libraries, or general-purpose tools or generally available free 150 | programs which are used unmodified in performing those activities but 151 | which are not part of the work. For example, Corresponding Source 152 | includes interface definition files associated with source files for 153 | the work, and the source code for shared libraries and dynamically 154 | linked subprograms that the work is specifically designed to require, 155 | such as by intimate data communication or control flow between those 156 | subprograms and other parts of the work. 157 | 158 | The Corresponding Source need not include anything that users 159 | can regenerate automatically from other parts of the Corresponding 160 | Source. 161 | 162 | The Corresponding Source for a work in source code form is that 163 | same work. 164 | 165 | 2. Basic Permissions. 166 | 167 | All rights granted under this License are granted for the term of 168 | copyright on the Program, and are irrevocable provided the stated 169 | conditions are met. This License explicitly affirms your unlimited 170 | permission to run the unmodified Program. The output from running a 171 | covered work is covered by this License only if the output, given its 172 | content, constitutes a covered work. This License acknowledges your 173 | rights of fair use or other equivalent, as provided by copyright law. 174 | 175 | You may make, run and propagate covered works that you do not 176 | convey, without conditions so long as your license otherwise remains 177 | in force. You may convey covered works to others for the sole purpose 178 | of having them make modifications exclusively for you, or provide you 179 | with facilities for running those works, provided that you comply with 180 | the terms of this License in conveying all material for which you do 181 | not control copyright. Those thus making or running the covered works 182 | for you must do so exclusively on your behalf, under your direction 183 | and control, on terms that prohibit them from making any copies of 184 | your copyrighted material outside their relationship with you. 185 | 186 | Conveying under any other circumstances is permitted solely under 187 | the conditions stated below. Sublicensing is not allowed; section 10 188 | makes it unnecessary. 189 | 190 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 191 | 192 | No covered work shall be deemed part of an effective technological 193 | measure under any applicable law fulfilling obligations under article 194 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 195 | similar laws prohibiting or restricting circumvention of such 196 | measures. 197 | 198 | When you convey a covered work, you waive any legal power to forbid 199 | circumvention of technological measures to the extent such circumvention 200 | is effected by exercising rights under this License with respect to 201 | the covered work, and you disclaim any intention to limit operation or 202 | modification of the work as a means of enforcing, against the work's 203 | users, your or third parties' legal rights to forbid circumvention of 204 | technological measures. 205 | 206 | 4. Conveying Verbatim Copies. 207 | 208 | You may convey verbatim copies of the Program's source code as you 209 | receive it, in any medium, provided that you conspicuously and 210 | appropriately publish on each copy an appropriate copyright notice; 211 | keep intact all notices stating that this License and any 212 | non-permissive terms added in accord with section 7 apply to the code; 213 | keep intact all notices of the absence of any warranty; and give all 214 | recipients a copy of this License along with the Program. 215 | 216 | You may charge any price or no price for each copy that you convey, 217 | and you may offer support or warranty protection for a fee. 218 | 219 | 5. Conveying Modified Source Versions. 220 | 221 | You may convey a work based on the Program, or the modifications to 222 | produce it from the Program, in the form of source code under the 223 | terms of section 4, provided that you also meet all of these conditions: 224 | 225 | a) The work must carry prominent notices stating that you modified 226 | it, and giving a relevant date. 227 | 228 | b) The work must carry prominent notices stating that it is 229 | released under this License and any conditions added under section 230 | 7. This requirement modifies the requirement in section 4 to 231 | "keep intact all notices". 232 | 233 | c) You must license the entire work, as a whole, under this 234 | License to anyone who comes into possession of a copy. This 235 | License will therefore apply, along with any applicable section 7 236 | additional terms, to the whole of the work, and all its parts, 237 | regardless of how they are packaged. This License gives no 238 | permission to license the work in any other way, but it does not 239 | invalidate such permission if you have separately received it. 240 | 241 | d) If the work has interactive user interfaces, each must display 242 | Appropriate Legal Notices; however, if the Program has interactive 243 | interfaces that do not display Appropriate Legal Notices, your 244 | work need not make them do so. 245 | 246 | A compilation of a covered work with other separate and independent 247 | works, which are not by their nature extensions of the covered work, 248 | and which are not combined with it such as to form a larger program, 249 | in or on a volume of a storage or distribution medium, is called an 250 | "aggregate" if the compilation and its resulting copyright are not 251 | used to limit the access or legal rights of the compilation's users 252 | beyond what the individual works permit. Inclusion of a covered work 253 | in an aggregate does not cause this License to apply to the other 254 | parts of the aggregate. 255 | 256 | 6. Conveying Non-Source Forms. 257 | 258 | You may convey a covered work in object code form under the terms 259 | of sections 4 and 5, provided that you also convey the 260 | machine-readable Corresponding Source under the terms of this License, 261 | in one of these ways: 262 | 263 | a) Convey the object code in, or embodied in, a physical product 264 | (including a physical distribution medium), accompanied by the 265 | Corresponding Source fixed on a durable physical medium 266 | customarily used for software interchange. 267 | 268 | b) Convey the object code in, or embodied in, a physical product 269 | (including a physical distribution medium), accompanied by a 270 | written offer, valid for at least three years and valid for as 271 | long as you offer spare parts or customer support for that product 272 | model, to give anyone who possesses the object code either (1) a 273 | copy of the Corresponding Source for all the software in the 274 | product that is covered by this License, on a durable physical 275 | medium customarily used for software interchange, for a price no 276 | more than your reasonable cost of physically performing this 277 | conveying of source, or (2) access to copy the 278 | Corresponding Source from a network server at no charge. 279 | 280 | c) Convey individual copies of the object code with a copy of the 281 | written offer to provide the Corresponding Source. This 282 | alternative is allowed only occasionally and noncommercially, and 283 | only if you received the object code with such an offer, in accord 284 | with subsection 6b. 285 | 286 | d) Convey the object code by offering access from a designated 287 | place (gratis or for a charge), and offer equivalent access to the 288 | Corresponding Source in the same way through the same place at no 289 | further charge. You need not require recipients to copy the 290 | Corresponding Source along with the object code. If the place to 291 | copy the object code is a network server, the Corresponding Source 292 | may be on a different server (operated by you or a third party) 293 | that supports equivalent copying facilities, provided you maintain 294 | clear directions next to the object code saying where to find the 295 | Corresponding Source. Regardless of what server hosts the 296 | Corresponding Source, you remain obligated to ensure that it is 297 | available for as long as needed to satisfy these requirements. 298 | 299 | e) Convey the object code using peer-to-peer transmission, provided 300 | you inform other peers where the object code and Corresponding 301 | Source of the work are being offered to the general public at no 302 | charge under subsection 6d. 303 | 304 | A separable portion of the object code, whose source code is excluded 305 | from the Corresponding Source as a System Library, need not be 306 | included in conveying the object code work. 307 | 308 | A "User Product" is either (1) a "consumer product", which means any 309 | tangible personal property which is normally used for personal, family, 310 | or household purposes, or (2) anything designed or sold for incorporation 311 | into a dwelling. In determining whether a product is a consumer product, 312 | doubtful cases shall be resolved in favor of coverage. For a particular 313 | product received by a particular user, "normally used" refers to a 314 | typical or common use of that class of product, regardless of the status 315 | of the particular user or of the way in which the particular user 316 | actually uses, or expects or is expected to use, the product. A product 317 | is a consumer product regardless of whether the product has substantial 318 | commercial, industrial or non-consumer uses, unless such uses represent 319 | the only significant mode of use of the product. 320 | 321 | "Installation Information" for a User Product means any methods, 322 | procedures, authorization keys, or other information required to install 323 | and execute modified versions of a covered work in that User Product from 324 | a modified version of its Corresponding Source. The information must 325 | suffice to ensure that the continued functioning of the modified object 326 | code is in no case prevented or interfered with solely because 327 | modification has been made. 328 | 329 | If you convey an object code work under this section in, or with, or 330 | specifically for use in, a User Product, and the conveying occurs as 331 | part of a transaction in which the right of possession and use of the 332 | User Product is transferred to the recipient in perpetuity or for a 333 | fixed term (regardless of how the transaction is characterized), the 334 | Corresponding Source conveyed under this section must be accompanied 335 | by the Installation Information. But this requirement does not apply 336 | if neither you nor any third party retains the ability to install 337 | modified object code on the User Product (for example, the work has 338 | been installed in ROM). 339 | 340 | The requirement to provide Installation Information does not include a 341 | requirement to continue to provide support service, warranty, or updates 342 | for a work that has been modified or installed by the recipient, or for 343 | the User Product in which it has been modified or installed. Access to a 344 | network may be denied when the modification itself materially and 345 | adversely affects the operation of the network or violates the rules and 346 | protocols for communication across the network. 347 | 348 | Corresponding Source conveyed, and Installation Information provided, 349 | in accord with this section must be in a format that is publicly 350 | documented (and with an implementation available to the public in 351 | source code form), and must require no special password or key for 352 | unpacking, reading or copying. 353 | 354 | 7. Additional Terms. 355 | 356 | "Additional permissions" are terms that supplement the terms of this 357 | License by making exceptions from one or more of its conditions. 358 | Additional permissions that are applicable to the entire Program shall 359 | be treated as though they were included in this License, to the extent 360 | that they are valid under applicable law. If additional permissions 361 | apply only to part of the Program, that part may be used separately 362 | under those permissions, but the entire Program remains governed by 363 | this License without regard to the additional permissions. 364 | 365 | When you convey a copy of a covered work, you may at your option 366 | remove any additional permissions from that copy, or from any part of 367 | it. (Additional permissions may be written to require their own 368 | removal in certain cases when you modify the work.) You may place 369 | additional permissions on material, added by you to a covered work, 370 | for which you have or can give appropriate copyright permission. 371 | 372 | Notwithstanding any other provision of this License, for material you 373 | add to a covered work, you may (if authorized by the copyright holders of 374 | that material) supplement the terms of this License with terms: 375 | 376 | a) Disclaiming warranty or limiting liability differently from the 377 | terms of sections 15 and 16 of this License; or 378 | 379 | b) Requiring preservation of specified reasonable legal notices or 380 | author attributions in that material or in the Appropriate Legal 381 | Notices displayed by works containing it; or 382 | 383 | c) Prohibiting misrepresentation of the origin of that material, or 384 | requiring that modified versions of such material be marked in 385 | reasonable ways as different from the original version; or 386 | 387 | d) Limiting the use for publicity purposes of names of licensors or 388 | authors of the material; or 389 | 390 | e) Declining to grant rights under trademark law for use of some 391 | trade names, trademarks, or service marks; or 392 | 393 | f) Requiring indemnification of licensors and authors of that 394 | material by anyone who conveys the material (or modified versions of 395 | it) with contractual assumptions of liability to the recipient, for 396 | any liability that these contractual assumptions directly impose on 397 | those licensors and authors. 398 | 399 | All other non-permissive additional terms are considered "further 400 | restrictions" within the meaning of section 10. If the Program as you 401 | received it, or any part of it, contains a notice stating that it is 402 | governed by this License along with a term that is a further 403 | restriction, you may remove that term. If a license document contains 404 | a further restriction but permits relicensing or conveying under this 405 | License, you may add to a covered work material governed by the terms 406 | of that license document, provided that the further restriction does 407 | not survive such relicensing or conveying. 408 | 409 | If you add terms to a covered work in accord with this section, you 410 | must place, in the relevant source files, a statement of the 411 | additional terms that apply to those files, or a notice indicating 412 | where to find the applicable terms. 413 | 414 | Additional terms, permissive or non-permissive, may be stated in the 415 | form of a separately written license, or stated as exceptions; 416 | the above requirements apply either way. 417 | 418 | 8. Termination. 419 | 420 | You may not propagate or modify a covered work except as expressly 421 | provided under this License. Any attempt otherwise to propagate or 422 | modify it is void, and will automatically terminate your rights under 423 | this License (including any patent licenses granted under the third 424 | paragraph of section 11). 425 | 426 | However, if you cease all violation of this License, then your 427 | license from a particular copyright holder is reinstated (a) 428 | provisionally, unless and until the copyright holder explicitly and 429 | finally terminates your license, and (b) permanently, if the copyright 430 | holder fails to notify you of the violation by some reasonable means 431 | prior to 60 days after the cessation. 432 | 433 | Moreover, your license from a particular copyright holder is 434 | reinstated permanently if the copyright holder notifies you of the 435 | violation by some reasonable means, this is the first time you have 436 | received notice of violation of this License (for any work) from that 437 | copyright holder, and you cure the violation prior to 30 days after 438 | your receipt of the notice. 439 | 440 | Termination of your rights under this section does not terminate the 441 | licenses of parties who have received copies or rights from you under 442 | this License. If your rights have been terminated and not permanently 443 | reinstated, you do not qualify to receive new licenses for the same 444 | material under section 10. 445 | 446 | 9. Acceptance Not Required for Having Copies. 447 | 448 | You are not required to accept this License in order to receive or 449 | run a copy of the Program. Ancillary propagation of a covered work 450 | occurring solely as a consequence of using peer-to-peer transmission 451 | to receive a copy likewise does not require acceptance. However, 452 | nothing other than this License grants you permission to propagate or 453 | modify any covered work. These actions infringe copyright if you do 454 | not accept this License. Therefore, by modifying or propagating a 455 | covered work, you indicate your acceptance of this License to do so. 456 | 457 | 10. Automatic Licensing of Downstream Recipients. 458 | 459 | Each time you convey a covered work, the recipient automatically 460 | receives a license from the original licensors, to run, modify and 461 | propagate that work, subject to this License. You are not responsible 462 | for enforcing compliance by third parties with this License. 463 | 464 | An "entity transaction" is a transaction transferring control of an 465 | organization, or substantially all assets of one, or subdividing an 466 | organization, or merging organizations. If propagation of a covered 467 | work results from an entity transaction, each party to that 468 | transaction who receives a copy of the work also receives whatever 469 | licenses to the work the party's predecessor in interest had or could 470 | give under the previous paragraph, plus a right to possession of the 471 | Corresponding Source of the work from the predecessor in interest, if 472 | the predecessor has it or can get it with reasonable efforts. 473 | 474 | You may not impose any further restrictions on the exercise of the 475 | rights granted or affirmed under this License. For example, you may 476 | not impose a license fee, royalty, or other charge for exercise of 477 | rights granted under this License, and you may not initiate litigation 478 | (including a cross-claim or counterclaim in a lawsuit) alleging that 479 | any patent claim is infringed by making, using, selling, offering for 480 | sale, or importing the Program or any portion of it. 481 | 482 | 11. Patents. 483 | 484 | A "contributor" is a copyright holder who authorizes use under this 485 | License of the Program or a work on which the Program is based. The 486 | work thus licensed is called the contributor's "contributor version". 487 | 488 | A contributor's "essential patent claims" are all patent claims 489 | owned or controlled by the contributor, whether already acquired or 490 | hereafter acquired, that would be infringed by some manner, permitted 491 | by this License, of making, using, or selling its contributor version, 492 | but do not include claims that would be infringed only as a 493 | consequence of further modification of the contributor version. For 494 | purposes of this definition, "control" includes the right to grant 495 | patent sublicenses in a manner consistent with the requirements of 496 | this License. 497 | 498 | Each contributor grants you a non-exclusive, worldwide, royalty-free 499 | patent license under the contributor's essential patent claims, to 500 | make, use, sell, offer for sale, import and otherwise run, modify and 501 | propagate the contents of its contributor version. 502 | 503 | In the following three paragraphs, a "patent license" is any express 504 | agreement or commitment, however denominated, not to enforce a patent 505 | (such as an express permission to practice a patent or covenant not to 506 | sue for patent infringement). To "grant" such a patent license to a 507 | party means to make such an agreement or commitment not to enforce a 508 | patent against the party. 509 | 510 | If you convey a covered work, knowingly relying on a patent license, 511 | and the Corresponding Source of the work is not available for anyone 512 | to copy, free of charge and under the terms of this License, through a 513 | publicly available network server or other readily accessible means, 514 | then you must either (1) cause the Corresponding Source to be so 515 | available, or (2) arrange to deprive yourself of the benefit of the 516 | patent license for this particular work, or (3) arrange, in a manner 517 | consistent with the requirements of this License, to extend the patent 518 | license to downstream recipients. "Knowingly relying" means you have 519 | actual knowledge that, but for the patent license, your conveying the 520 | covered work in a country, or your recipient's use of the covered work 521 | in a country, would infringe one or more identifiable patents in that 522 | country that you have reason to believe are valid. 523 | 524 | If, pursuant to or in connection with a single transaction or 525 | arrangement, you convey, or propagate by procuring conveyance of, a 526 | covered work, and grant a patent license to some of the parties 527 | receiving the covered work authorizing them to use, propagate, modify 528 | or convey a specific copy of the covered work, then the patent license 529 | you grant is automatically extended to all recipients of the covered 530 | work and works based on it. 531 | 532 | A patent license is "discriminatory" if it does not include within 533 | the scope of its coverage, prohibits the exercise of, or is 534 | conditioned on the non-exercise of one or more of the rights that are 535 | specifically granted under this License. You may not convey a covered 536 | work if you are a party to an arrangement with a third party that is 537 | in the business of distributing software, under which you make payment 538 | to the third party based on the extent of your activity of conveying 539 | the work, and under which the third party grants, to any of the 540 | parties who would receive the covered work from you, a discriminatory 541 | patent license (a) in connection with copies of the covered work 542 | conveyed by you (or copies made from those copies), or (b) primarily 543 | for and in connection with specific products or compilations that 544 | contain the covered work, unless you entered into that arrangement, 545 | or that patent license was granted, prior to 28 March 2007. 546 | 547 | Nothing in this License shall be construed as excluding or limiting 548 | any implied license or other defenses to infringement that may 549 | otherwise be available to you under applicable patent law. 550 | 551 | 12. No Surrender of Others' Freedom. 552 | 553 | If conditions are imposed on you (whether by court order, agreement or 554 | otherwise) that contradict the conditions of this License, they do not 555 | excuse you from the conditions of this License. If you cannot convey a 556 | covered work so as to satisfy simultaneously your obligations under this 557 | License and any other pertinent obligations, then as a consequence you may 558 | not convey it at all. For example, if you agree to terms that obligate you 559 | to collect a royalty for further conveying from those to whom you convey 560 | the Program, the only way you could satisfy both those terms and this 561 | License would be to refrain entirely from conveying the Program. 562 | 563 | 13. Use with the GNU Affero General Public License. 564 | 565 | Notwithstanding any other provision of this License, you have 566 | permission to link or combine any covered work with a work licensed 567 | under version 3 of the GNU Affero General Public License into a single 568 | combined work, and to convey the resulting work. The terms of this 569 | License will continue to apply to the part which is the covered work, 570 | but the special requirements of the GNU Affero General Public License, 571 | section 13, concerning interaction through a network will apply to the 572 | combination as such. 573 | 574 | 14. Revised Versions of this License. 575 | 576 | The Free Software Foundation may publish revised and/or new versions of 577 | the GNU General Public License from time to time. Such new versions will 578 | be similar in spirit to the present version, but may differ in detail to 579 | address new problems or concerns. 580 | 581 | Each version is given a distinguishing version number. If the 582 | Program specifies that a certain numbered version of the GNU General 583 | Public License "or any later version" applies to it, you have the 584 | option of following the terms and conditions either of that numbered 585 | version or of any later version published by the Free Software 586 | Foundation. If the Program does not specify a version number of the 587 | GNU General Public License, you may choose any version ever published 588 | by the Free Software Foundation. 589 | 590 | If the Program specifies that a proxy can decide which future 591 | versions of the GNU General Public License can be used, that proxy's 592 | public statement of acceptance of a version permanently authorizes you 593 | to choose that version for the Program. 594 | 595 | Later license versions may give you additional or different 596 | permissions. However, no additional obligations are imposed on any 597 | author or copyright holder as a result of your choosing to follow a 598 | later version. 599 | 600 | 15. Disclaimer of Warranty. 601 | 602 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 603 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 604 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 605 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 606 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 607 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 608 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 609 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 610 | 611 | 16. Limitation of Liability. 612 | 613 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 614 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 615 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 616 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 617 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 618 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 619 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 620 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 621 | SUCH DAMAGES. 622 | 623 | 17. Interpretation of Sections 15 and 16. 624 | 625 | If the disclaimer of warranty and limitation of liability provided 626 | above cannot be given local legal effect according to their terms, 627 | reviewing courts shall apply local law that most closely approximates 628 | an absolute waiver of all civil liability in connection with the 629 | Program, unless a warranty or assumption of liability accompanies a 630 | copy of the Program in return for a fee. 631 | --------------------------------------------------------------------------------