Compare commits

...

45 commits
whip ... master

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
50 changed files with 6214 additions and 1270 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,13 +17,19 @@ 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

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,7 +1,4 @@
use std::time::Instant;
use specs::prelude::*;
use specs_derive::Component;
use instant::Instant;
pub mod monster;
pub mod player;
@ -15,7 +12,6 @@ pub use renderable::Renderable;
use crate::resources::sound_output::SoundEffectHandle;
#[derive(Component)]
pub struct WantsToWhip {
pub frame: u8,
pub last_frame: Instant,

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;

View file

@ -1,45 +0,0 @@
#[derive(Debug, Eq, PartialEq, Copy, Clone, Hash)]
pub struct Difficulty {
pub value: u32,
pub starting_gems: u32,
pub starting_whips: u32,
pub starting_teleports: u32,
pub starting_keys: u32,
pub starting_whip_power: u32,
}
pub const SECRET: Difficulty = Difficulty {
value: 9,
starting_gems: 250,
starting_whips: 100,
starting_teleports: 50,
starting_keys: 1,
starting_whip_power: 3,
};
pub const NOVICE: Difficulty = Difficulty {
value: 8,
starting_gems: 20,
starting_whips: 10,
starting_teleports: 0,
starting_keys: 0,
starting_whip_power: 0,
};
pub const EXPERIENCED: Difficulty = Difficulty {
value: 5,
starting_gems: 15,
starting_whips: 0,
starting_teleports: 0,
starting_keys: 0,
starting_whip_power: 0,
};
pub const ADVANCED: Difficulty = Difficulty {
value: 2,
starting_gems: 10,
starting_whips: 0,
starting_teleports: 0,
starting_keys: 0,
starting_whip_power: 0,
};

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;
}
}

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,86 +2,16 @@
pub mod components;
pub mod constants;
pub mod difficulty;
mod graphics;
pub mod input;
pub mod levels;
pub mod resources;
mod sidebar;
mod state;
pub mod systems;
pub mod tile_data;
pub mod vga_color;
use bracket_lib::prelude::*;
use components::{Monster, Player, Position, Renderable, WantsToWhip};
use resources::{
Clock, LevelNumber, Map, ShowDebugInfo, SoundEffects, SoundOutput, Stats, StopClock,
};
use specs::prelude::*;
use state::State;
use std::time::Instant;
fn main() -> BError {
let context = BTermBuilder::vga(80, 25)
.with_fps_cap(60.0)
.with_title("Kroz")
.build()?;
let mut sound_system = SoundOutput::new();
let sound_effects = SoundEffects::new(&sound_system);
sound_system.play_sound(sound_effects.startup.clone());
let mut ecs = World::new();
let starting_level = 0;
ecs.insert(sound_system);
ecs.insert(LevelNumber(starting_level));
ecs.insert(ShowDebugInfo(false));
ecs.insert(StopClock(false));
ecs.insert(Clock {
last_ticked: Instant::now(),
has_ticked: false,
ticks: 0,
});
ecs.insert(sound_effects);
let selected_difficulty = difficulty::SECRET;
ecs.insert(selected_difficulty);
ecs.insert(Stats {
score: 0,
gems: selected_difficulty.starting_gems,
whips: selected_difficulty.starting_whips,
whip_power: selected_difficulty.starting_whip_power,
teleports: selected_difficulty.starting_teleports,
keys: selected_difficulty.starting_keys,
});
ecs.register::<Position>();
ecs.register::<Renderable>();
ecs.register::<Monster>();
ecs.register::<Player>();
ecs.register::<WantsToWhip>();
let map = Map::from_level(levels::get_level(starting_level));
map.spawn_entities(&mut ecs);
ecs.insert(map);
// 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);
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,14 +1,14 @@
use std::time::Instant;
use instant::Instant;
use crate::{
components::{monster::*, Monster, Player, Position, Renderable},
constants::*,
graphics::vga_color as vga,
levels::Level,
tile_data::{self, TileType},
vga_color as vga,
};
use bracket_lib::{prelude::*, random::RandomNumberGenerator};
use specs::{Builder, Entity, World, WorldExt};
use hecs::{Entity, World};
pub struct Map {
tiles: Vec<TileType>,
@ -44,9 +44,194 @@ impl Map {
}
}
pub fn from_level(level: Level) -> Self {
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, bterm: &mut BTerm) {
// Border
bterm.fill_region(
Rect {
x1: MAP_X as i32 - 1,
x2: MAP_WIDTH as i32 + MAP_X as i32 + 1,
y1: MAP_Y as i32 - 1,
y2: MAP_HEIGHT as i32 + MAP_Y as i32 + 1,
},
to_cp437('▓'),
self.border_fg,
self.border_bg,
);
for (i, tile) in self.tiles.iter().enumerate() {
let point = self.index_to_point2d(i);
let (x, y) = (point.x as usize, point.y as usize);
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,
);
}
}
pub fn get_tile_at(&self, point: Point) -> TileType {
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;
}
}
impl From<Level> for Map {
fn from(level: Level) -> Self {
match level {
Level::Normal(_data) => todo!(),
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();
@ -79,156 +264,4 @@ impl Map {
Level::End => todo!(),
}
}
pub fn spawn_entities(&self, ecs: &mut World) {
for (index, tile) in self.tiles.iter().enumerate() {
let point = self.index_to_point2d(index);
match tile {
TileType::Player => {
let player_entity = ecs
.create_entity()
.with(Position {
x: point.x,
y: point.y,
})
.with(Renderable {
glyph: to_cp437('☻'),
fg: RGB::named(vga::YELLOW_BRIGHT),
bg: RGB::named(vga::BLACK),
})
.with(Player {
last_moved: Instant::now(),
})
.build();
ecs.insert(point);
ecs.insert(player_entity);
}
TileType::Slow => {
let mut rng = RandomNumberGenerator::new();
ecs.create_entity()
.with(Position {
x: point.x,
y: point.y,
})
.with(Renderable {
glyph: *rng
.random_slice_entry(&glyphs_for_kind(MonsterKind::Slow))
.unwrap(),
fg: color_for_kind(MonsterKind::Slow),
bg: RGB::named(vga::BLACK),
})
.with(Monster {
kind: MonsterKind::Slow,
ticks_until_move: ticks_for_kind(MonsterKind::Slow),
})
.build();
}
TileType::Medium => {
let mut rng = RandomNumberGenerator::new();
ecs.create_entity()
.with(Position {
x: point.x,
y: point.y,
})
.with(Renderable {
glyph: *rng
.random_slice_entry(&glyphs_for_kind(MonsterKind::Medium))
.unwrap(),
fg: color_for_kind(MonsterKind::Medium),
bg: RGB::named(vga::BLACK),
})
.with(Monster {
kind: MonsterKind::Medium,
ticks_until_move: ticks_for_kind(MonsterKind::Medium),
})
.build();
}
TileType::Fast => {
let mut rng = RandomNumberGenerator::new();
ecs.create_entity()
.with(Position {
x: point.x,
y: point.y,
})
.with(Renderable {
glyph: *rng
.random_slice_entry(&glyphs_for_kind(MonsterKind::Fast))
.unwrap(),
fg: color_for_kind(MonsterKind::Fast),
bg: RGB::named(vga::BLACK),
})
.with(Monster {
kind: MonsterKind::Fast,
ticks_until_move: ticks_for_kind(MonsterKind::Fast),
})
.build();
}
_ => {}
}
}
}
pub fn clear_all_tile_content(&mut self) {
self.tile_content.iter_mut().for_each(|tile| {
*tile = None;
});
}
pub fn get_tile_content(&self, index: usize) -> Option<Entity> {
self.tile_content[index]
}
pub fn set_tile_content(&mut self, index: usize, entity: Entity) {
self.tile_content[index] = Some(entity);
}
pub fn get_tiles(&self) -> &Vec<TileType> {
&self.tiles
}
pub fn draw(&self, ctx: &mut BTerm) {
// Border
ctx.fill_region(
Rect {
x1: MAP_X as i32 - 1,
x2: MAP_WIDTH as i32 + MAP_X as i32 + 1,
y1: MAP_Y as i32 - 1,
y2: MAP_HEIGHT as i32 + MAP_Y as i32 + 1,
},
to_cp437('▓'),
self.border_fg,
self.border_bg,
);
for (i, tile) in self.tiles.iter().enumerate() {
let point = self.index_to_point2d(i);
let (x, y) = (point.x as usize, point.y as usize);
let data = tile_data::tile_data(*tile);
ctx.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,
);
}
}
pub fn get_tile_at(&self, point: Point) -> TileType {
self.tiles[self.point2d_to_index(point)]
}
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::Block)
}
}

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,73 +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 fn reset(&mut self) {
self.last_ticked = Instant::now();
self.has_ticked = false;
}
}
pub struct StopClock(pub bool);
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 take_gems(&mut self, num_gems: u32) -> PlayerSurvived {
let new_num_gems = self.gems as i64 - num_gems as i64;
if new_num_gems <= 0 {
self.gems = 0;
false
} else {
self.gems = new_num_gems as u32;
true
}
}
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,31 +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,
@ -62,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),
@ -78,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),
@ -93,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)
@ -107,25 +115,83 @@ impl SoundEffects {
})
.collect(),
}),
whipping: ss.render_sound_effect(&SoundEffect {
whipping: sound_output.render_sound_effect(&SoundEffect {
sounds: vec![Sound {
sound_type: SoundType::Tone(70),
duration: Duration::from_secs(3),
}],
}),
whipping_hit: ss.render_sound_effect(&SoundEffect {
sounds: vec![
Sound {
sound_type: SoundType::Tone(400),
duration: Duration::from_millis(20),
},
Sound {
sound_type: SoundType::Tone(90),
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),
}],
}),
rng: RandomNumberGenerator::new(),
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,4 +1,4 @@
use std::{f32::consts::PI, sync::Arc};
use std::sync::Arc;
use cpal::{
traits::{DeviceTrait, HostTrait, StreamTrait},
@ -61,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)
@ -116,11 +129,10 @@ impl SoundOutput {
}
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 + 1,
);
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,220 +1,101 @@
use std::time::{Duration, Instant};
use instant::Instant;
use crate::components::monster::damage_for_kind;
use crate::components::*;
use crate::resources::*;
use crate::systems::*;
use crate::vga_color as vga;
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();
}
self.draw_whip(ctx);
sidebar::draw(&self.ecs, ctx);
}
}
impl State {
pub fn new(ecs: World) -> Self {
State { ecs }
}
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::W => {
let player_entity = self.ecs.read_resource::<Entity>();
let mut stats = self.ecs.write_resource::<Stats>();
let positions = self.ecs.read_storage::<Position>();
let mut wants_to_whips = self.ecs.write_storage::<WantsToWhip>();
if let Some(_position) = positions.get(*player_entity) {
if wants_to_whips.get(*player_entity).is_none() && stats.whips > 0 {
let mut sound_output = self.ecs.write_resource::<SoundOutput>();
let sound_effects = self.ecs.fetch::<SoundEffects>();
let _ = wants_to_whips.insert(
*player_entity,
WantsToWhip {
frame: 0,
last_frame: Instant::now(),
sound: Some(
sound_output.play_sound(sound_effects.whipping.clone()),
),
},
);
stats.whips -= 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());
}
},
}
}
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 monsters = self.ecs.write_storage::<Monster>();
let map = self.ecs.read_resource::<Map>();
let mut stats = self.ecs.write_resource::<Stats>();
let mut sound_system = self.ecs.write_resource::<SoundOutput>();
let wants_to_whips = self.ecs.read_storage::<WantsToWhip>();
for (player_entity, player, pos) in (&entities, &mut players, &mut positions).join() {
// The player shouldn't be able to move while whipping
if let Some(_wants_to_whip) = wants_to_whips.get(player_entity) {
continue;
}
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,
};
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 Some(e) = map.get_tile_content(map.point2d_to_index(destination)) {
if let Some(monster) = monsters.get(e) {
stats.take_gems(damage_for_kind(monster.kind));
let _ = entities.delete(e);
}
}
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;
}
}
}
pub fn draw_whip(&self, ctx: &mut BTerm) {
let positions = self.ecs.read_storage::<Position>();
let wants_to_whips = self.ecs.read_storage::<WantsToWhip>();
let mut rng = RandomNumberGenerator::new();
for (position, wants_to_whip) in (&positions, &wants_to_whips).join() {
let color = RGB::named(vga::get_by_index(rng.range(1, 16)));
let frame_data = match wants_to_whip.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 {
ctx.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),
);
};
}
}
fn run_systems(&mut self) {
let mut map_indexing_system = MapIndexingSystem {};
map_indexing_system.run_now(&self.ecs);
let mut whip_system = WhipSystem {};
whip_system.run_now(&self.ecs);
let mut monster_ai_system = MonsterAiSystem {};
monster_ai_system.run_now(&self.ecs);
self.ecs.maintain();
let mut clock = self.ecs.write_resource::<Clock>();
if !self.ecs.read_resource::<StopClock>().0 {
clock.try_tick();
#[allow(dead_code)]
pub fn new(initialize_sound: bool) -> Self {
let mut sound_output = if initialize_sound {
Some(SoundOutput::new())
} else {
clock.reset();
None
};
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 next_level(&mut self) {
self.resources.level_number += 1;
self.world.clear();
self.resources.map = Map::from(levels::get_level(self.resources.level_number));
self.resources.map.spawn_entities(&mut self.world);
self.resources.should_advance_level = false;
}
}

View file

@ -1,27 +0,0 @@
use bracket_lib::prelude::*;
use specs::prelude::*;
use crate::{components::Position, resources::Map};
pub struct MapIndexingSystem {}
impl<'a> System<'a> for MapIndexingSystem {
type SystemData = (
WriteExpect<'a, Map>,
ReadStorage<'a, Position>,
Entities<'a>,
);
fn run(&mut self, data: Self::SystemData) {
let (mut map, position, entities) = data;
map.clear_all_tile_content();
for (entity, position) in (&entities, &position).join() {
let index = map.point2d_to_index(Point {
x: position.x,
y: position.y,
});
map.set_tile_content(index, entity);
}
}
}

View file

@ -1,7 +1,15 @@
pub mod map_indexing_system;
pub mod monster_ai_system;
pub mod whip_system;
pub mod monster_ai;
pub mod powerups;
pub mod time;
pub mod whip;
pub use map_indexing_system::MapIndexingSystem;
pub use monster_ai_system::MonsterAiSystem;
pub use whip_system::WhipSystem;
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,102 +0,0 @@
use crate::{
components::{
monster::{self, damage_for_kind, ticks_for_kind},
Monster, Player, Position, Renderable,
},
resources::{Clock, Map, Stats},
tile_data::TileType,
};
use bracket_lib::{prelude::*, random::RandomNumberGenerator};
use specs::prelude::*;
pub struct MonsterAiSystem {}
#[allow(clippy::type_complexity)]
impl<'a> System<'a> for MonsterAiSystem {
type SystemData = (
Entities<'a>,
ReadExpect<'a, Clock>,
ReadExpect<'a, Point>,
ReadExpect<'a, Map>,
WriteExpect<'a, Stats>,
WriteStorage<'a, Monster>,
WriteStorage<'a, Position>,
WriteStorage<'a, Renderable>,
ReadStorage<'a, Player>,
);
fn run(
&mut self,
(
entities,
clock,
player_pos,
map,
mut stats,
mut monsters,
mut positions,
mut renderables,
players,
): 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,
};
if let Some(e) = map.get_tile_content(map.point2d_to_index(destination)) {
if let Some(_player) = players.get(e) {
// TODO: Sound
stats.take_gems(damage_for_kind(monster.kind));
let _ = entities.delete(*entity);
}
} else {
match map.get_tile_at(destination) {
TileType::Wall => {}
TileType::Block => {
// TODO: Sound
let _ = entities.delete(*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()));
}
}

View file

@ -1,116 +0,0 @@
use std::time::{Duration, Instant};
use bracket_lib::prelude::*;
use specs::prelude::*;
use crate::{
components::{Monster, Position, WantsToWhip},
resources::{Map, SoundEffects, SoundOutput, StopClock},
};
pub struct WhipSystem {}
#[allow(clippy::type_complexity)]
impl<'a> System<'a> for WhipSystem {
type SystemData = (
WriteExpect<'a, Map>,
WriteExpect<'a, StopClock>,
WriteExpect<'a, SoundOutput>,
ReadExpect<'a, SoundEffects>,
ReadStorage<'a, Position>,
WriteStorage<'a, WantsToWhip>,
WriteStorage<'a, Monster>,
Entities<'a>,
);
fn run(&mut self, data: Self::SystemData) {
let (
map,
mut stop_clock,
mut sound_output,
sound_effects,
positions,
mut wants_to_whips,
monsters,
entities,
) = data;
let mut entities_to_remove: Vec<Entity> = vec![];
for (entity, position, mut wants_to_whip) in
(&entities, &positions, &mut wants_to_whips).join()
{
stop_clock.0 = true;
let now = Instant::now();
if now - wants_to_whip.last_frame > Duration::from_secs_f32(0.1) {
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 map.in_bounds(dest) {
if let Some(e) = map.get_tile_content(map.point2d_to_index(dest)) {
if let Some(_monster) = monsters.get(e) {
let _ = entities.delete(e);
if let Some(sound) = &mut wants_to_whip.sound {
sound.control::<oddio::Stop<_>, _>().stop();
}
wants_to_whip.sound = Some(
sound_output.play_sound(sound_effects.whipping_hit.clone()),
);
}
}
}
}
if wants_to_whip.frame < 7 {
(*wants_to_whip).frame += 1;
wants_to_whip.last_frame = now;
} else {
entities_to_remove.push(entity);
stop_clock.0 = false;
if let Some(sound) = &mut wants_to_whip.sound {
sound.control::<oddio::Stop<_>, _>().stop();
wants_to_whip.sound = None;
}
}
}
}
for entity in entities_to_remove {
wants_to_whips.remove(entity);
}
}
}

View file

@ -1,10 +1,10 @@
use bracket_lib::prelude::*;
use crate::vga_color as vga;
use crate::graphics::vga_color as vga;
#[derive(PartialEq, Copy, Clone)]
#[derive(Eq, PartialEq, Copy, Clone)]
pub struct TileData {
pub glyph: u16,
pub glyph: FontCharType,
pub color_fg: (u8, u8, u8),
pub color_bg: (u8, u8, u8),
pub serialized_char: char,
@ -375,3 +375,61 @@ pub fn tile_data(tile: TileType) -> TileData {
},
}
}
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,
}),
]
};