Compare commits

...

56 commits

Author SHA1 Message Date
67822f9f31 Update npm dependencies
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone Build is passing
2022-11-28 17:19:16 -05:00
a7d7d219a8 Optimize release builds for filesize 2022-11-28 17:18:52 -05:00
3674e4c26a Improve wall destruction sound
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone Build is passing
2022-11-27 23:53:27 -05:00
a7759cfa06 Fix wasm target 2022-11-27 23:53:03 -05:00
3ca0eb1eea Use simpler algorithm for PC speaker tones
All checks were successful
continuous-integration/drone/push Build is passing
2022-11-27 22:36:39 -05:00
4b0b67c69a Fix whipping input 2022-11-27 22:29:00 -05:00
74d1c120fc Revert "Use FunDSP crate for beepboops"
This reverts commit 9219b6c475.
2022-11-24 00:05:11 -05:00
9dcd94932f Crate updates 2022-11-23 23:57:14 -05:00
38d3333635 Implement whipping blocks and trees
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone Build is passing
2022-02-10 17:40:00 -05:00
36d109654c Add more one-time flashing messages 2022-02-09 21:28:15 -05:00
ce05dcb194 Implement speed and slow spells
All checks were successful
continuous-integration/drone/push Build is passing
2022-02-08 21:02:42 -05:00
3129f1be1d Be specific with cargo dependencies 2022-02-08 19:59:33 -05:00
9e83e004dc Suppress clippy warning in wasm_bindgen macro 2022-02-08 19:58:18 -05:00
7c93fb2bae Add web build and deploy to CI
Some checks reported errors
continuous-integration/drone/push Build was killed
continuous-integration/drone Build is passing
2022-02-04 21:37:07 -05:00
c17013ac92 Don't allow quitting on the web
All checks were successful
continuous-integration/drone/push Build is passing
2022-02-04 19:55:21 -05:00
f08691a62e Add webpack 2022-02-04 19:44:58 -05:00
ecd7c87e29 Add lib target for wasm 2022-02-04 19:28:31 -05:00
cbcda28719 Initial web support 2022-02-04 19:09:59 -05:00
4cd9f5acc3 Include numpad numbers in input 2022-02-04 00:22:05 -05:00
fe7eef7770 Add changing levels when touching stairs
All checks were successful
continuous-integration/drone/push Build is passing
2022-02-03 20:16:33 -05:00
f38a80b0c7 Implement deserializing non-random levels 2022-02-03 20:16:06 -05:00
2b484a4ad7 Clear tile content when monster eats a block 2022-02-03 20:11:58 -05:00
e948ad1d93 Remove unused imports 2022-02-03 19:19:40 -05:00
094d8e8617 Allow input to fall through flashing messages
This is for parity with the original game
2022-02-03 19:19:28 -05:00
550713aaf8 Better center flashing messages 2022-02-03 19:18:38 -05:00
0e5e823b0b Add flashing message intents 2022-02-03 17:59:44 -05:00
def124cd71 Add support for bottom flashing messages 2022-02-03 17:32:45 -05:00
ecaf448e90 Fix monster death logic
All checks were successful
continuous-integration/drone/push Build is passing
2022-02-03 01:39:49 -05:00
cf4e818094 Add sfx for monster eating block 2022-02-03 01:39:40 -05:00
616a4d580a Implement a few player pickups 2022-02-03 01:16:41 -05:00
c138aeb228 Display score as score*10 2022-02-03 00:56:39 -05:00
a3adb27acf Remove unused component
All checks were successful
continuous-integration/drone/push Build is passing
2022-02-03 00:22:58 -05:00
d9606e8b87 Switch from specs to hecs
All checks were successful
continuous-integration/drone/push Build is passing
2022-02-03 00:07:12 -05:00
c0ce37aa38 Use correct type for tile glyphs
All checks were successful
continuous-integration/drone/push Build is passing
2022-02-02 17:21:37 -05:00
9d911d8c72 Heavily reorganize code 2022-02-02 17:08:23 -05:00
6ae930cb43 Q quits the game 2022-02-01 17:08:07 -05:00
82c4358ac7 Allow monsters to break blocks
All checks were successful
continuous-integration/drone/push Build is passing
2022-02-01 03:01:21 -05:00
b62f2759de Add score for touching/whipping monsters 2022-02-01 02:56:45 -05:00
b2672904c8 Add monster impact sfx 2022-02-01 02:54:08 -05:00
73aa491d24 Fix monster/player collision issues 2022-02-01 02:53:00 -05:00
d818c8f7a6 Update dependencies
All checks were successful
continuous-integration/drone/push Build is passing
2022-01-31 19:10:56 -05:00
e5d820eded Abandon map_indexing_system
All checks were successful
continuous-integration/drone/push Build is passing
2022-01-31 19:10:24 -05:00
1c54755039 Skip out-of-bounds whip frames 2022-01-31 18:49:59 -05:00
770793ea68 Ensure hit beep on last frame of whip 2022-01-31 18:15:04 -05:00
9219b6c475 Use FunDSP crate for beepboops 2022-01-31 18:10:39 -05:00
784e205357 Implement whipping
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2022-01-30 17:06:27 -05:00
2be2b357ad Add difficulties
All checks were successful
continuous-integration/drone/push Build is passing
2022-01-30 03:56:34 -05:00
1628abea0e Remove unnecessary blink field from TileData 2022-01-30 03:55:59 -05:00
3da6f63b8e Randomize gem color 2022-01-30 01:01:51 -05:00
576bd76bd6 Render letter tiles as uppercase 2022-01-29 21:55:15 -05:00
62905dc330 Implement randomized levels 2022-01-29 21:53:01 -05:00
29a1a2bc7f Don't render player spawn tile 2022-01-29 21:51:12 -05:00
1dd15c4c8f Fill in data about each tile type
All checks were successful
continuous-integration/drone/push Build is passing
2022-01-29 05:28:06 -05:00
b417c53a01 Add method to remove gems with bounds check 2022-01-29 01:55:06 -05:00
67d6396e60 Update README 2022-01-29 01:02:33 -05:00
8e80ff3639 Implement and use map indexing system
All checks were successful
continuous-integration/drone/push Build is passing
2022-01-28 03:05:56 -05:00
48 changed files with 6674 additions and 966 deletions

View file

@ -6,12 +6,15 @@ steps:
image: rust
commands:
- apt-get update
- apt-get install -y libasound2-dev g++-mingw-w64-x86-64
- apt-get install -y libasound2-dev g++-mingw-w64-x86-64 npm
- rustup target add x86_64-pc-windows-gnu
- rustup toolchain install stable-x86_64-pc-windows-gnu
- cargo build --release --verbose --all
- rustup target add wasm32-unknown-unknown
- cargo build --release --verbose --all --target x86_64-unknown-linux-gnu
- cargo build --release --verbose --all --target x86_64-pc-windows-gnu
- mv target/release/kroz kroz_linux_x86_64
- npm install
- npm run build
- mv target/x86_64-unknown-linux-gnu/release/kroz kroz_linux_x86_64
- mv target/x86_64-pc-windows-gnu/release/kroz.exe kroz_win_x86_64.exe
- name: release
image: plugins/gitea-release
@ -29,3 +32,22 @@ steps:
when:
event:
- tag
- name: deploy
image: alpine
volumes:
- name: krozhtml
path: /html
commands:
- rm -r /html/*.wasm || true
- cp -r dist/* /html/
- chown -R 1000:1000 /html/*
when:
event:
- promote
target:
- production
volumes:
- name: krozhtml
host:
path: /home/alex/docker/kroz/files

4
.gitignore vendored
View file

@ -1,3 +1,7 @@
/extern
/target
.vscode
/pkg
node_modules
/dist
/wasm-pack.log

860
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -4,15 +4,32 @@ version = "0.1.0"
edition = "2021"
build = "build.rs"
[lib]
name = "libkroz"
crate-type = ["cdylib", "rlib"]
[[bin]]
name = "kroz"
path = "src/main.rs"
[dependencies]
# bracket-lib = { path = "extern/bracket-lib" }
bracket-lib = { git = "https://github.com/amethyst/bracket-lib" }
specs = { version = "0.16.1", default-features = false }
hecs = "0.9.0"
specs-derive = "0.4.1"
cpal = "0.13"
oddio = "0.5"
rand = "0.8"
spin_sleep = "1.0"
cpal = { version = "0.14.1", features = ["wasm-bindgen"] }
oddio = "0.6.2"
typenum = "1.15.0"
console_error_panic_hook = "0.1.7"
wasm-bindgen = "0.2.79"
instant = "0.1.12"
rand = "0.8.5"
getrandom = { version = "0.2.4", features = ["js"] }
[target.'cfg(windows)'.build-dependencies]
winres = "0.1"
winres = "0.1.12"
[profile.release]
lto = true
opt-level = 's'

View file

@ -17,17 +17,22 @@ The goal is to closely mimic the look and behavior of the original game, but not
- Game speed will be fixed, possibly configurable
- The original game's speed varied with CPU speed
- Improve control response
- Support Windows, Linux, macOS
- Possibly web and mobile platforms too
- Support Windows, Linux, macOS, and the web
## Building
1. [Install Rust](https://rustup.rs/)
2. Run `cargo build` or `cargo run`
[Install Rust](https://rustup.rs/)
### Desktop
Run `cargo build` or `cargo run`
### Web
Run `npm run build` or `npm start`
## License
"Kroz" is a registered trademark of Apogee Software, Ltd.
The original "Kroz" copyright 1987 - 2009 Apogee Software, Ltd. All trademarks and copyrights reserved.
The original "Kroz" copyright 1987 - 2022 Apogee Entertainment Inc. All trademarks and copyrights reserved.
This project has no affiliation with Apogee Software, Ltd and its code is licensed under the [GNU General Public License Version 3](https://www.gnu.org/licenses/gpl-3.0.en.html).
This project has no affiliation with Apogee Entertainment Inc. and the code within is licensed under the [GNU General Public License Version 3](https://www.gnu.org/licenses/gpl-3.0.en.html).

View file

@ -1,12 +1,12 @@
#[cfg(target_os = "windows")]
#[cfg(windows)]
extern crate winres;
#[cfg(target_os = "windows")]
#[cfg(windows)]
fn main() {
let mut res = winres::WindowsResource::new();
res.set_icon("icon.ico");
res.compile().unwrap();
let _ = res.compile();
}
#[cfg(not(target_os = "windows"))]
#[cfg(not(windows))]
fn main() {}

1
js/index.js Normal file
View file

@ -0,0 +1 @@
import("../pkg/index.js").catch(console.error);

3701
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

18
package.json Normal file
View file

@ -0,0 +1,18 @@
{
"author": "anpage <alex@anpage.me>",
"name": "kroz",
"version": "0.1.0",
"scripts": {
"build": "rimraf dist pkg && webpack",
"start": "rimraf dist pkg && webpack-dev-server --open",
"test": "cargo test && wasm-pack test --headless"
},
"devDependencies": {
"@wasm-tool/wasm-pack-plugin": "^1.1.0",
"copy-webpack-plugin": "^11.0.0",
"rimraf": "^3.0.0",
"webpack": "^5.75.0",
"webpack-cli": "^5.0.0",
"webpack-dev-server": "^4.11.1"
}
}

View file

@ -1,3 +1,5 @@
use instant::Instant;
pub mod monster;
pub mod player;
pub mod position;
@ -7,3 +9,11 @@ pub use monster::Monster;
pub use player::Player;
pub use position::Position;
pub use renderable::Renderable;
use crate::resources::sound_output::SoundEffectHandle;
pub struct WantsToWhip {
pub frame: u8,
pub last_frame: Instant,
pub sound: Option<SoundEffectHandle>,
}

View file

@ -1,9 +1,10 @@
use crate::vga_color as vga;
use crate::{
graphics::vga_color as vga,
resources::{sound_output::SoundSamples, SoundEffects},
};
use bracket_lib::prelude::*;
use specs::prelude::*;
use specs_derive::Component;
#[derive(Component, Debug)]
#[derive(Debug)]
pub struct Monster {
pub kind: MonsterKind,
pub ticks_until_move: i32,
@ -47,3 +48,11 @@ pub fn damage_for_kind(kind: MonsterKind) -> u32 {
MonsterKind::Fast => 3,
}
}
pub fn sound_effect_for_kind(kind: MonsterKind, sound_effects: &SoundEffects) -> SoundSamples {
match kind {
MonsterKind::Slow => sound_effects.slow_hit.clone(),
MonsterKind::Medium => sound_effects.medium_hit.clone(),
MonsterKind::Fast => sound_effects.fast_hit.clone(),
}
}

View file

@ -1,9 +1,6 @@
use std::time::Instant;
use instant::Instant;
use specs::prelude::*;
use specs_derive::Component;
#[derive(Component, Debug)]
#[derive(Debug)]
pub struct Player {
pub last_moved: Instant,
}

View file

@ -1,8 +1,6 @@
use bracket_lib::prelude::*;
use specs::prelude::*;
use specs_derive::Component;
#[derive(Component)]
#[derive(Clone, Copy, Debug)]
pub struct Position {
pub x: i32,
pub y: i32,
@ -13,3 +11,21 @@ impl PartialEq<Point> for Position {
self.x == other.x && self.y == other.y
}
}
impl From<Point> for Position {
fn from(point: Point) -> Self {
Self {
x: point.x,
y: point.y,
}
}
}
impl From<Position> for Point {
fn from(position: Position) -> Self {
Self {
x: position.x,
y: position.y,
}
}
}

View file

@ -1,8 +1,6 @@
use bracket_lib::prelude::*;
use specs::prelude::*;
use specs_derive::Component;
#[derive(Component)]
#[derive(Debug)]
pub struct Renderable {
pub glyph: FontCharType,
pub fg: RGB,

View file

@ -2,6 +2,7 @@
/// Fast PC mode at 400 cycles/ms.
pub const CLOCK_PERIOD: f32 = 0.184;
pub const PLAYER_STEP_PERIOD: f32 = 1.0 / 7.5;
pub const FLASHING_PERIOD: f32 = 0.02;
pub const SIDEBAR_POS_X: i32 = 66;
pub const SIDEBAR_POS_Y: i32 = 0;
@ -12,3 +13,5 @@ pub const MAP_SIZE: usize = MAP_WIDTH * MAP_HEIGHT;
pub const MAP_X: usize = 1;
pub const MAP_Y: usize = 1;
pub const BASE_WHIP_POWER: u32 = 2;

16
src/graphics/entities.rs Normal file
View file

@ -0,0 +1,16 @@
use bracket_lib::prelude::*;
use hecs::World;
use crate::{components::*, constants::*};
pub fn draw(world: &World, bterm: &mut BTerm) {
for (_, (pos, render)) in &mut world.query::<(&Position, &Renderable)>() {
bterm.set(
pos.x + MAP_X as i32,
pos.y + MAP_Y as i32,
render.fg,
render.bg,
render.glyph,
);
}
}

View file

@ -0,0 +1,18 @@
use crate::constants::*;
use crate::graphics::vga_color as vga;
use crate::resources::Resources;
use bracket_lib::prelude::*;
pub fn draw(resources: &mut Resources, bterm: &mut BTerm) {
if let Some(flashing_message) = &mut resources.flashing_message {
flashing_message.next_color();
bterm.print_color_centered_at(
MAP_X + (MAP_WIDTH / 2),
MAP_Y + MAP_HEIGHT,
RGB::named(vga::get_by_index(flashing_message.color)),
RGB::named(vga::BLACK),
flashing_message.message.to_string(),
);
}
}

7
src/graphics/map.rs Normal file
View file

@ -0,0 +1,7 @@
use bracket_lib::prelude::*;
use crate::resources::*;
pub fn draw(resources: &Resources, bterm: &mut BTerm) {
resources.map.draw(bterm);
}

20
src/graphics/mod.rs Normal file
View file

@ -0,0 +1,20 @@
use bracket_lib::prelude::*;
use hecs::World;
use crate::resources::Resources;
mod entities;
mod flashing_message;
mod map;
mod sidebar;
pub mod vga_color;
mod whip;
pub fn draw(world: &World, resources: &mut Resources, bterm: &mut BTerm) {
bterm.cls();
map::draw(resources, bterm);
entities::draw(world, bterm);
whip::draw(world, resources, bterm);
flashing_message::draw(resources, bterm);
sidebar::draw(resources, bterm);
}

132
src/graphics/sidebar.rs Normal file
View file

@ -0,0 +1,132 @@
use crate::constants::*;
use crate::graphics::vga_color as vga;
use crate::resources::Resources;
use bracket_lib::prelude::*;
pub fn draw(resources: &Resources, bterm: &mut BTerm) {
// Blue background
bterm.fill_region(
Rect {
x1: SIDEBAR_POS_X,
x2: SIDEBAR_POS_X + 14,
y1: SIDEBAR_POS_Y,
y2: SIDEBAR_POS_Y + 19,
},
to_cp437(' '),
RGB::named(vga::YELLOW_BRIGHT),
RGB::named(vga::BLUE),
);
// Gray number boxes
(1..17).step_by(3).for_each(|y| {
bterm.fill_region(
Rect {
x1: SIDEBAR_POS_X + 3,
x2: SIDEBAR_POS_X + 10,
y1: SIDEBAR_POS_Y + y,
y2: SIDEBAR_POS_Y + y + 1,
},
to_cp437(' '),
RGB::named(vga::RED),
RGB::named(vga::WHITE),
);
});
// Stats
bterm.print(SIDEBAR_POS_X + 4, SIDEBAR_POS_Y, "Score");
bterm.print(SIDEBAR_POS_X + 4, SIDEBAR_POS_Y + 3, "Level");
bterm.print_centered_at(
SIDEBAR_POS_X + 6,
SIDEBAR_POS_Y + 4,
resources.level_number + 1,
);
bterm.print(SIDEBAR_POS_X + 4, SIDEBAR_POS_Y + 6, "Gems");
bterm.print(SIDEBAR_POS_X + 4, SIDEBAR_POS_Y + 9, "Whips");
bterm.print(SIDEBAR_POS_X + 2, SIDEBAR_POS_Y + 12, "Teleports");
bterm.print(SIDEBAR_POS_X + 4, SIDEBAR_POS_Y + 15, "Keys");
let stats = &resources.stats;
bterm.print_centered_at(SIDEBAR_POS_X + 6, SIDEBAR_POS_Y + 1, stats.score * 10);
bterm.print_centered_at(SIDEBAR_POS_X + 6, SIDEBAR_POS_Y + 7, stats.gems);
bterm.print_centered_at(
SIDEBAR_POS_X + 6,
SIDEBAR_POS_Y + 10,
if stats.whip_power <= BASE_WHIP_POWER {
stats.whips.to_string()
} else {
format!("{}+{}", stats.whips, stats.whip_power - BASE_WHIP_POWER)
},
);
bterm.print_centered_at(SIDEBAR_POS_X + 6, SIDEBAR_POS_Y + 13, stats.teleports);
bterm.print_centered_at(SIDEBAR_POS_X + 6, SIDEBAR_POS_Y + 16, stats.keys);
// Hotkey list
bterm.print_color(
SIDEBAR_POS_X + 3,
SIDEBAR_POS_Y + 18,
RGB::named(vga::CYAN_BRIGHT),
RGB::named(vga::RED),
"OPTIONS",
);
bterm.fill_region(
Rect {
x1: SIDEBAR_POS_X,
x2: SIDEBAR_POS_X + 14,
y1: SIDEBAR_POS_Y + 19,
y2: SIDEBAR_POS_Y + 25,
},
to_cp437(' '),
RGB::named(vga::WHITE),
RGB::named(vga::BLUE),
);
bterm.fill_region(
Rect {
x1: SIDEBAR_POS_X + 3,
x2: SIDEBAR_POS_X + 4,
y1: SIDEBAR_POS_Y + 19,
y2: SIDEBAR_POS_Y + 25,
},
to_cp437(' '),
RGB::named(vga::WHITE_BRIGHT),
RGB::named(vga::BLUE),
);
bterm.print(SIDEBAR_POS_X + 3, SIDEBAR_POS_Y + 19, "Whip");
bterm.print(SIDEBAR_POS_X + 3, SIDEBAR_POS_Y + 20, "Teleport");
bterm.print(SIDEBAR_POS_X + 3, SIDEBAR_POS_Y + 21, "Pause");
if !cfg!(target_family = "wasm") {
bterm.print(SIDEBAR_POS_X + 3, SIDEBAR_POS_Y + 22, "Quit");
}
bterm.print(SIDEBAR_POS_X + 3, SIDEBAR_POS_Y + 23, "Save");
bterm.print(SIDEBAR_POS_X + 3, SIDEBAR_POS_Y + 24, "Restore");
if resources.show_debug_info {
bterm.print_color_right(
SIDEBAR_POS_X + 14,
SIDEBAR_POS_Y,
RGB::named(vga::GREEN_BRIGHT),
RGB::named(vga::BLACK),
&format!("{}", bterm.fps),
);
let mut debug_string = format!("{}", resources.clock.ticks);
if resources.speed_time_ticks > 0 {
debug_string += " SPEED"
}
if resources.slow_time_ticks > 0 {
debug_string += " SLOW"
}
bterm.print_color(
0,
0,
RGB::named(vga::YELLOW_BRIGHT),
RGB::named(vga::BLACK),
&debug_string,
);
}
}

51
src/graphics/whip.rs Normal file
View file

@ -0,0 +1,51 @@
use bracket_lib::prelude::*;
use hecs::World;
use crate::{components::*, constants::*, resources::*};
use super::{vga_color as vga, vga_color::get_by_index};
pub fn draw(world: &World, resources: &Resources, bterm: &mut BTerm) {
let mut rng = RandomNumberGenerator::new();
for (_, (position, wants_to_whip)) in &mut world.query::<(&Position, &WantsToWhip)>() {
let color = RGB::named(get_by_index(rng.range(1, 16)));
let mut rendered_frame = wants_to_whip.frame;
let frame_data = loop {
let frame_data = match rendered_frame {
0 => Some((-1, -1, '\\')),
1 => Some((-1, 0, '─')),
2 => Some((-1, 1, '/')),
3 => Some((0, 1, '│')),
4 => Some((1, 1, '\\')),
5 => Some((1, 0, '─')),
6 => Some((1, -1, '/')),
7 => Some((0, -1, '│')),
_ => None,
};
if let Some(data) = frame_data {
let dest = Point {
x: position.x + data.0,
y: position.y + data.1,
};
if resources.map.in_bounds(dest) {
break frame_data;
}
rendered_frame += 1;
if rendered_frame > 7 {
break None;
}
}
};
if let Some(data) = frame_data {
bterm.set(
(position.x + MAP_X as i32) + data.0,
(position.y + MAP_Y as i32) + data.1,
color,
RGB::named(vga::BLACK),
to_cp437(data.2),
);
};
}
}

106
src/input/mod.rs Normal file
View file

@ -0,0 +1,106 @@
use bracket_lib::prelude::*;
use hecs::World;
use crate::resources::{flashing_message::FlashingMessageIntent, *};
mod player;
pub fn handle_intent(bterm: &mut BTerm, _world: &mut World, resources: &mut Resources) {
if let Some(key) = bterm.key {
if let Some(flashing_message) = &resources.flashing_message {
if let Some(intent) = &flashing_message.intent {
match intent {
FlashingMessageIntent::Start => {
if resources.sound_output.is_none() || resources.sound_effects.is_none() {
let sound_output = SoundOutput::new();
resources.sound_effects = Some(SoundEffects::new(&sound_output));
resources.sound_output = Some(sound_output);
}
}
FlashingMessageIntent::Quit => {
if key == VirtualKeyCode::Y {
bterm.quit()
}
}
FlashingMessageIntent::Save => todo!(),
FlashingMessageIntent::Restore => todo!(),
FlashingMessageIntent::Restart => todo!(),
&FlashingMessageIntent::NextLevel => {
resources.should_advance_level = true;
}
}
}
}
}
}
pub fn handle(world: &mut World, resources: &mut Resources, bterm: &mut BTerm) {
if resources.flashing_message.is_some() && bterm.key.is_some() {
handle_intent(bterm, world, resources);
resources.flashing_message = None;
}
match bterm.key {
None => {}
Some(key) => match key {
VirtualKeyCode::Left | VirtualKeyCode::J | VirtualKeyCode::Numpad4 => {
player::try_move(-1, 0, world, resources);
}
VirtualKeyCode::U | VirtualKeyCode::Home | VirtualKeyCode::Numpad7 => {
player::try_move(-1, -1, world, resources)
}
VirtualKeyCode::Up | VirtualKeyCode::I | VirtualKeyCode::Numpad8 => {
player::try_move(0, -1, world, resources);
}
VirtualKeyCode::O | VirtualKeyCode::PageUp | VirtualKeyCode::Numpad9 => {
player::try_move(1, -1, world, resources)
}
VirtualKeyCode::Right | VirtualKeyCode::K | VirtualKeyCode::Numpad6 => {
player::try_move(1, 0, world, resources);
}
VirtualKeyCode::Comma | VirtualKeyCode::PageDown | VirtualKeyCode::Numpad3 => {
player::try_move(1, 1, world, resources)
}
VirtualKeyCode::Down | VirtualKeyCode::M | VirtualKeyCode::Numpad2 => {
player::try_move(0, 1, world, resources);
}
VirtualKeyCode::N | VirtualKeyCode::End | VirtualKeyCode::Numpad1 => {
player::try_move(-1, 1, world, resources)
}
VirtualKeyCode::W => {
player::whip(world, resources);
}
VirtualKeyCode::D => {
resources.show_debug_info = !resources.show_debug_info;
}
VirtualKeyCode::Escape | VirtualKeyCode::Q => {
if cfg!(not(target_family = "wasm")) {
resources.flashing_message = Some(FlashingMessage::new(
" Are you sure you want to quit (Y/N)? ",
Some(FlashingMessageIntent::Quit),
));
} else if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output.play_sound(sound_effects.bad_key.clone());
}
}
VirtualKeyCode::P => {
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output.play_sound(sound_effects.pause.clone());
}
resources.flashing_message =
Some(FlashingMessage::from(" Press any key to resume game. "));
}
_ => {
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output.play_sound(sound_effects.bad_key.clone());
}
}
},
}
}

301
src/input/player.rs Normal file
View file

@ -0,0 +1,301 @@
use instant::Instant;
use std::time::Duration;
use bracket_lib::prelude::*;
use hecs::{Entity, Without, World};
use crate::{
components::monster::*,
components::*,
constants::*,
resources::{flashing_message::FlashingMessageIntent, *},
systems,
tile_data::TileType,
};
pub fn try_move(delta_x: i32, delta_y: i32, world: &mut World, resources: &mut Resources) {
let mut to_kill: Vec<Entity> = Vec::new();
for (player_entity, (player, pos)) in
&mut world.query::<Without<(&mut Player, &mut Position), &WantsToWhip>>()
{
let now = Instant::now();
if now - player.last_moved > Duration::from_secs_f32(PLAYER_STEP_PERIOD) {
let destination = Point {
x: pos.x + delta_x,
y: pos.y + delta_y,
};
if resources.map.in_bounds(destination) {
if try_step(destination, world, resources) {
if let Some(monster_entity) = resources.map.get_tile_content_at(destination) {
if let Ok(monster) = world.get::<&Monster>(monster_entity) {
resources.stats.add_score(damage_for_kind(monster.kind));
resources.stats.take_gems(damage_for_kind(monster.kind));
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output
.play_sound(sound_effect_for_kind(monster.kind, sound_effects));
}
to_kill.push(monster_entity);
}
}
resources.map.clear_tile_content_at(Point::from(*pos));
pos.x = destination.x;
pos.y = destination.y;
resources
.map
.set_tile_content_at(destination, player_entity);
systems::time::force_tick(&mut resources.clock);
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output.play_sound(sound_effects.step.clone());
}
}
} else if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
if !resources.message_shown.touched_boundary {
resources.flashing_message = Some(FlashingMessage::from(
"An Electrified Wall blocks your way.",
));
resources.message_shown.touched_boundary = true;
}
let static_sound = sound_effects.get_new_static_effect(sound_output);
sound_output.play_sound(static_sound);
}
player.last_moved = now;
}
}
for e in to_kill {
let _ = world.despawn(e);
}
}
fn try_step(point: Point, _world: &World, resources: &mut Resources) -> bool {
match resources.map.get_tile_at(point) {
crate::tile_data::TileType::Floor
| crate::tile_data::TileType::Slow
| crate::tile_data::TileType::Medium
| crate::tile_data::TileType::Fast
| crate::tile_data::TileType::Player => true,
crate::tile_data::TileType::Block => {
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output.play_sound(sound_effects.blocked.clone());
}
if !resources.message_shown.touched_boundary {
resources.flashing_message = Some(FlashingMessage::from(
"An Electrified Wall blocks your way.",
));
resources.message_shown.touched_boundary = true;
}
if resources.stats.score > 2 {
resources.stats.take_score(2);
}
false
}
crate::tile_data::TileType::Wall => {
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output.play_sound(sound_effects.blocked.clone());
}
if !resources.message_shown.touched_boundary {
resources.flashing_message =
Some(FlashingMessage::from("A Solid Wall blocks your way."));
resources.message_shown.touched_boundary = true;
}
if resources.stats.score > 2 {
resources.stats.take_score(2);
}
false
}
crate::tile_data::TileType::Whip => {
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output.play_sound(sound_effects.grab.clone());
}
if !resources.message_shown.whip {
resources.flashing_message = Some(FlashingMessage::from("You found a Whip."));
resources.message_shown.whip = true;
}
resources.stats.give_whips(1);
resources.stats.add_score(1);
resources.map.set_tile_at(point, TileType::Floor);
true
}
crate::tile_data::TileType::Stairs => {
if !resources.message_shown.stairs {
resources.flashing_message = Some(FlashingMessage::new(
"Stairs take you to the next lower level.",
Some(FlashingMessageIntent::NextLevel),
));
resources.message_shown.stairs = true;
} else {
resources.should_advance_level = true;
}
true
}
crate::tile_data::TileType::Chest => todo!(),
crate::tile_data::TileType::SlowTime => {
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output.play_sound(sound_effects.slow_time.clone());
}
if !resources.message_shown.slow_time {
resources.flashing_message = Some(FlashingMessage::from(
"You activated a Slow Creature spell.",
));
resources.message_shown.slow_time = true;
}
resources.slow_time_ticks = 100;
resources.map.set_tile_at(point, TileType::Floor);
true
}
crate::tile_data::TileType::Gem => {
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output.play_sound(sound_effects.grab.clone());
}
if !resources.message_shown.gem {
resources.flashing_message = Some(FlashingMessage::from(
"Gems give you both points and strength.",
));
resources.message_shown.gem = true;
}
resources.stats.give_gems(1);
resources.stats.add_score(1);
resources.map.set_tile_at(point, TileType::Floor);
true
}
crate::tile_data::TileType::Invisible => todo!(),
crate::tile_data::TileType::Teleport => {
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output.play_sound(sound_effects.grab.clone());
}
if !resources.message_shown.teleport_scroll {
resources.flashing_message =
Some(FlashingMessage::from("You found a Teleport scroll."));
resources.message_shown.teleport_scroll = true;
}
resources.stats.give_teleports(1);
resources.stats.add_score(1);
resources.map.set_tile_at(point, TileType::Floor);
true
}
crate::tile_data::TileType::Key => todo!(),
crate::tile_data::TileType::Door => todo!(),
crate::tile_data::TileType::SpeedTime => {
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output.play_sound(sound_effects.speed_time.clone());
}
if !resources.message_shown.speed_time {
resources.flashing_message = Some(FlashingMessage::from(
"You activated a Speed Creature spell.",
));
resources.message_shown.speed_time = true;
}
resources.speed_time_ticks = 80;
resources.map.set_tile_at(point, TileType::Floor);
true
}
crate::tile_data::TileType::Trap => todo!(),
crate::tile_data::TileType::River => todo!(),
crate::tile_data::TileType::Power => todo!(),
crate::tile_data::TileType::Forest => todo!(),
crate::tile_data::TileType::Tree => todo!(),
crate::tile_data::TileType::Bomb => todo!(),
crate::tile_data::TileType::Lava => todo!(),
crate::tile_data::TileType::Pit => todo!(),
crate::tile_data::TileType::Tome => todo!(),
crate::tile_data::TileType::Tunnel => todo!(),
crate::tile_data::TileType::Freeze => todo!(),
crate::tile_data::TileType::Nugget => todo!(),
crate::tile_data::TileType::Quake => todo!(),
crate::tile_data::TileType::InvisibleBlock => todo!(),
crate::tile_data::TileType::InvisibleWall => todo!(),
crate::tile_data::TileType::InvisibleDoor => todo!(),
crate::tile_data::TileType::Stop => todo!(),
crate::tile_data::TileType::Zap => todo!(),
crate::tile_data::TileType::Create => todo!(),
crate::tile_data::TileType::Generator => todo!(),
crate::tile_data::TileType::Trap2 => todo!(),
crate::tile_data::TileType::Trap3 => todo!(),
crate::tile_data::TileType::Trap4 => todo!(),
crate::tile_data::TileType::Trap5 => todo!(),
crate::tile_data::TileType::Trap6 => todo!(),
crate::tile_data::TileType::Trap7 => todo!(),
crate::tile_data::TileType::Trap8 => todo!(),
crate::tile_data::TileType::Trap9 => todo!(),
crate::tile_data::TileType::Trap10 => todo!(),
crate::tile_data::TileType::Trap11 => todo!(),
crate::tile_data::TileType::Trap12 => todo!(),
crate::tile_data::TileType::Trap13 => todo!(),
crate::tile_data::TileType::Punctuation => todo!(),
crate::tile_data::TileType::Letter(_) => todo!(),
}
}
pub fn whip(world: &mut World, resources: &mut Resources) {
let mut to_add: Vec<Entity> = Vec::new();
for (entity, _) in world.query_mut::<Without<(&Player, &Position), &WantsToWhip>>() {
if resources.stats.whips > 0 {
to_add.push(entity);
}
}
for e in to_add {
let _ = world.insert_one(
e,
WantsToWhip {
frame: 0,
last_frame: Instant::now(),
sound: {
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
Some(sound_output.play_sound(sound_effects.whipping.clone()))
} else {
None
}
},
},
);
resources.stats.whips -= 1;
}
}

56
src/levels.rs Normal file
View file

@ -0,0 +1,56 @@
use std::collections::HashMap;
use crate::{constants::*, tile_data::TileType};
#[allow(clippy::large_enum_variant)]
pub enum Level {
Normal([&'static str; MAP_HEIGHT]),
Randomized(HashMap<TileType, u32>),
End,
}
pub fn get_level(index: u32) -> Level {
match index {
0 => Level::Randomized(HashMap::from([
(TileType::Slow, 15),
(TileType::Whip, 1),
(TileType::Stairs, 3),
(TileType::Gem, 8),
])),
1 => Level::Normal([
"LXXX2 2 2 2 2 2 2 2 2 2 2 2 2 +",
"+XXX 2 2 2 2 2 2 2 2 XXX ",
" XXX2 2 2 2 2 2 2 2 2 2 2 XTX ",
"+XXX 2 2 2 2 2 2 2 XXX ",
" XXX 2 2 2 2 2 2 2 2 2 2 ",
"+XXX 2 ",
" XXX 2 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 2 2 ",
"+XXX2 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 2 ",
" XXX 2 XXX2 W 2XXX 2 ",
"+XXX 2 XXX 2 FFFFF 2 XXX 2 2 ",
" XXX2 2 XXX F111F XXX ",
"+XXX2 XXX+ 3 3 W F1P1F W 3 3 +XXX 2 ",
"XXXX 2 XXX F111F XXX 2 2",
"WXXX 2 XXX 2 FFFFF 2 XXX 2 ",
"WXXX2 XXX2 W 2XXX 2 ",
"WXXX 2 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 2 ",
"WXXX 2 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 2 ",
"WXXX2 2 ",
"WXXX 2 2 2 2 2 2 2 2 2 2 2 ",
"XXXX 2 2 2 2 2 2 2 2 2 2 2 XXX ",
"XXXX2 2 2 2 2 2 2 2 2 2 2 2 XTX ",
"XXXX 2 2 2 2 2 2 2 2 2 2 2 2 XXX ",
"CXXX 2 2 2 2 2 2 2 2 2 2 2 2 2 2 +",
]),
2 => Level::Randomized(HashMap::from([
(TileType::Slow, 60),
(TileType::Block, 25),
(TileType::Whip, 5),
(TileType::Stairs, 2),
(TileType::Gem, 10),
(TileType::Teleport, 3),
])),
40 => Level::End,
_ => Level::Randomized(HashMap::new()),
}
}

34
src/lib.rs Normal file
View file

@ -0,0 +1,34 @@
#![allow(clippy::unused_unit)]
use std::panic;
use bracket_lib::prelude::*;
use state::State;
use wasm_bindgen::prelude::*;
pub mod components;
pub mod constants;
mod graphics;
pub mod input;
pub mod levels;
pub mod resources;
mod state;
pub mod systems;
pub mod tile_data;
#[wasm_bindgen(start)]
pub fn main_js() -> Result<(), JsValue> {
panic::set_hook(Box::new(console_error_panic_hook::hook));
let _ = main_common(false);
Ok(())
}
pub fn main_common(initialize_sound: bool) -> BError {
let context = BTermBuilder::vga(80, 25)
.with_fps_cap(60.0)
.with_title("Kroz")
.build()
.unwrap();
main_loop(context, State::new(initialize_sound))
}

View file

@ -2,156 +2,16 @@
pub mod components;
pub mod constants;
mod graphics;
pub mod input;
pub mod levels;
pub mod resources;
mod sidebar;
mod state;
pub mod systems;
pub mod vga_color;
pub mod tile_data;
use bracket_lib::prelude::*;
use components::{
monster::{color_for_kind, glyphs_for_kind, ticks_for_kind, MonsterKind},
Monster, Player, Position, Renderable,
};
use resources::map::TileType;
use resources::{Clock, LevelNumber, Map, ShowDebugInfo, SoundEffects, SoundOutput, Stats};
use specs::prelude::*;
use state::State;
use std::time::Instant;
use vga_color as vga;
fn main() -> BError {
let context = BTermBuilder::simple(80, 25)?
.with_fps_cap(60.0)
.with_title("Kroz")
.with_tile_dimensions(8, 16)
.build()?;
let mut ss = SoundOutput::new();
let sound_effects = SoundEffects::new(&ss);
ss.play_sound(sound_effects.startup.clone());
let mut ecs = World::new();
ecs.insert(ss);
ecs.insert(LevelNumber(0));
ecs.insert(ShowDebugInfo(false));
ecs.insert(Clock {
last_ticked: Instant::now(),
has_ticked: false,
ticks: 0,
});
ecs.insert(sound_effects);
ecs.insert(Stats {
score: 1290,
gems: 14,
whips: 7,
teleports: 0,
keys: 0,
});
ecs.register::<Position>();
ecs.register::<Renderable>();
ecs.register::<Monster>();
ecs.register::<Player>();
let mut map = Map::new();
let mut rng = RandomNumberGenerator::new();
for (i, tile) in &mut map.get_tiles().iter().enumerate() {
if rng.roll_dice(1, 16) < 2 && *tile == TileType::Floor {
let position = map.index_to_point2d(i);
let kind = MonsterKind::Slow;
ecs.create_entity()
.with(Position {
x: position.x,
y: position.y,
})
.with(Renderable {
glyph: *rng.random_slice_entry(&glyphs_for_kind(kind)).unwrap(),
fg: color_for_kind(kind),
bg: RGB::named(vga::BLACK),
})
.with(Monster {
kind,
ticks_until_move: ticks_for_kind(kind),
})
.build();
}
}
{
let entities = ecs.entities();
let positions = ecs.read_storage::<Position>();
let monsters = ecs.read_storage::<Monster>();
for (entity, _monster, pos) in (&entities, &monsters, &positions).join() {
map.set_tile_at(Point { x: pos.x, y: pos.y }, TileType::Monster(entity));
}
}
let player_start_pos = Point { x: 40, y: 22 };
ecs.create_entity()
.with(Position {
x: player_start_pos.x,
y: player_start_pos.y,
})
.with(Renderable {
glyph: to_cp437('☻'),
fg: RGB::named(vga::YELLOW_BRIGHT),
bg: RGB::named(vga::BLACK),
})
.with(Player {
last_moved: Instant::now(),
})
.build();
map.set_tile_at(player_start_pos, TileType::Player);
ecs.insert(map);
ecs.insert(Point::new(player_start_pos.x, player_start_pos.y));
// for i in 0..10 {
// gs.ecs
// .create_entity()
// .with(Position { x: i * 7, y: 20 })
// .with(Renderable {
// glyph: to_cp437('Ä'),
// fg: RGB::named(vga::RED_BRIGHT),
// bg: RGB::named(vga::BLACK),
// })
// .with(LeftMover {})
// .build();
// }
// let descent_sounds: Vec<Sound> = (20..100)
// .rev()
// .flat_map(|x| {
// (1..10).rev().flat_map(move |y| {
// vec![Sound {
// sound_type: SoundType::Tone(x * y * y),
// duration: Duration::from_millis((y as f64 / 1.5) as u64),
// }]
// })
// })
// .collect();
// let descent_effect = gs.sound_system.render_sound_effect(SoundEffect {
// sounds: descent_sounds,
// });
// let _ = gs.sound_system.play_sound(descent_effect);
// let effect = gs.sound_system.render_sound_effect(SoundEffect {
// sounds: vec![Sound {
// sound_type: SoundType::Tone(3500),
// duration: Duration::from_millis(4000),
// }],
// });
// let _ = gs.sound_system.play_sound(effect);
main_loop(context, State::new(ecs))
libkroz::main_common(true)
}

9
src/resources/clock.rs Normal file
View file

@ -0,0 +1,9 @@
use instant::Instant;
pub struct Clock {
pub last_ticked: Instant,
pub has_ticked: bool,
pub ticks: u128,
}
pub struct StopClock(pub bool);

View file

@ -0,0 +1,65 @@
use crate::constants::*;
pub enum Difficulty {
Novice,
Experienced,
Advanced,
Secret,
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash)]
pub struct DifficultySettings {
pub value: u32,
pub starting_gems: u32,
pub starting_whips: u32,
pub starting_teleports: u32,
pub starting_keys: u32,
pub starting_whip_power: u32,
}
impl From<&Difficulty> for DifficultySettings {
fn from(difficulty: &Difficulty) -> Self {
match difficulty {
Difficulty::Novice => NOVICE,
Difficulty::Experienced => EXPERIENCED,
Difficulty::Advanced => ADVANCED,
Difficulty::Secret => SECRET,
}
}
}
const SECRET: DifficultySettings = DifficultySettings {
value: 9,
starting_gems: 250,
starting_whips: 100,
starting_teleports: 50,
starting_keys: 1,
starting_whip_power: BASE_WHIP_POWER + 1,
};
const NOVICE: DifficultySettings = DifficultySettings {
value: 8,
starting_gems: 20,
starting_whips: 10,
starting_teleports: 0,
starting_keys: 0,
starting_whip_power: BASE_WHIP_POWER,
};
const EXPERIENCED: DifficultySettings = DifficultySettings {
value: 5,
starting_gems: 15,
starting_whips: 0,
starting_teleports: 0,
starting_keys: 0,
starting_whip_power: BASE_WHIP_POWER,
};
const ADVANCED: DifficultySettings = DifficultySettings {
value: 2,
starting_gems: 10,
starting_whips: 0,
starting_teleports: 0,
starting_keys: 0,
starting_whip_power: BASE_WHIP_POWER,
};

View file

@ -0,0 +1,48 @@
use instant::Instant;
use std::time::Duration;
use crate::constants::*;
pub enum FlashingMessageIntent {
Start,
Quit,
Save,
Restore,
Restart,
NextLevel,
}
pub struct FlashingMessage {
pub message: String,
pub color: usize,
pub last_changed_color: Instant,
pub intent: Option<FlashingMessageIntent>,
}
impl FlashingMessage {
pub fn new(message: &str, intent: Option<FlashingMessageIntent>) -> Self {
Self {
message: message.to_string(),
color: 14,
last_changed_color: Instant::now(),
intent,
}
}
pub fn next_color(&mut self) {
let now = Instant::now();
if now - self.last_changed_color > Duration::from_secs_f32(FLASHING_PERIOD) {
self.color += 1;
if self.color > 15 {
self.color = 13
}
self.last_changed_color = now;
}
}
}
impl From<&str> for FlashingMessage {
fn from(message: &str) -> Self {
Self::new(message, None)
}
}

View file

@ -1,23 +1,21 @@
use instant::Instant;
use crate::{
constants::{MAP_HEIGHT, MAP_SIZE, MAP_WIDTH, MAP_X, MAP_Y},
vga_color as vga,
components::{monster::*, Monster, Player, Position, Renderable},
constants::*,
graphics::vga_color as vga,
levels::Level,
tile_data::{self, TileType},
};
use bracket_lib::{prelude::*, random::RandomNumberGenerator};
use specs::Entity;
#[derive(PartialEq, Copy, Clone)]
pub enum TileType {
Player,
Monster(Entity),
Wall,
BreakableWall,
Floor,
}
use hecs::{Entity, World};
pub struct Map {
tiles: Vec<TileType>,
tile_content: Vec<Option<Entity>>,
border_fg: RGB,
border_bg: RGB,
gem_color: RGB,
}
impl BaseMap for Map {}
@ -36,29 +34,138 @@ impl Default for Map {
impl Map {
pub fn new() -> Self {
let mut tiles = vec![TileType::Floor; MAP_SIZE];
let mut rng = RandomNumberGenerator::new();
for tile in &mut tiles {
if rng.roll_dice(1, 16) < 2 {
*tile = TileType::Wall;
} else if rng.roll_dice(1, 16) < 2 {
*tile = TileType::BreakableWall;
}
}
Self {
tiles,
tiles: vec![TileType::Floor; MAP_SIZE],
tile_content: vec![None; MAP_SIZE],
border_fg: RGB::named(vga::get_by_index(rng.range(8, 15))),
border_bg: RGB::named(vga::get_by_index(rng.range(1, 7) as usize)),
gem_color: RGB::named(vga::get_by_index(rng.range(1, 15))),
}
}
pub fn spawn_entities(&mut self, world: &mut World) {
for (index, tile) in self
.tiles
.iter_mut()
.enumerate()
.collect::<Vec<(usize, &mut TileType)>>()
{
let point = Point::new(index % MAP_WIDTH, index / MAP_WIDTH);
match tile {
TileType::Player => {
let entity = world.spawn((
Player {
last_moved: Instant::now(),
},
Position {
x: point.x,
y: point.y,
},
Renderable {
glyph: to_cp437('☻'),
fg: RGB::named(vga::YELLOW_BRIGHT),
bg: RGB::named(vga::BLACK),
},
));
self.tile_content[index] = Some(entity);
}
TileType::Slow => {
let mut rng = RandomNumberGenerator::new();
let entity = world.spawn((
Monster {
kind: MonsterKind::Slow,
ticks_until_move: ticks_for_kind(MonsterKind::Slow),
},
Position {
x: point.x,
y: point.y,
},
Renderable {
glyph: *rng
.random_slice_entry(&glyphs_for_kind(MonsterKind::Slow))
.unwrap(),
fg: color_for_kind(MonsterKind::Slow),
bg: RGB::named(vga::BLACK),
},
));
self.tile_content[index] = Some(entity);
}
TileType::Medium => {
let mut rng = RandomNumberGenerator::new();
let entity = world.spawn((
Monster {
kind: MonsterKind::Medium,
ticks_until_move: ticks_for_kind(MonsterKind::Medium),
},
Position {
x: point.x,
y: point.y,
},
Renderable {
glyph: *rng
.random_slice_entry(&glyphs_for_kind(MonsterKind::Medium))
.unwrap(),
fg: color_for_kind(MonsterKind::Medium),
bg: RGB::named(vga::BLACK),
},
));
self.tile_content[index] = Some(entity);
}
TileType::Fast => {
let mut rng = RandomNumberGenerator::new();
let entity = world.spawn((
Monster {
kind: MonsterKind::Fast,
ticks_until_move: ticks_for_kind(MonsterKind::Fast),
},
Position {
x: point.x,
y: point.y,
},
Renderable {
glyph: *rng
.random_slice_entry(&glyphs_for_kind(MonsterKind::Fast))
.unwrap(),
fg: color_for_kind(MonsterKind::Fast),
bg: RGB::named(vga::BLACK),
},
));
self.tile_content[index] = Some(entity);
}
_ => {}
}
}
}
pub fn clear_all_tile_content(&mut self) {
self.tile_content.iter_mut().for_each(|tile| {
*tile = None;
});
}
pub fn get_tile_content_at(&self, point: Point) -> Option<Entity> {
let index = self.point2d_to_index(point);
self.tile_content[index]
}
pub fn set_tile_content_at(&mut self, point: Point, entity: Entity) {
let index = self.point2d_to_index(point);
self.tile_content[index] = Some(entity);
}
pub fn clear_tile_content_at(&mut self, point: Point) {
let index = self.point2d_to_index(point);
self.tile_content[index] = None;
}
pub fn get_tiles(&self) -> &Vec<TileType> {
&self.tiles
}
pub fn draw(&self, ctx: &mut BTerm) {
pub fn draw(&self, bterm: &mut BTerm) {
// Border
ctx.fill_region(
bterm.fill_region(
Rect {
x1: MAP_X as i32 - 1,
x2: MAP_WIDTH as i32 + MAP_X as i32 + 1,
@ -74,44 +181,18 @@ impl Map {
let point = self.index_to_point2d(i);
let (x, y) = (point.x as usize, point.y as usize);
match tile {
TileType::Player | TileType::Monster(_) => {
ctx.set(
x + MAP_X,
y + MAP_Y,
RGB::named(vga::BLACK),
RGB::named(vga::BLACK),
to_cp437(' '),
);
}
TileType::Floor => {
ctx.set(
x + MAP_X,
y + MAP_Y,
RGB::named(vga::BLACK),
RGB::named(vga::BLACK),
to_cp437(' '),
);
}
TileType::BreakableWall => {
ctx.set(
x + MAP_X,
y + MAP_Y,
RGB::named(vga::YELLOW),
RGB::named(vga::BLACK),
to_cp437('▓'),
);
}
TileType::Wall => {
ctx.set(
x + MAP_X,
y + MAP_Y,
RGB::named(vga::YELLOW),
RGB::named(vga::BLACK),
to_cp437('█'),
);
}
}
let data = tile_data::tile_data(*tile);
bterm.set(
x + MAP_X,
y + MAP_Y,
if *tile == TileType::Gem {
self.gem_color
} else {
RGB::named(data.color_fg)
},
data.color_bg,
data.glyph,
);
}
}
@ -119,15 +200,68 @@ impl Map {
self.tiles[self.point2d_to_index(point)]
}
pub fn get_tile_at_mut(&mut self, point: Point) -> &mut TileType {
let index = self.point2d_to_index(point);
&mut self.tiles[index]
}
pub fn set_tile_at(&mut self, point: Point, tile: TileType) {
let index = self.point2d_to_index(point);
self.tiles[index] = tile;
}
}
pub fn is_solid(&self, point: Point) -> bool {
matches!(
self.get_tile_at(point),
TileType::Wall | TileType::BreakableWall
)
impl From<Level> for Map {
fn from(level: Level) -> Self {
match level {
Level::Normal(data) => {
assert_eq!(data.len(), MAP_HEIGHT, "Level data is incorrect height!");
let mut map = Self::new();
for (y, line) in data.iter().enumerate() {
assert_eq!(line.len(), MAP_WIDTH, "Level data is incorrect width!");
for (x, c) in line.chars().enumerate() {
map.set_tile_at(
Point {
x: x as i32,
y: y as i32,
},
TileType::from(c),
);
}
}
map
}
Level::Randomized(data) => {
let mut rng = RandomNumberGenerator::new();
let mut map = Self::new();
for (tile, count) in data {
for _ in 0..count {
loop {
let point = Point {
x: rng.range(0, MAP_WIDTH as i32),
y: rng.range(0, MAP_HEIGHT as i32),
};
if map.get_tile_at(point) == TileType::Floor {
map.set_tile_at(point, tile);
break;
}
}
}
}
loop {
let point = Point {
x: rng.range(0, MAP_WIDTH as i32),
y: rng.range(0, MAP_HEIGHT as i32),
};
if map.get_tile_at(point) == TileType::Floor {
map.set_tile_at(point, TileType::Player);
break;
}
}
map
}
Level::End => todo!(),
}
}
}

View file

@ -0,0 +1,24 @@
#[derive(Debug, Default)]
pub struct MessageShown {
pub touched_boundary: bool,
pub slow_time: bool,
pub speed_time: bool,
pub whip: bool,
pub gem: bool,
pub teleport_scroll: bool,
pub stairs: bool,
}
impl MessageShown {
pub fn all_shown() -> Self {
MessageShown {
touched_boundary: true,
slow_time: true,
speed_time: true,
whip: true,
gem: true,
teleport_scroll: true,
stairs: true,
}
}
}

View file

@ -1,50 +1,36 @@
pub mod clock;
pub mod difficulty;
pub mod flashing_message;
pub mod map;
pub mod message_shown;
pub mod sound_effects;
pub mod sound_output;
pub mod stats;
use bracket_lib::prelude::*;
pub use clock::{Clock, StopClock};
pub use difficulty::DifficultySettings;
pub use flashing_message::FlashingMessage;
pub use map::Map;
pub use message_shown::MessageShown;
pub use sound_effects::SoundEffects;
pub use sound_output::SoundOutput;
pub use stats::Stats;
use crate::constants::CLOCK_PERIOD;
use std::time::{Duration, Instant};
#[derive(Default)]
pub struct LevelNumber(pub u32);
#[derive(Default)]
pub struct ShowDebugInfo(pub bool);
pub struct Clock {
pub last_ticked: Instant,
pub has_ticked: bool,
pub ticks: u128,
}
impl Clock {
pub fn try_tick(&mut self) {
if Instant::now() - self.last_ticked > Duration::from_secs_f32(CLOCK_PERIOD) {
self.tick();
} else {
self.has_ticked = false;
}
}
pub fn force_tick(&mut self) {
self.tick();
}
fn tick(&mut self) {
self.has_ticked = true;
self.last_ticked = Instant::now();
self.ticks += 1;
}
}
pub struct Stats {
pub score: u32,
pub gems: u32,
pub whips: u32,
pub teleports: u32,
pub keys: u32,
pub struct Resources {
pub level_number: u32,
pub show_debug_info: bool,
pub player_input: Option<VirtualKeyCode>,
pub stats: Stats,
pub clock: Clock,
pub stop_clock: bool,
pub map: Map,
pub difficulty: Option<DifficultySettings>,
pub sound_effects: Option<SoundEffects>,
pub sound_output: Option<SoundOutput>,
pub flashing_message: Option<FlashingMessage>,
pub message_shown: MessageShown,
pub should_advance_level: bool,
pub speed_time_ticks: u32,
pub slow_time_ticks: u32,
}

View file

@ -1,4 +1,4 @@
use std::{array, iter, time::Duration};
use std::{cmp, iter, time::Duration};
use bracket_lib::random::RandomNumberGenerator;
@ -26,29 +26,39 @@ pub struct SoundEffect {
pub struct SoundEffects {
pub startup: SoundSamples,
pub step: SoundSamples,
pub pickup: SoundSamples,
pub grab: SoundSamples,
pub bad_key: SoundSamples,
pub blocked: SoundSamples,
pub whipping: SoundSamples,
pub whipping_hit: SoundSamples,
pub whipping_hit_enemy: SoundSamples,
pub whipping_hit_block: SoundSamples,
pub slow_hit: SoundSamples,
pub medium_hit: SoundSamples,
pub fast_hit: SoundSamples,
pub pause: SoundSamples,
pub speed_time: SoundSamples,
pub slow_time: SoundSamples,
rng: RandomNumberGenerator,
}
impl SoundEffects {
pub fn new(ss: &SoundOutput) -> Self {
pub fn new(sound_output: &SoundOutput) -> Self {
let mut rng = RandomNumberGenerator::new();
Self {
startup: ss.render_sound_effect(&SoundEffect {
sounds: (30..400)
.step_by(8)
startup: sound_output.render_sound_effect(&SoundEffect {
sounds: (1..800)
.map(|x| Sound {
sound_type: SoundType::Tone(x),
duration: Duration::from_millis(24),
sound_type: SoundType::Tone(x / 2),
duration: Duration::from_millis(1),
})
.collect(),
}),
step: ss.render_sound_effect(&SoundEffect {
step: sound_output.render_sound_effect(&SoundEffect {
sounds: vec![
Sound {
sound_type: SoundType::Noise(350, 900),
duration: Duration::from_millis(6),
duration: Duration::from_millis(5),
},
Sound {
sound_type: SoundType::Silence,
@ -60,7 +70,7 @@ impl SoundEffects {
},
],
}),
pickup: ss.render_sound_effect(&SoundEffect {
grab: sound_output.render_sound_effect(&SoundEffect {
sounds: vec![
Sound {
sound_type: SoundType::Noise(350, 900),
@ -76,13 +86,13 @@ impl SoundEffects {
},
],
}),
bad_key: ss.render_sound_effect(&SoundEffect {
bad_key: sound_output.render_sound_effect(&SoundEffect {
sounds: iter::once(Sound {
sound_type: SoundType::Tone(400),
duration: Duration::from_millis(20),
sound_type: SoundType::Tone(540),
duration: Duration::from_millis(40),
})
.chain((0..4).flat_map(|_| {
array::IntoIter::new([
[
Sound {
sound_type: SoundType::Tone(100),
duration: Duration::from_millis(15),
@ -91,11 +101,11 @@ impl SoundEffects {
sound_type: SoundType::Silence,
duration: Duration::from_millis(15),
},
])
]
}))
.collect(),
}),
blocked: ss.render_sound_effect(&SoundEffect {
blocked: sound_output.render_sound_effect(&SoundEffect {
sounds: (30..=60)
.rev()
.step_by(6)
@ -105,7 +115,83 @@ impl SoundEffects {
})
.collect(),
}),
rng: RandomNumberGenerator::new(),
whipping: sound_output.render_sound_effect(&SoundEffect {
sounds: vec![Sound {
sound_type: SoundType::Tone(70),
duration: Duration::from_secs(3),
}],
}),
whipping_hit: sound_output.render_sound_effect(&SoundEffect {
sounds: vec![Sound {
sound_type: SoundType::Tone(90),
duration: Duration::from_secs(3),
}],
}),
whipping_hit_enemy: sound_output.render_sound_effect(&SoundEffect {
sounds: vec![Sound {
sound_type: SoundType::Tone(400),
duration: Duration::from_millis(20),
}],
}),
whipping_hit_block: sound_output.render_sound_effect(&SoundEffect {
sounds: (20_i32..=5700_i32)
.rev()
.step_by(5)
.map(|x| Sound {
sound_type: SoundType::Tone(cmp::max(0, rng.range(0, x * 2) - x) as u32),
duration: Duration::from_micros(665),
})
.collect(),
}),
slow_hit: sound_output.render_sound_effect(&SoundEffect {
sounds: vec![Sound {
sound_type: SoundType::Tone(400),
duration: Duration::from_millis(25),
}],
}),
medium_hit: sound_output.render_sound_effect(&SoundEffect {
sounds: vec![Sound {
sound_type: SoundType::Tone(600),
duration: Duration::from_millis(25),
}],
}),
fast_hit: sound_output.render_sound_effect(&SoundEffect {
sounds: vec![Sound {
sound_type: SoundType::Tone(800),
duration: Duration::from_millis(25),
}],
}),
pause: sound_output.render_sound_effect(&SoundEffect {
sounds: {
let mut sounds = vec![Sound {
sound_type: SoundType::Tone(500),
duration: Duration::from_millis(100),
}];
sounds.extend((100..=200).rev().step_by(10).map(|x| Sound {
sound_type: SoundType::Tone(x),
duration: Duration::from_millis(20),
}));
sounds
},
}),
speed_time: sound_output.render_sound_effect(&SoundEffect {
sounds: (1..=7)
.map(|x| Sound {
sound_type: SoundType::Tone(x * 50 + 300),
duration: Duration::from_millis(x as u64 * 10 + 40),
})
.collect(),
}),
slow_time: sound_output.render_sound_effect(&SoundEffect {
sounds: (1..=7)
.rev()
.map(|x| Sound {
sound_type: SoundType::Tone(x * 50 + 300),
duration: Duration::from_millis(x as u64 * 10 + 40),
})
.collect(),
}),
rng,
}
}

View file

@ -1,15 +1,16 @@
use std::{f32::consts::PI, sync::Arc};
use std::sync::Arc;
use cpal::{
traits::{DeviceTrait, HostTrait, StreamTrait},
SampleRate, Stream,
};
use oddio::{Frames, Handle, Mixer};
use oddio::{Frames, FramesSignal, Gain, Handle, Mixer, MonoToStereo, Stop};
use rand::Rng;
use super::sound_effects::{SoundEffect, SoundType};
pub type SoundSamples = Arc<Frames<f32>>;
pub type SoundEffectHandle = Handle<Stop<MonoToStereo<Gain<FramesSignal<f32>>>>>;
pub struct SoundOutput {
mixer_handle: Handle<Mixer<[f32; 2]>>,
@ -60,41 +61,54 @@ impl SoundOutput {
}
pub fn render_sound_effect(&self, effect: &SoundEffect) -> SoundSamples {
// Keep these outside the loop to remember phase
let mut half_cycle_counter: u32 = 0;
let mut speaker_out: bool = false;
let effect_buffer: Vec<f32> = effect
.sounds
.iter()
.flat_map(|sound| match sound.sound_type {
SoundType::Silence => (0
..(self.sample_rate.0 as f32 * sound.duration.as_secs_f32()) as usize)
.map(|_| 0f32)
.collect::<Vec<f32>>(),
SoundType::Silence => {
// Reset phase on silence
half_cycle_counter = 0;
speaker_out = false;
(0..(self.sample_rate.0 as f32 * sound.duration.as_secs_f32()) as usize)
.map(|_| 0f32)
.collect::<Vec<f32>>()
}
SoundType::Tone(freq) => {
// A frequency of 0 is silence
if freq == 0 {
half_cycle_counter = 0;
speaker_out = false;
return (0..(self.sample_rate.0 as f32 * sound.duration.as_secs_f32())
as usize)
.map(|_| 0f32)
.collect::<Vec<f32>>();
}
let num_harmonics = self.sample_rate.0 / (freq as u32 * 2);
let coefficients = (0..=num_harmonics)
.map(|i| {
if i == 0 {
return 0.0;
}
(i as f32 * 0.5 * PI).sin() * 2.0 / (i as f32 * PI)
})
.collect::<Vec<f32>>();
let scaler = freq as f32 * PI * 2.0 / self.sample_rate.0 as f32;
(0..(self.sample_rate.0 as f32 * sound.duration.as_secs_f32()) as usize)
.map(|i| {
let temp = scaler * i as f32;
coefficients
.iter()
.enumerate()
.map(|(j, coef)| coef * (j as f32 * temp).cos())
.sum::<f32>()
})
.collect::<Vec<f32>>()
let mut buffer: Vec<f32> = vec![
0.;
(self.sample_rate.0 as f32 * sound.duration.as_secs_f32())
as usize
];
let half_cycle_counter_upper_bound: u32 = self.sample_rate.0 / freq;
for sample in &mut buffer {
if speaker_out {
*sample = 0.75;
}
half_cycle_counter += 2;
if half_cycle_counter >= half_cycle_counter_upper_bound {
half_cycle_counter %= half_cycle_counter_upper_bound;
speaker_out = !speaker_out;
}
}
buffer
}
SoundType::Noise(min, max) => {
(0..(self.sample_rate.0 as f32 * sound.duration.as_secs_f32()) as usize)
@ -114,12 +128,11 @@ impl SoundOutput {
oddio::Frames::from_iter(self.sample_rate.0, effect_buffer.iter().copied())
}
pub fn play_sound(&mut self, samples: SoundSamples) {
pub fn play_sound(&mut self, samples: SoundSamples) -> SoundEffectHandle {
let mut gain = oddio::Gain::new(oddio::FramesSignal::from(samples));
gain.set_gain(-10.0);
self.mixer_handle
.control::<oddio::Mixer<_>, _>()
.play(oddio::MonoToStereo::new(oddio::Gain::new(
oddio::FramesSignal::from(samples),
0.20,
)));
.play(oddio::MonoToStereo::new(gain))
}
}

74
src/resources/stats.rs Normal file
View file

@ -0,0 +1,74 @@
pub struct Stats {
pub score: u32,
pub gems: u32,
pub whips: u32,
pub whip_power: u32,
pub teleports: u32,
pub keys: u32,
}
type PlayerSurvived = bool;
impl Stats {
pub fn add_score(&mut self, score: u32) {
self.score += score;
}
pub fn take_score(&mut self, score: u32) {
if let Some(result) = self.score.checked_sub(score) {
self.score = result;
} else {
self.score = 0;
}
}
pub fn give_gems(&mut self, num_gems: u32) {
self.gems += num_gems;
}
pub fn take_gems(&mut self, num_gems: u32) -> PlayerSurvived {
if let Some(result) = self.gems.checked_sub(num_gems) {
self.gems = result;
true
} else {
self.gems = 0;
false
}
}
pub fn give_whips(&mut self, num_whips: u32) {
self.whips += num_whips;
}
pub fn take_whips(&mut self, num_whips: u32) {
if let Some(result) = self.whips.checked_sub(num_whips) {
self.whips = result;
} else {
self.whips = 0;
}
}
pub fn give_teleports(&mut self, num_teleports: u32) {
self.teleports += num_teleports;
}
pub fn take_teleports(&mut self, num_teleports: u32) {
if let Some(result) = self.teleports.checked_sub(num_teleports) {
self.teleports = result;
} else {
self.teleports = 0;
}
}
pub fn give_keys(&mut self, num_keys: u32) {
self.keys += num_keys;
}
pub fn take_keys(&mut self, num_keys: u32) {
if let Some(result) = self.keys.checked_sub(num_keys) {
self.keys = result;
} else {
self.keys = 0;
}
}
}

View file

@ -1,113 +0,0 @@
use crate::constants::{SIDEBAR_POS_X, SIDEBAR_POS_Y};
use crate::resources::{Clock, LevelNumber, ShowDebugInfo, Stats};
use crate::vga_color as vga;
use bracket_lib::prelude::*;
use specs::prelude::*;
pub fn draw(ecs: &World, ctx: &mut BTerm) {
// Blue background
ctx.fill_region(
Rect {
x1: SIDEBAR_POS_X,
x2: SIDEBAR_POS_X + 14,
y1: SIDEBAR_POS_Y,
y2: SIDEBAR_POS_Y + 19,
},
to_cp437(' '),
RGB::named(vga::YELLOW_BRIGHT),
RGB::named(vga::BLUE),
);
// Gray number boxes
(1..17).step_by(3).for_each(|y| {
ctx.fill_region(
Rect {
x1: SIDEBAR_POS_X + 3,
x2: SIDEBAR_POS_X + 10,
y1: SIDEBAR_POS_Y + y,
y2: SIDEBAR_POS_Y + y + 1,
},
to_cp437(' '),
RGB::named(vga::RED),
RGB::named(vga::WHITE),
);
});
// Stats
ctx.print(SIDEBAR_POS_X + 4, SIDEBAR_POS_Y, "Score");
ctx.print(SIDEBAR_POS_X + 4, SIDEBAR_POS_Y + 3, "Level");
ctx.print_centered_at(
SIDEBAR_POS_X + 6,
SIDEBAR_POS_Y + 4,
ecs.read_resource::<LevelNumber>().0,
);
ctx.print(SIDEBAR_POS_X + 4, SIDEBAR_POS_Y + 6, "Gems");
ctx.print(SIDEBAR_POS_X + 4, SIDEBAR_POS_Y + 9, "Whips");
ctx.print(SIDEBAR_POS_X + 2, SIDEBAR_POS_Y + 12, "Teleports");
ctx.print(SIDEBAR_POS_X + 4, SIDEBAR_POS_Y + 15, "Keys");
let stats = ecs.read_resource::<Stats>();
ctx.print_centered_at(SIDEBAR_POS_X + 6, SIDEBAR_POS_Y + 1, stats.score);
ctx.print_centered_at(SIDEBAR_POS_X + 6, SIDEBAR_POS_Y + 7, stats.gems);
ctx.print_centered_at(SIDEBAR_POS_X + 6, SIDEBAR_POS_Y + 10, stats.whips);
ctx.print_centered_at(SIDEBAR_POS_X + 6, SIDEBAR_POS_Y + 13, stats.teleports);
ctx.print_centered_at(SIDEBAR_POS_X + 6, SIDEBAR_POS_Y + 16, stats.keys);
// Hotkey list
ctx.print_color(
SIDEBAR_POS_X + 3,
SIDEBAR_POS_Y + 18,
RGB::named(vga::CYAN_BRIGHT),
RGB::named(vga::RED),
"OPTIONS",
);
ctx.fill_region(
Rect {
x1: SIDEBAR_POS_X,
x2: SIDEBAR_POS_X + 14,
y1: SIDEBAR_POS_Y + 19,
y2: SIDEBAR_POS_Y + 25,
},
to_cp437(' '),
RGB::named(vga::WHITE),
RGB::named(vga::BLUE),
);
ctx.fill_region(
Rect {
x1: SIDEBAR_POS_X + 3,
x2: SIDEBAR_POS_X + 4,
y1: SIDEBAR_POS_Y + 19,
y2: SIDEBAR_POS_Y + 25,
},
to_cp437(' '),
RGB::named(vga::WHITE_BRIGHT),
RGB::named(vga::BLUE),
);
ctx.print(SIDEBAR_POS_X + 3, SIDEBAR_POS_Y + 19, "Whip");
ctx.print(SIDEBAR_POS_X + 3, SIDEBAR_POS_Y + 20, "Teleport");
ctx.print(SIDEBAR_POS_X + 3, SIDEBAR_POS_Y + 21, "Pause");
ctx.print(SIDEBAR_POS_X + 3, SIDEBAR_POS_Y + 22, "Quit");
ctx.print(SIDEBAR_POS_X + 3, SIDEBAR_POS_Y + 23, "Save");
ctx.print(SIDEBAR_POS_X + 3, SIDEBAR_POS_Y + 24, "Restore");
if ecs.read_resource::<ShowDebugInfo>().0 {
ctx.print_color_right(
SIDEBAR_POS_X + 14,
SIDEBAR_POS_Y,
RGB::named(vga::GREEN_BRIGHT),
RGB::named(vga::BLACK),
&format!("{}", ctx.fps),
);
ctx.print_color(
0,
0,
RGB::named(vga::YELLOW_BRIGHT),
RGB::named(vga::BLACK),
&format!("{}", ecs.read_resource::<Clock>().ticks),
);
}
}

View file

@ -1,152 +1,101 @@
use std::time::{Duration, Instant};
use instant::Instant;
use crate::components::monster::damage_for_kind;
use crate::components::{Monster, Player, Position, Renderable};
use crate::resources::map::TileType;
use crate::resources::{Clock, Map, ShowDebugInfo, SoundEffects, SoundOutput, Stats};
use crate::systems::MonsterMotion;
use crate::{constants::*, sidebar};
use crate::resources::clock::Clock;
use crate::resources::flashing_message::{FlashingMessage, FlashingMessageIntent};
use crate::resources::sound_effects::SoundEffects;
use crate::resources::stats::Stats;
use crate::resources::{difficulty::*, MessageShown};
use crate::resources::{Map, Resources, SoundOutput};
use crate::{graphics, input, levels, systems};
use bracket_lib::prelude::*;
use specs::prelude::*;
use hecs::World;
pub struct State {
ecs: World,
world: World,
resources: Resources,
}
impl GameState for State {
fn tick(&mut self, ctx: &mut BTerm) {
ctx.cls();
fn tick(&mut self, bterm: &mut BTerm) {
input::handle(&mut self.world, &mut self.resources, bterm);
systems::run(&mut self.world, &mut self.resources);
graphics::draw(&self.world, &mut self.resources, bterm);
self.handle_input(ctx);
self.run_systems();
let map = self.ecs.fetch::<Map>();
map.draw(ctx);
let positions = self.ecs.read_storage::<Position>();
let renderables = self.ecs.read_storage::<Renderable>();
for (pos, render) in (&positions, &renderables).join() {
ctx.set(
pos.x + MAP_X as i32,
pos.y + MAP_Y as i32,
render.fg,
render.bg,
render.glyph,
);
if self.resources.should_advance_level {
self.next_level();
}
sidebar::draw(&self.ecs, ctx);
}
}
impl State {
pub fn new(ecs: World) -> Self {
State { ecs }
}
#[allow(dead_code)]
pub fn new(initialize_sound: bool) -> Self {
let mut sound_output = if initialize_sound {
Some(SoundOutput::new())
} else {
None
};
fn handle_input(&mut self, ctx: &mut BTerm) {
// Player movement
match ctx.key {
None => {} // Nothing happened
Some(key) => match key {
VirtualKeyCode::Left | VirtualKeyCode::J => {
self.try_move_player(-1, 0);
}
VirtualKeyCode::U | VirtualKeyCode::Home => self.try_move_player(-1, -1),
VirtualKeyCode::Up | VirtualKeyCode::I => {
self.try_move_player(0, -1);
}
VirtualKeyCode::O | VirtualKeyCode::PageUp => self.try_move_player(1, -1),
VirtualKeyCode::Right | VirtualKeyCode::K => {
self.try_move_player(1, 0);
}
VirtualKeyCode::Comma | VirtualKeyCode::PageDown => self.try_move_player(1, 1),
VirtualKeyCode::Down | VirtualKeyCode::M => {
self.try_move_player(0, 1);
}
VirtualKeyCode::N | VirtualKeyCode::End => self.try_move_player(-1, 1),
VirtualKeyCode::S => {
let mut sound_system = self.ecs.write_resource::<SoundOutput>();
let sound_effects = self.ecs.fetch::<SoundEffects>();
sound_system.play_sound(sound_effects.pickup.clone());
}
VirtualKeyCode::D => {
let mut show_debug_info = self.ecs.write_resource::<ShowDebugInfo>();
show_debug_info.0 = !show_debug_info.0;
}
VirtualKeyCode::Escape => {
ctx.quit();
}
_ => {
let mut sound_system = self.ecs.write_resource::<SoundOutput>();
let sound_effects = self.ecs.fetch::<SoundEffects>();
sound_system.play_sound(sound_effects.bad_key.clone());
}
let sound_effects = sound_output.as_ref().map(SoundEffects::new);
if let (Some(so), Some(se)) = (&mut sound_output, &sound_effects) {
so.play_sound(se.startup.clone());
}
let starting_level = 0;
let selected_difficulty = Difficulty::Secret;
let difficulty_settings = DifficultySettings::from(&selected_difficulty);
let mut world = World::new();
let mut map = Map::from(levels::get_level(starting_level));
map.spawn_entities(&mut world);
let resources = Resources {
level_number: starting_level,
show_debug_info: false,
player_input: None,
stats: Stats {
score: 0,
gems: difficulty_settings.starting_gems,
whips: difficulty_settings.starting_whips,
whip_power: difficulty_settings.starting_whip_power,
teleports: difficulty_settings.starting_teleports,
keys: difficulty_settings.starting_keys,
},
}
clock: Clock {
last_ticked: Instant::now(),
has_ticked: false,
ticks: 0,
},
stop_clock: false,
map,
sound_effects,
sound_output,
difficulty: Some(difficulty_settings),
flashing_message: Some(FlashingMessage::new(
"Press any key to begin this level.",
Some(FlashingMessageIntent::Start),
)),
message_shown: match selected_difficulty {
Difficulty::Novice | Difficulty::Experienced => Default::default(),
_ => MessageShown::all_shown(),
},
should_advance_level: false,
speed_time_ticks: 0,
slow_time_ticks: 0,
};
State { world, resources }
}
fn try_move_player(&mut self, delta_x: i32, delta_y: i32) {
let entities = self.ecs.entities();
let mut positions = self.ecs.write_storage::<Position>();
let mut players = self.ecs.write_storage::<Player>();
let mut map = self.ecs.write_resource::<Map>();
let mut stats = self.ecs.write_resource::<Stats>();
let mut sound_system = self.ecs.write_resource::<SoundOutput>();
fn next_level(&mut self) {
self.resources.level_number += 1;
for (player, pos) in (&mut players, &mut positions).join() {
let now = Instant::now();
if now - player.last_moved > Duration::from_secs_f32(PLAYER_STEP_PERIOD) {
let destination = Point {
x: pos.x + delta_x,
y: pos.y + delta_y,
};
self.world.clear();
self.resources.map = Map::from(levels::get_level(self.resources.level_number));
self.resources.map.spawn_entities(&mut self.world);
let mut sound_effects = self.ecs.fetch_mut::<SoundEffects>();
if map.in_bounds(destination) {
if map.is_solid(destination) {
sound_system.play_sound(sound_effects.blocked.clone());
} else {
if let TileType::Monster(monster) = map.get_tile_at(destination) {
if let Some(monster_component) =
self.ecs.read_component::<Monster>().get(monster)
{
if stats.gems > 0 {
stats.gems -= damage_for_kind(monster_component.kind);
}
let _ = entities.delete(monster);
}
}
map.set_tile_at(Point { x: pos.x, y: pos.y }, TileType::Floor);
map.set_tile_at(destination, TileType::Player);
pos.x = destination.x;
pos.y = destination.y;
let mut player_pos = self.ecs.write_resource::<Point>();
player_pos.x = pos.x;
player_pos.y = pos.y;
self.ecs.write_resource::<Clock>().force_tick();
sound_system.play_sound(sound_effects.step.clone());
}
} else {
let static_sound = sound_effects.get_new_static_effect(&sound_system);
sound_system.play_sound(static_sound);
}
player.last_moved = now;
}
}
}
fn run_systems(&mut self) {
let mut mm = MonsterMotion {};
mm.run_now(&self.ecs);
self.ecs.maintain();
self.ecs.write_resource::<Clock>().try_tick();
self.resources.should_advance_level = false;
}
}

View file

@ -1,3 +1,15 @@
pub mod monster_motion;
pub mod monster_ai;
pub mod powerups;
pub mod time;
pub mod whip;
pub use monster_motion::MonsterMotion;
use hecs::World;
use crate::resources::Resources;
pub fn run(world: &mut World, resources: &mut Resources) {
powerups::run(resources);
whip::run(world, resources);
monster_ai::run(world, resources);
time::run(resources);
}

109
src/systems/monster_ai.rs Normal file
View file

@ -0,0 +1,109 @@
use crate::{
components::{monster::*, *},
resources::Resources,
tile_data::TileType,
};
use bracket_lib::{prelude::*, random::RandomNumberGenerator};
use hecs::*;
pub fn run(world: &mut World, resources: &mut Resources) {
let player_position = world
.query::<(&Player, &Position)>()
.iter()
.map(|(_, (_, &pos))| pos)
.collect::<Vec<_>>()
.first()
.cloned();
if let Some(player_pos) = player_position {
let mut to_kill: Vec<Entity> = Vec::new();
for (entity, (monster, position, renderable)) in
&mut world.query::<(&mut Monster, &mut Position, &mut Renderable)>()
{
if resources.clock.has_ticked {
monster.ticks_until_move -= 1;
if monster.ticks_until_move <= 0 {
// Change glyph
let mut rng = RandomNumberGenerator::new();
if let Some(glyph) =
rng.random_slice_entry(&monster::glyphs_for_kind(monster.kind))
{
renderable.glyph = *glyph;
}
// Move monster
let (mut delta_x, mut delta_y) = (0, 0);
if player_pos.x < position.x {
delta_x = -1;
}
if player_pos.x > position.x {
delta_x = 1;
}
if player_pos.y < position.y {
delta_y = -1;
}
if player_pos.y > position.y {
delta_y = 1;
}
let destination = Point {
x: position.x + delta_x,
y: position.y + delta_y,
};
if let Some(e) = resources.map.get_tile_content_at(destination) {
if let Ok(_player) = world.get::<&Player>(e) {
// TODO: Sound
resources.map.clear_tile_content_at(Point::from(*position));
resources.stats.take_gems(damage_for_kind(monster.kind));
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output
.play_sound(sound_effect_for_kind(monster.kind, sound_effects));
}
to_kill.push(entity);
}
} else {
let tile = resources.map.get_tile_at_mut(destination);
match tile {
TileType::Wall => {}
TileType::Block => {
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output.play_sound(sound_effect_for_kind(
monster.kind,
sound_effects,
));
}
resources.stats.add_score(1);
*tile = TileType::Floor;
to_kill.push(entity);
resources.map.clear_tile_content_at(Point::from(*position));
}
_ => {
resources.map.clear_tile_content_at(Point::from(*position));
position.x = destination.x;
position.y = destination.y;
resources.map.set_tile_content_at(destination, entity);
}
}
}
if resources.speed_time_ticks > 0 {
monster.ticks_until_move = 3;
} else if resources.slow_time_ticks > 0 {
monster.ticks_until_move = ticks_for_kind(monster.kind) * 5;
} else {
monster.ticks_until_move = ticks_for_kind(monster.kind);
}
}
}
}
for e in to_kill {
let _ = world.despawn(e);
}
}
}

View file

@ -1,119 +0,0 @@
use crate::{
components::{
monster::{self, damage_for_kind, ticks_for_kind},
Monster, Position, Renderable,
},
resources::map::TileType,
resources::{Clock, Map, Stats},
};
use bracket_lib::{prelude::*, random::RandomNumberGenerator};
use specs::prelude::*;
pub struct MonsterMotion {}
#[allow(clippy::type_complexity)]
impl<'a> System<'a> for MonsterMotion {
type SystemData = (
Entities<'a>,
ReadExpect<'a, Clock>,
ReadExpect<'a, Point>,
WriteExpect<'a, Map>,
WriteExpect<'a, Stats>,
WriteStorage<'a, Monster>,
WriteStorage<'a, Position>,
WriteStorage<'a, Renderable>,
);
fn run(
&mut self,
(
entities,
clock,
player_pos,
mut map,
mut stats,
mut monsters,
mut positions,
mut renderables,
): Self::SystemData,
) {
let mut data = (&entities, &mut monsters, &mut positions, &mut renderables)
.join()
.collect::<Vec<_>>();
for (entity, monster, position, renderable) in &mut data {
if clock.has_ticked {
monster.ticks_until_move -= 1;
if monster.ticks_until_move <= 0 {
// Change glyph
let mut rng = RandomNumberGenerator::new();
if let Some(glyph) =
rng.random_slice_entry(&monster::glyphs_for_kind(monster.kind))
{
renderable.glyph = *glyph;
}
// Move monster
let (mut delta_x, mut delta_y) = (0, 0);
if player_pos.x < position.x {
delta_x = -1;
}
if player_pos.x > position.x {
delta_x = 1;
}
if player_pos.y < position.y {
delta_y = -1;
}
if player_pos.y > position.y {
delta_y = 1;
}
let destination = Point {
x: position.x + delta_x,
y: position.y + delta_y,
};
//for (entity, monster, position, renderable) in &data {}
match map.get_tile_at(destination) {
TileType::Player => {
// TODO: Sound
if stats.gems > 0 {
stats.gems -= damage_for_kind(monster.kind);
}
map.set_tile_at(
Point {
x: position.x,
y: position.y,
},
TileType::Floor,
);
let _ = entities.delete(*entity);
continue;
}
TileType::Monster(_) => {}
TileType::Wall => {}
TileType::BreakableWall => {
// TODO: Sound
map.set_tile_at(destination, TileType::Floor);
let _ = entities.delete(*entity);
}
TileType::Floor => {
map.set_tile_at(
Point {
x: position.x,
y: position.y,
},
TileType::Floor,
);
map.set_tile_at(destination, TileType::Monster(*entity));
position.x = destination.x;
position.y = destination.y;
}
}
monster.ticks_until_move = ticks_for_kind(monster.kind);
}
}
}
}
}

12
src/systems/powerups.rs Normal file
View file

@ -0,0 +1,12 @@
use crate::resources::Resources;
pub fn run(resources: &mut Resources) {
if resources.clock.has_ticked {
if let Some(t) = resources.speed_time_ticks.checked_sub(1) {
resources.speed_time_ticks = t;
}
if let Some(t) = resources.slow_time_ticks.checked_sub(1) {
resources.slow_time_ticks = t;
}
}
}

37
src/systems/time.rs Normal file
View file

@ -0,0 +1,37 @@
use instant::Instant;
use std::time::Duration;
use crate::constants::CLOCK_PERIOD;
use crate::resources::{Clock, Resources};
pub fn run(resources: &mut Resources) {
if !resources.stop_clock && resources.flashing_message.is_none() {
try_tick(&mut resources.clock);
} else {
reset(&mut resources.clock);
}
}
fn try_tick(clock: &mut Clock) {
if Instant::now() - clock.last_ticked > Duration::from_secs_f32(CLOCK_PERIOD) {
tick(clock);
} else {
clock.has_ticked = false;
}
}
pub fn force_tick(clock: &mut Clock) {
tick(clock);
}
fn tick(clock: &mut Clock) {
clock.has_ticked = true;
clock.last_ticked = Instant::now();
clock.ticks += 1;
}
fn reset(clock: &mut Clock) {
clock.last_ticked = Instant::now();
clock.has_ticked = false;
}

143
src/systems/whip.rs Normal file
View file

@ -0,0 +1,143 @@
use instant::Instant;
use std::time::Duration;
use bracket_lib::prelude::*;
use hecs::{Entity, World};
use crate::{
components::{monster::damage_for_kind, Monster, Position, WantsToWhip},
resources::Resources,
tile_data::TileType,
};
pub fn run(world: &mut World, resources: &mut Resources) {
let mut to_kill: Vec<Entity> = Vec::new();
let mut to_remove: Vec<Entity> = Vec::new();
for (entity, (position, mut wants_to_whip)) in
&mut world.query::<(&Position, &mut WantsToWhip)>()
{
resources.stop_clock = true;
let now = Instant::now();
if now - wants_to_whip.last_frame > Duration::from_secs_f32(0.1) {
let destination = loop {
let destination = match wants_to_whip.frame {
0 => Some(Point {
x: position.x - 1,
y: position.y - 1,
}),
1 => Some(Point {
x: position.x - 1,
y: position.y,
}),
2 => Some(Point {
x: position.x - 1,
y: position.y + 1,
}),
3 => Some(Point {
x: position.x,
y: position.y + 1,
}),
4 => Some(Point {
x: position.x + 1,
y: position.y + 1,
}),
5 => Some(Point {
x: position.x + 1,
y: position.y,
}),
6 => Some(Point {
x: position.x + 1,
y: position.y - 1,
}),
7 => Some(Point {
x: position.x,
y: position.y - 1,
}),
_ => None,
};
if let Some(dest) = destination {
if resources.map.in_bounds(dest) {
break destination;
}
wants_to_whip.frame += 1;
if wants_to_whip.frame > 7 {
break None;
}
}
};
if let Some(dest) = destination {
if let Some(e) = resources.map.get_tile_content_at(dest) {
if let Ok(monster) = world.get::<&Monster>(e) {
resources.stats.add_score(damage_for_kind(monster.kind));
to_kill.push(e);
resources.map.clear_tile_content_at(dest);
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output.play_sound(sound_effects.whipping_hit_enemy.clone());
}
switch_to_hit_sound(resources, wants_to_whip);
}
} else {
hit_tile(resources, wants_to_whip, dest);
}
}
if wants_to_whip.frame < 7 {
wants_to_whip.frame += 1;
wants_to_whip.last_frame = now;
} else {
to_remove.push(entity);
resources.stop_clock = false;
if let Some(sound) = &mut wants_to_whip.sound {
sound.control::<oddio::Stop<_>, _>().stop();
wants_to_whip.sound = None;
}
}
}
}
for e in to_kill {
let _ = world.despawn(e);
}
for e in to_remove {
let _ = world.remove_one::<WantsToWhip>(e);
}
}
fn hit_tile(resources: &mut Resources, wants_to_whip: &mut WantsToWhip, location: Point) {
let tile = resources.map.get_tile_at(location);
match tile {
TileType::Block | TileType::Tree => {
let mut rng = RandomNumberGenerator::new();
if (rng.range(0, 7) as u32) < resources.stats.whip_power {
resources.map.set_tile_at(location, TileType::Floor);
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
sound_output.play_sound(sound_effects.whipping_hit_block.clone());
}
switch_to_hit_sound(resources, wants_to_whip);
}
}
TileType::Forest => todo!(),
_ => (),
}
}
fn switch_to_hit_sound(resources: &mut Resources, wants_to_whip: &mut WantsToWhip) {
if let Some(sound) = &mut wants_to_whip.sound {
sound.control::<oddio::Stop<_>, _>().stop();
}
if let (Some(sound_effects), Some(sound_output)) =
(&mut resources.sound_effects, &mut resources.sound_output)
{
wants_to_whip.sound = Some(sound_output.play_sound(sound_effects.whipping_hit.clone()));
}
}

435
src/tile_data.rs Normal file
View file

@ -0,0 +1,435 @@
use bracket_lib::prelude::*;
use crate::graphics::vga_color as vga;
#[derive(Eq, PartialEq, Copy, Clone)]
pub struct TileData {
pub glyph: FontCharType,
pub color_fg: (u8, u8, u8),
pub color_bg: (u8, u8, u8),
pub serialized_char: char,
}
#[derive(Eq, PartialEq, Copy, Clone, Hash)]
pub enum TileType {
Floor, // 0
Slow, // 1
Medium, // 2
Fast, // 3
Block, // 4
Whip, // 5
Stairs, // 6
Chest, // 7
SlowTime, // 8
Gem, // 9
Invisible, // 10
Teleport, // 11
Key, // 12
Door, // 13
Wall, // 14
SpeedTime, // 15
Trap, // 16
River, // 17
Power, // 18
Forest, // 19
Tree, // 20, 252
Bomb, // 21
Lava, // 22
Pit, // 23
Tome, // 24
Tunnel, // 25
Freeze, // 26
Nugget, // 27
Quake, // 28
InvisibleBlock, // 29
InvisibleWall, // 30
InvisibleDoor, // 31
Stop, // 32
Zap, // 34
Create, // 35
Generator, // 36
Trap2, // 33
Trap3, // 37
Trap4, // 39
Trap5, // 67
Trap6, // 224
Trap7, // 225
Trap8, // 226
Trap9, // 227
Trap10, // 228
Trap11, // 229
Trap12, // 230
Trap13, // 231
Player, // 40
Punctuation, // 222
Letter(char),
}
pub fn tile_data(tile: TileType) -> TileData {
match tile {
TileType::Floor => TileData {
glyph: 0,
serialized_char: ' ',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Slow => TileData {
glyph: 0,
serialized_char: '1',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Medium => TileData {
glyph: 0,
serialized_char: '2',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Fast => TileData {
glyph: 0,
serialized_char: '3',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Block => TileData {
glyph: to_cp437('▓'),
serialized_char: 'X',
color_fg: vga::YELLOW,
color_bg: vga::BLACK,
},
TileType::Whip => TileData {
glyph: to_cp437('⌠'),
serialized_char: 'W',
color_fg: vga::WHITE_BRIGHT,
color_bg: vga::BLACK,
},
TileType::Stairs => TileData {
glyph: to_cp437('≡'),
serialized_char: 'L',
color_fg: vga::BLACK,
color_bg: vga::WHITE,
},
TileType::Chest => TileData {
glyph: to_cp437('C'),
serialized_char: 'C',
color_fg: vga::YELLOW_BRIGHT,
color_bg: vga::RED,
},
TileType::SlowTime => TileData {
glyph: to_cp437('Φ'),
serialized_char: 'S',
color_fg: vga::CYAN_BRIGHT,
color_bg: vga::BLACK,
},
TileType::Gem => TileData {
glyph: to_cp437('♦'),
serialized_char: '+',
color_fg: vga::WHITE,
color_bg: vga::BLACK,
},
TileType::Invisible => TileData {
glyph: to_cp437('¡'),
serialized_char: 'I',
color_fg: vga::GREEN,
color_bg: vga::BLACK,
},
TileType::Teleport => TileData {
glyph: to_cp437('↑'),
serialized_char: 'T',
color_fg: vga::MAGENTA_BRIGHT,
color_bg: vga::BLACK,
},
TileType::Key => TileData {
glyph: to_cp437('î'),
serialized_char: 'K',
color_fg: vga::RED_BRIGHT,
color_bg: vga::BLACK,
},
TileType::Door => TileData {
glyph: to_cp437('∞'),
serialized_char: 'D',
color_fg: vga::CYAN,
color_bg: vga::MAGENTA,
},
TileType::Wall => TileData {
glyph: to_cp437('█'),
serialized_char: '#',
color_fg: vga::YELLOW,
color_bg: vga::BLACK,
},
TileType::SpeedTime => TileData {
glyph: to_cp437('Θ'),
serialized_char: 'F',
color_fg: vga::CYAN_BRIGHT,
color_bg: vga::BLACK,
},
TileType::Trap => TileData {
glyph: to_cp437('∙'),
serialized_char: '.',
color_fg: vga::WHITE,
color_bg: vga::BLACK,
},
TileType::River => TileData {
glyph: to_cp437('≈'),
serialized_char: 'R',
color_fg: vga::BLUE_BRIGHT,
color_bg: vga::BLUE,
},
TileType::Power => TileData {
glyph: to_cp437('○'),
serialized_char: 'Q',
color_fg: vga::WHITE_BRIGHT,
color_bg: vga::BLACK,
},
TileType::Forest => TileData {
glyph: to_cp437('█'),
serialized_char: '/',
color_fg: vga::GREEN,
color_bg: vga::BLACK,
},
TileType::Tree => TileData {
glyph: to_cp437('♣'),
serialized_char: '\\',
color_fg: vga::YELLOW,
color_bg: vga::GREEN,
},
TileType::Bomb => TileData {
glyph: to_cp437('¥'),
serialized_char: 'B',
color_fg: vga::WHITE_BRIGHT,
color_bg: vga::BLACK,
},
TileType::Lava => TileData {
glyph: to_cp437('▓'),
serialized_char: 'V',
color_fg: vga::RED_BRIGHT,
color_bg: vga::RED,
},
TileType::Pit => TileData {
glyph: to_cp437('░'),
serialized_char: '=',
color_fg: vga::WHITE,
color_bg: vga::BLACK,
},
TileType::Tome => TileData {
glyph: to_cp437('♀'),
serialized_char: 'A',
color_fg: vga::WHITE_BRIGHT,
color_bg: vga::BLACK,
},
TileType::Tunnel => TileData {
glyph: to_cp437('∩'),
serialized_char: 'U',
color_fg: vga::WHITE_BRIGHT,
color_bg: vga::BLACK,
},
TileType::Freeze => TileData {
glyph: to_cp437('ƒ'),
serialized_char: 'Z',
color_fg: vga::CYAN_BRIGHT,
color_bg: vga::BLACK,
},
TileType::Nugget => TileData {
glyph: to_cp437('☼'),
serialized_char: '*',
color_fg: vga::YELLOW_BRIGHT,
color_bg: vga::BLACK,
},
TileType::Quake => TileData {
glyph: 0,
serialized_char: 'E',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::InvisibleBlock => TileData {
glyph: 0,
serialized_char: ';',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::InvisibleWall => TileData {
glyph: 0,
serialized_char: ':',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::InvisibleDoor => TileData {
glyph: 0,
serialized_char: '`',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Stop => TileData {
glyph: 0,
serialized_char: '-',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Zap => TileData {
glyph: to_cp437('▲'),
serialized_char: '%',
color_fg: vga::RED_BRIGHT,
color_bg: vga::BLACK,
},
TileType::Create => TileData {
glyph: to_cp437('▼'),
serialized_char: ']',
color_fg: vga::WHITE_BRIGHT,
color_bg: vga::BLACK,
},
TileType::Generator => TileData {
glyph: to_cp437('♠'),
serialized_char: 'G',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Trap2 => TileData {
glyph: 0,
serialized_char: '@',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Trap3 => TileData {
glyph: 0,
serialized_char: ')',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Trap4 => TileData {
glyph: 0,
serialized_char: '(',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Trap5 => TileData {
glyph: 0,
serialized_char: '$', // Unsure about this
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Trap6 => TileData {
glyph: 0,
serialized_char: 'α',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Trap7 => TileData {
glyph: 0,
serialized_char: 'ß',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Trap8 => TileData {
glyph: 0,
serialized_char: 'Γ',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Trap9 => TileData {
glyph: 0,
serialized_char: 'π',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Trap10 => TileData {
glyph: 0,
serialized_char: 'Σ',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Trap11 => TileData {
glyph: 0,
serialized_char: 'σ',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Trap12 => TileData {
glyph: 0,
serialized_char: 'µ',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Trap13 => TileData {
glyph: 0,
serialized_char: 'τ',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Player => TileData {
glyph: 0,
serialized_char: 'P',
color_fg: vga::BLACK,
color_bg: vga::BLACK,
},
TileType::Punctuation => TileData {
glyph: to_cp437('!'),
serialized_char: '!',
color_fg: vga::WHITE_BRIGHT,
color_bg: vga::YELLOW,
},
TileType::Letter(c) => TileData {
glyph: to_cp437(c.to_ascii_uppercase()),
serialized_char: c,
color_fg: vga::WHITE_BRIGHT,
color_bg: vga::YELLOW,
},
}
}
impl From<char> for TileType {
fn from(c: char) -> Self {
match c {
' ' => TileType::Floor,
'1' => TileType::Slow,
'2' => TileType::Medium,
'3' => TileType::Fast,
'X' => TileType::Block,
'W' => TileType::Whip,
'L' => TileType::Stairs,
'C' => TileType::Chest,
'S' => TileType::SlowTime,
'+' => TileType::Gem,
'I' => TileType::Invisible,
'T' => TileType::Teleport,
'K' => TileType::Key,
'D' => TileType::Door,
'#' => TileType::Wall,
'F' => TileType::SpeedTime,
'.' => TileType::Trap,
'R' => TileType::River,
'Q' => TileType::Power,
'/' => TileType::Forest,
'\\' => TileType::Tree,
'B' => TileType::Bomb,
'V' => TileType::Lava,
'=' => TileType::Pit,
'A' => TileType::Tome,
'U' => TileType::Tunnel,
'Z' => TileType::Freeze,
'*' => TileType::Nugget,
'E' => TileType::Quake,
';' => TileType::InvisibleBlock,
':' => TileType::InvisibleWall,
'`' => TileType::InvisibleDoor,
'-' => TileType::Stop,
'%' => TileType::Zap,
']' => TileType::Create,
'G' => TileType::Generator,
'@' => TileType::Trap2,
')' => TileType::Trap3,
'(' => TileType::Trap4,
'$' => TileType::Trap5,
'α' => TileType::Trap6,
'ß' => TileType::Trap7,
'Γ' => TileType::Trap8,
'π' => TileType::Trap9,
'Σ' => TileType::Trap10,
'σ' => TileType::Trap11,
'µ' => TileType::Trap12,
'τ' => TileType::Trap13,
'P' => TileType::Player,
'!' => TileType::Punctuation,
_ => TileType::Letter(c),
}
}
}

BIN
static/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

36
static/index.html Normal file
View file

@ -0,0 +1,36 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Kroz</title>
<link rel="icon" type="image/png" href="icon.png" />
<style>
* {
margin: 0;
padding: 0;
}
body,
html {
height: 100%;
}
#canvas {
width: 100vw;
height: 56.25vw;
max-height: 100vh;
max-width: 177.78vh;
margin: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script src="index.js"></script>
</body>
</html>

36
webpack.config.js Normal file
View file

@ -0,0 +1,36 @@
const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");
const dist = path.resolve(__dirname, "dist");
module.exports = {
mode: "production",
entry: {
index: "./js/index.js"
},
output: {
path: dist,
filename: "[name].js"
},
experiments: {
asyncWebAssembly: true,
syncWebAssembly: true
},
devServer: {
static: {
directory: dist,
}
},
plugins: [
new CopyPlugin({
patterns: [
"static"
]
}),
new WasmPackPlugin({
crateDirectory: __dirname,
}),
]
};