Compare commits

...

12 Commits

Author SHA1 Message Date
1c6e5d26d0 Show manual
extract playing the game and the manual from main
2024-01-23 09:56:31 +01:00
4a31994ac9 add a basic manual 2024-01-22 20:47:35 +01:00
a7195b9c3d adjust monster speed 2024-01-19 10:39:15 +01:00
970904c411 Monsters move after the player moved
this allows direct counter attack or fleeing
2024-01-19 10:39:05 +01:00
32fffd492d Fog of War can be disabled in dev builds 2024-01-19 10:10:52 +01:00
119a3d314a clean up some warnings 2024-01-14 13:31:40 +01:00
5265682c53 Show last message on death 2024-01-14 13:21:20 +01:00
efe531f6ce movement depends on monster class now 2024-01-10 16:40:46 +01:00
0b08cb41c2 more work on dungeon slayer 2024-01-10 11:00:23 +01:00
cad08bd300 Player and monster attacks follow the dungeon slayer rules 2024-01-06 13:02:31 +01:00
0431d872e4 using character and monster sheets 2024-01-06 10:38:34 +01:00
1f02ffc36e update ratatui 2024-01-06 10:35:37 +01:00
12 changed files with 859 additions and 127 deletions

231
Cargo.lock generated
View File

@ -20,6 +20,54 @@ version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5"
[[package]]
name = "anstream"
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e1ebcb11de5c03c67de28a7df593d32191b44939c482e97702baaaa6ab6a5"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87"
[[package]]
name = "anstyle-parse"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c75ac65da39e5fe5ab759307499ddad880d724eed2f6ce5b5e8a26f4f387928c"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e28923312444cdd728e4738b3f9c9cac739500909bb3d3c94b43551b16517648"
dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1cd54b81ec8d6180e24654d0b371ad22fc3dd083b6ff8ba325b72e00c87660a7"
dependencies = [
"anstyle",
"windows-sys 0.52.0",
]
[[package]]
name = "autocfg"
version = "1.1.0"
@ -56,6 +104,52 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "clap"
version = "4.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e578d6ec4194633722ccf9544794b71b1385c3c027efe0c55db226fc880865c"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4df4df40ec50c46000231c914968278b1eb05098cf8f1b3a518a95030e71d1c7"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf9804afaaf59a91e75b022a30fb7229a7901f60c755489cc61c9b423b836442"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 2.0.38",
]
[[package]]
name = "clap_lex"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1"
[[package]]
name = "colorchoice"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"
[[package]]
name = "crossterm"
version = "0.27.0"
@ -91,6 +185,7 @@ checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07"
name = "el_diabolo"
version = "0.1.0"
dependencies = [
"clap",
"crossterm",
"petgraph",
"rand",
@ -155,9 +250,9 @@ checksum = "1e186cfbae8084e513daff4240b4797e342f988cecda4fb6c939150f96315fd8"
[[package]]
name = "itertools"
version = "0.11.0"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"
checksum = "25db6b064527c5d482d0423354fcd07a89a2dfe07b67892e62411946db7f07b0"
dependencies = [
"either",
]
@ -211,7 +306,7 @@ dependencies = [
"libc",
"log",
"wasi",
"windows-sys",
"windows-sys 0.48.0",
]
[[package]]
@ -240,7 +335,7 @@ dependencies = [
"libc",
"redox_syscall",
"smallvec",
"windows-targets",
"windows-targets 0.48.5",
]
[[package]]
@ -315,9 +410,9 @@ dependencies = [
[[package]]
name = "ratatui"
version = "0.24.0"
version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ebc917cfb527a566c37ecb94c7e3fd098353516fb4eb6bea17015ade0182425"
checksum = "a5659e52e4ba6e07b2dad9f1158f578ef84a73762625ddb51536019f34d180eb"
dependencies = [
"bitflags 2.4.1",
"cassowary",
@ -326,6 +421,7 @@ dependencies = [
"itertools",
"lru",
"paste",
"stability",
"strum",
"unicode-segmentation",
"unicode-width",
@ -388,6 +484,22 @@ version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a"
[[package]]
name = "stability"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebd1b177894da2a2d9120208c3386066af06a488255caabc5de8ddca22dbc3ce"
dependencies = [
"quote",
"syn 1.0.109",
]
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "strum"
version = "0.25.0"
@ -407,7 +519,18 @@ dependencies = [
"proc-macro2",
"quote",
"rustversion",
"syn",
"syn 2.0.38",
]
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
@ -439,6 +562,12 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85"
[[package]]
name = "utf8parse"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"
[[package]]
name = "version_check"
version = "0.9.4"
@ -472,7 +601,7 @@ dependencies = [
"once_cell",
"proc-macro2",
"quote",
"syn",
"syn 2.0.38",
"wasm-bindgen-shared",
]
@ -494,7 +623,7 @@ checksum = "f0eb82fcb7930ae6219a7ecfd55b217f5f0893484b7a13022ebb2b2bf20b5283"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.38",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
@ -553,7 +682,16 @@ version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
"windows-targets",
"windows-targets 0.48.5",
]
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.0",
]
[[package]]
@ -562,13 +700,28 @@ version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
"windows_aarch64_gnullvm 0.48.5",
"windows_aarch64_msvc 0.48.5",
"windows_i686_gnu 0.48.5",
"windows_i686_msvc 0.48.5",
"windows_x86_64_gnu 0.48.5",
"windows_x86_64_gnullvm 0.48.5",
"windows_x86_64_msvc 0.48.5",
]
[[package]]
name = "windows-targets"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd"
dependencies = [
"windows_aarch64_gnullvm 0.52.0",
"windows_aarch64_msvc 0.52.0",
"windows_i686_gnu 0.52.0",
"windows_i686_msvc 0.52.0",
"windows_x86_64_gnu 0.52.0",
"windows_x86_64_gnullvm 0.52.0",
"windows_x86_64_msvc 0.52.0",
]
[[package]]
@ -577,42 +730,84 @@ version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef"
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_gnu"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313"
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_i686_msvc"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a"
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e"
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04"
[[package]]
name = "zerocopy"
version = "0.7.19"
@ -630,5 +825,5 @@ checksum = "56feebc4664bdb37f39c0b1b8fc8fa2f5648e3ec5f9cf4344978b4b7ca561fff"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.38",
]

View File

@ -6,8 +6,9 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
ratatui = "0.24.0"
ratatui = "0.25.0"
crossterm = "0.27.0"
rand = "0.8.5"
petgraph = "0.6.4"
whoami = "1.4.1"
whoami = "1.4.1"
clap = { version = "4.4.11", features = ["derive"] }

View File

@ -72,7 +72,7 @@ impl Artifact for Potion {
// only consume potion of the player can gain at least one health point
if !player.is_healthy() {
let old = player.get_life();
player.change_life(self.health.try_into().unwrap());
player.increase_life(self.health.try_into().unwrap());
let new = player.get_life();
messages.insert(0, format!("picked up potion and gained {} hp.", new - old).to_string());
self.health = 0;

150
src/dungeon_slayer.rs Normal file
View File

@ -0,0 +1,150 @@
use rand::Rng;
pub fn do_challenge(stat: u8) -> (bool, u8) {
if stat <= 20 {
let mut rng = rand::thread_rng();
let dice_roll = rng.gen_range(1..21);
return match dice_roll {
20 => { (false, 0) }
1 => { (true, dice_roll) }
_ => {
if dice_roll <= stat {
(true, stat - dice_roll)
} else {
(false, 0)
}
}
};
}
(false, 0)
}
#[allow(dead_code)]
pub struct PlayerStats {
// dungeon slayer attributes
pub(crate) body: u8,
pub(crate) agility: u8,
pub(crate) mind: u8,
// dungeon slayer properties
// for body
pub(crate) strength: u8,
pub(crate) toughness: u8,
// for agility
pub(crate) movement: u8,
pub(crate) dexterity: u8,
// for mind
pub(crate) wisdom: u8,
// TODO maybe the wrong translation of Verstand
pub(crate) aura: u8,
}
impl PlayerStats {
/// create random values for the 3 attributes of the dungeon slayer character
/// Each attribute is between 4 and 8, not over 20 in sum.
fn create_random_attributes() -> (u8, u8, u8) {
let mut values: [u8; 3] = [8, 8, 8];
let mut rng = rand::thread_rng();
while values[0] + values[1] + values[2] > 20 {
let i = rng.gen_range(0..3);
values[i] = values[i].saturating_sub(1);
}
(values[0], values[1], values[2])
}
/// create random values for the 6 properties of the dungeon slayer character
/// Each property is between 0 and 4, not over 8 in sum.
fn create_random_properties() -> (u8, u8, u8, u8, u8, u8) {
let mut values: [u8; 6] = [4, 4, 4, 4, 4, 4];
let mut rng = rand::thread_rng();
while values[0] + values[1] + values[2] + values[3] + values[4] + values[5] > 8 {
let i = rng.gen_range(0..6);
values[i] = values[i].saturating_sub(1);
}
(values[0], values[1], values[2], values[3], values[4], values[5])
}
/// create a set of player stats containing attributes and properties according to the
/// dungeon slayer rules.
pub fn create_random() -> PlayerStats {
let attributes = PlayerStats::create_random_attributes();
let properties = PlayerStats::create_random_properties();
PlayerStats {
body: attributes.0,
agility: attributes.1,
mind: attributes.2,
strength: properties.0,
toughness: properties.1,
movement: properties.2,
dexterity: properties.3,
wisdom: properties.4,
aura: properties.5,
}
}
/// calculate the max life based on this player stats.
pub fn get_max_life(&self) -> u8 {
self.body + self.toughness + 10
}
pub fn get_defense(&self) -> u8 {
self.body + self.toughness // TODO + self.armor
}
pub fn get_hit(&self) -> u8 {
self.body + self.strength // TODO + self.weapon
}
}
#[allow(dead_code)]
pub struct MonsterStats {
// dungeon slayer attributes
pub(crate) body: u8,
pub(crate) agility: u8,
pub(crate) mind: u8,
// dungeon slayer properties
// for body
pub(crate) strength: u8,
pub(crate) toughness: u8,
// for agility
pub(crate) movement: u8,
pub(crate) dexterity: u8,
// for mind
pub(crate) wisdom: u8,
// TODO maybe the wrong translation of Verstand
pub(crate) aura: u8,
pub(crate) max_life: u8,
pub(crate) defense: u8,
pub(crate) initiative: u8,
pub(crate) walk: u8,
pub(crate) hit: u8,
pub(crate) shoot: u8,
pub(crate) cast: u8,
pub(crate) targeted_cast: u8,
}
#[test]
fn test_create_random_attributes() {
for _ in 0..1000 {
let attributes = PlayerStats::create_random_attributes();
assert!(attributes.0 <= 8);
assert!(attributes.1 <= 8);
assert!(attributes.2 <= 8);
assert_eq!(attributes.0 + attributes.1 + attributes.2, 20);
}
}
#[test]
fn test_create_random_properties() {
for _ in 0..1000 {
let properties = PlayerStats::create_random_properties();
assert!(properties.0 <= 4);
assert!(properties.1 <= 4);
assert!(properties.2 <= 4);
assert!(properties.3 <= 4);
assert!(properties.4 <= 4);
assert!(properties.5 <= 4);
assert_eq!(properties.0 + properties.1 + properties.2 + properties.3 + properties.4 + properties.5, 8);
}
}

View File

@ -1,3 +1,6 @@
use crate::dungeon_slayer::do_challenge;
#[cfg(test)]
use crate::dungeon_slayer::PlayerStats;
use crate::level::{Level, StructureElement};
use crate::level_generator::LevelGenerator;
use crate::player::Player;
@ -24,6 +27,7 @@ pub struct Game {
/// the levels of the game
levels: Vec<Level>,
pub messages: Vec<String>,
use_fog_of_war: bool,
}
impl Game {
@ -36,6 +40,7 @@ impl Game {
player: p,
levels: v,
messages: Vec::with_capacity(10),
use_fog_of_war: true,
};
let start = {
g.get_level(0).start
@ -71,6 +76,8 @@ impl Game {
pub fn get_player(&self) -> &Player {
&self.player
}
pub fn toggle_fog_of_war(&mut self) { self.use_fog_of_war = !self.use_fog_of_war; }
pub fn uses_fog_of_war(&self) -> bool { self.use_fog_of_war }
pub fn get_mutable_player(&mut self) -> &mut Player {
&mut self.player
}
@ -102,7 +109,7 @@ impl Game {
let new_y: i16 = player_pos.get_y() as i16 + dy;
let player_level = player_pos.get_level();
let level = &mut self.levels[player_level];
level.get_element(new_x, new_y).0
level.get_element(new_x, new_y, self.use_fog_of_war).0
}
/// move the game's player into the given direction. If on the target field there is a stair,
@ -127,14 +134,14 @@ impl Game {
(dx, dy) = (0, 0);
let (next_level, x, y) = self.next_start();
player_level = next_level;
self.messages.insert(0, format!("you climb down to level {}.", next_level));
self.messages.insert(0, format!("You climb down to level {}.", next_level));
self.get_mutable_player().get_position().set(next_level, x, y);
}
StructureElement::StairUp => {
(dx, dy) = (0, 0);
let (next_level, x, y) = self.prev_end();
player_level = next_level;
self.messages.insert(0, format!("you climb up to level {}.", next_level));
self.messages.insert(0, format!("You climb up to level {}.", next_level));
self.get_mutable_player().get_position().set(next_level, x, y);
}
_ => {}
@ -152,18 +159,27 @@ impl Game {
let player_pos = &self.player.get_immutable_position();
let player_level = player_pos.get_level();
let level = &mut self.levels[player_level];
let (_, m, _) = level.get_element(player_pos.get_x() as i16, player_pos.get_y() as i16);
let (_, m, _) = level.get_element(player_pos.get_x() as i16, player_pos.get_y() as i16, true);
match m {
None => {}
Some(m) => {
// TODO fight the monster
self.player.change_life(-1);
m.decrease_life(1);
self.messages.insert(0, format!("{} hits you.", m.get_name()).to_string());
self.messages.insert(0, format!("you hit {}.", m.get_name()).to_string());
// Player attacks monster
let attack = do_challenge(self.player.player_stats.get_hit());
if attack.0 {
let mut damage = attack.1;
let defense = do_challenge(m.get_defense());
if defense.0 {
damage = damage.saturating_sub(defense.1);
}
self.messages.insert(0, format!("Attack on {} successful with {} damage.", m.get_name(), damage).to_string());
m.decrease_life(damage as usize);
} else {
self.messages.insert(0, format!("Attack on {} failed.", m.get_name()).to_string());
}
// monster died, player gains experience
if m.is_dead() {
self.player.gain_experience(m.get_experience_gain());
self.messages.insert(0, format!("You killed the {}.", m.get_name()).to_string());
}
return m.is_dead();
}
@ -174,7 +190,7 @@ impl Game {
let player_pos = &self.player.get_immutable_position();
let player_level = player_pos.get_level();
let level = &mut self.levels[player_level];
let (_, _, a) = level.get_element(player_pos.get_x() as i16, player_pos.get_y() as i16);
let (_, _, a) = level.get_element(player_pos.get_x() as i16, player_pos.get_y() as i16, true);
match a {
None => {}
Some(a) => {
@ -183,24 +199,48 @@ impl Game {
}
}
/// updates the player's current level. This will remove collected artifacts and dead monsters.
pub fn update_level(&mut self, ticks: u128) {
/// ticks is measuring the progress of the game even if the player is not moving, player_moved
/// indicates the player moved
pub fn update_level(&mut self, ticks: u128, player_moved: bool) {
let player_pos = &self.player.get_immutable_position();
let player_level = player_pos.get_level();
let level = &mut self.levels[player_level];
level.update(ticks, &mut self.player, &mut self.messages);
level.update(ticks, player_moved, &mut self.player, &mut self.messages);
}
}
#[test]
fn game_has_correct_number_of_levels() {
let p = Player::new("foo", 42);
let player_stats = PlayerStats {
body: 8,
agility: 8,
mind: 4,
strength: 3,
toughness: 3,
movement: 1,
dexterity: 1,
wisdom: 0,
aura: 0,
};
let p = Player::new("foo", player_stats);
let g = Game::new(p);
assert_eq!(g.levels.len(), LEVELS);
}
#[test]
fn game_has_player() {
let p = Player::new("foo", 42);
let player_stats = PlayerStats {
body: 8,
agility: 8,
mind: 4,
strength: 3,
toughness: 3,
movement: 1,
dexterity: 1,
wisdom: 0,
aura: 0,
};
let p = Player::new("foo", player_stats);
let g = Game::new(p);
assert_eq!(g.get_player().get_name(), "foo");
assert_eq!(g.get_player().get_immutable_position().get_level(), 0);
@ -208,16 +248,38 @@ fn game_has_player() {
#[test]
fn game_has_mutable_player() {
let p = Player::new("foo", 42);
let player_stats = PlayerStats {
body: 8,
agility: 8,
mind: 4,
strength: 3,
toughness: 3,
movement: 1,
dexterity: 1,
wisdom: 0,
aura: 0,
};
let p = Player::new("foo", player_stats);
let mut g = Game::new(p);
assert_eq!(g.get_player().get_name(), "foo");
g.get_mutable_player().change_life(-1);
assert_eq!(g.get_player().get_life(), 41);
g.get_mutable_player().decrease_life(1);
assert_eq!(g.get_player().get_life(), 20);
}
#[test]
fn game_get_level() {
let p = Player::new("foo", 42);
let player_stats = PlayerStats {
body: 8,
agility: 8,
mind: 4,
strength: 3,
toughness: 3,
movement: 1,
dexterity: 1,
wisdom: 0,
aura: 0,
};
let p = Player::new("foo", player_stats);
let mut g = Game::new(p);
g.get_level(0);
assert_ne!(g.get_level(0).start, (0, 0));

View File

@ -1,11 +1,9 @@
use std::cmp::{max, min};
use rand::Rng;
use rand::rngs::ThreadRng;
#[cfg(test)]
use crate::artifacts::{Chest, Potion};
use crate::artifacts::Artifact;
use crate::dungeon_slayer::do_challenge;
#[cfg(test)]
use crate::monster::{Orc, Rat};
use crate::monster::Monster;
@ -37,11 +35,10 @@ pub struct Level {
pub(crate) start: (usize, usize),
/// the position of the end in the level (either stair down or end point)
pub(crate) end: (usize, usize),
pub(crate) rng: ThreadRng,
}
impl Level {
pub fn get_element(&mut self, x: i16, y: i16) -> (Option<StructureElement>, Option<&mut Box<(dyn Monster + 'static)>>, Option<&mut Box<(dyn Artifact + 'static)>>) {
pub fn get_element(&mut self, x: i16, y: i16, use_fog_of_war: bool) -> (Option<StructureElement>, Option<&mut Box<(dyn Monster + 'static)>>, Option<&mut Box<(dyn Artifact + 'static)>>) {
if x < 0 || y < 0 {
return (None, None, None);
}
@ -50,7 +47,7 @@ impl Level {
if x >= LEVEL_WIDTH || y >= LEVEL_HEIGHT {
return (None, None, None);
}
if !self.discovered[x][y] {
if use_fog_of_war && !self.discovered[x][y] {
return (Some(StructureElement::Unknown), None, None);
}
let search_pos = &Position::new(self.level, x, y);
@ -112,7 +109,7 @@ impl Level {
}
}
}
pub fn update(&mut self, ticks: u128, player: &mut Player, messages: &mut Vec<String>) {
pub fn update(&mut self, ticks: u128, player_moved: bool, player: &mut Player, messages: &mut Vec<String>) {
for (index, a) in &mut self.artifacts.iter().enumerate() {
if a.was_collected() {
self.artifacts.remove(index);
@ -123,26 +120,33 @@ impl Level {
if self.monsters[index].is_dead() {
continue;
}
if ticks % self.monsters[index].get_ticks_between_steps() != 0 {
// if the player moved, the monsters move as well all the time
if !player_moved && ticks % self.monsters[index].get_ticks_between_steps() != 0 {
continue;
}
loop {
// calculate the direction the monster will try to walk
let (dx, dy) = match self.rng.gen_range(0..5) {
1 => { (1, 0) }
2 => { (-1, 0) }
3 => { (0, 1) }
4 => { (0, -1) }
_ => { (0, 0) }
};
let (dx, dy) = self.monsters[index].get_next_move(&self, player.get_immutable_position());
if self.can_monster_move(self.monsters[index].as_ref(), dx, dy) {
let (new_x, new_y) = self.monsters[index].get_position().change(dx, dy);
if player.get_immutable_position().get_x() == new_x && player.get_immutable_position().get_y() == new_y {
self.monsters[index].decrease_life(1);
player.change_life(-1);
messages.insert(0, format!("{} hits you.", self.monsters[index].get_name()).to_string());
messages.insert(0, format!("you hit {}.", self.monsters[index].get_name()).to_string());
// if the attack did not kill the opponent, back down
// TODO monster attacks
let attack = do_challenge(self.monsters[index].get_hit());
if attack.0 {
let mut damage = attack.1;
let defense = do_challenge(player.player_stats.get_defense());
if defense.0 {
damage = damage.saturating_sub(defense.1);
}
player.decrease_life(damage);
if player.is_dead() {
messages.insert(0, format!("Attack from {} killed you.", self.monsters[index].get_name()).to_string());
} else {
messages.insert(0, format!("Attack from {} successful with {} damage.", self.monsters[index].get_name(), damage).to_string());
}
} else {
messages.insert(0, format!("Attack from {} failed.", self.monsters[index].get_name()).to_string());
}
if !player.is_dead() {
self.monsters[index].get_position().change(-dx, -dy);
}
@ -203,7 +207,6 @@ impl Level {
artifacts: Vec::with_capacity(10),
start: (0, 0),
end: (0, 0),
rng: rand::thread_rng(),
}
}
#[cfg(test)]
@ -237,23 +240,23 @@ impl Level {
#[test]
fn test_get_element() {
let mut l = Level::new(0);
assert_eq!(l.get_element(-1, -1).0, None);
assert_eq!(l.get_element(0, 0).0.unwrap(), StructureElement::Unknown);
assert_eq!(l.get_element(LEVEL_WIDTH as i16 - 1, LEVEL_HEIGHT as i16 - 1).0.unwrap(), StructureElement::Unknown);
assert_eq!(l.get_element(LEVEL_WIDTH as i16, LEVEL_HEIGHT as i16).0, None);
assert_eq!(l.get_element(-1, -1, true).0, None);
assert_eq!(l.get_element(0, 0, true).0.unwrap(), StructureElement::Unknown);
assert_eq!(l.get_element(LEVEL_WIDTH as i16 - 1, LEVEL_HEIGHT as i16 - 1, true).0.unwrap(), StructureElement::Unknown);
assert_eq!(l.get_element(LEVEL_WIDTH as i16, LEVEL_HEIGHT as i16, true).0, None);
}
#[test]
fn test_discover_get_element() {
let mut l = Level::new(0);
assert_eq!(l.get_element(10, 10).0.unwrap(), StructureElement::Unknown);
assert_eq!(l.get_element(10, 10, true).0.unwrap(), StructureElement::Unknown);
let p = Position::new(0, 10, 10);
l.discover(&p);
assert_eq!(l.get_element(10, 10).0.unwrap(), StructureElement::Floor);
assert_eq!(l.get_element(9, 10).0.unwrap(), StructureElement::Floor);
assert_eq!(l.get_element(10, 9).0.unwrap(), StructureElement::Floor);
assert_eq!(l.get_element(11, 10).0.unwrap(), StructureElement::Floor);
assert_eq!(l.get_element(10, 11).0.unwrap(), StructureElement::Floor);
assert_eq!(l.get_element(10, 10, true).0.unwrap(), StructureElement::Floor);
assert_eq!(l.get_element(9, 10, true).0.unwrap(), StructureElement::Floor);
assert_eq!(l.get_element(10, 9, true).0.unwrap(), StructureElement::Floor);
assert_eq!(l.get_element(11, 10, true).0.unwrap(), StructureElement::Floor);
assert_eq!(l.get_element(10, 11, true).0.unwrap(), StructureElement::Floor);
}
#[test]
@ -294,20 +297,20 @@ fn test_discover_get_monster() {
let mut l = Level::new(0);
let p = Position::new(0, 10, 10);
l.discover(&p);
assert_eq!(l.get_element(10, 10).0.unwrap(), StructureElement::Floor);
assert!(l.get_element(10, 10).1.is_none());
assert_eq!(l.get_element(10, 10, true).0.unwrap(), StructureElement::Floor);
assert!(l.get_element(10, 10, true).1.is_none());
let m = Rat::new_with_position(Position::new(0, 10, 10));
assert_eq!(l.add_monster(m), Ok(()));
let elem = l.get_element(10, 10);
let elem = l.get_element(10, 10, true);
assert_eq!(elem.0.unwrap(), StructureElement::Floor);
assert!(elem.1.is_some());
let m = elem.1.unwrap();
assert_eq!(m.get_life(), 2);
assert_eq!(m.get_life(), 3);
m.decrease_life(2);
assert_eq!(l.get_element(10, 10).1.unwrap().get_life(), 0);
m.decrease_life(3);
assert_eq!(l.get_element(10, 10, true).1.unwrap().get_life(), 0);
}
#[test]
@ -315,13 +318,13 @@ fn test_discover_get_artifact() {
let mut l = Level::new(0);
let p = Position::new(0, 10, 10);
l.discover(&p);
assert_eq!(l.get_element(10, 10).0.unwrap(), StructureElement::Floor);
assert!(l.get_element(10, 10).2.is_none());
assert_eq!(l.get_element(10, 10, true).0.unwrap(), StructureElement::Floor);
assert!(l.get_element(10, 10, true).2.is_none());
let a = Chest::new(Position::new(0, 10, 10));
assert_eq!(l.add_artifact(a), Ok(()));
let elem = l.get_element(10, 10);
let elem = l.get_element(10, 10, true);
assert_eq!(elem.0.unwrap(), StructureElement::Floor);
assert!(elem.2.is_some());
}
@ -335,12 +338,12 @@ fn test_discover_get_monster_can_move() {
let m = Rat::new_with_position(Position::new(0, 10, 10));
l.add_monster(m).expect("Panic because of");
let m = l.get_element(10, 10).1.unwrap();
let m = l.get_element(10, 10, true).1.unwrap();
m.get_position().change(1, 1);
let m = l.get_element(10, 10).1;
let m = l.get_element(10, 10, true).1;
assert!(m.is_none());
let m = l.get_element(11, 11).1;
let m = l.get_element(11, 11, true).1;
assert!(m.is_some());
assert_eq!(m.unwrap().get_life(), 2);
assert_eq!(m.unwrap().get_life(), 3);
}

View File

@ -11,7 +11,7 @@ use rand::rngs::ThreadRng;
use crate::artifacts::{Artifact, Chest, Potion};
use crate::level::{Level, StructureElement};
use crate::monster::{Monster, Orc, Rat};
use crate::monster::{LowerDaemon, Monster, Rat};
use crate::position::Position;
const ROOMS_VERTICAL: usize = 7;
@ -276,7 +276,7 @@ impl LevelGenerator {
// TODO randomize enemies here
match rng.gen_range(1..=100) {
1..=50 => {
enemies.push(Box::new(Orc::new_with_position(Position::new(self.level, t_x, t_y))));
enemies.push(Box::new(LowerDaemon::new_with_position(Position::new(self.level, t_x, t_y))));
}
_ => {
enemies.push(Box::new(Rat::new_with_position(Position::new(self.level, t_x, t_y))));
@ -344,7 +344,6 @@ impl LevelGenerator {
artifacts,
start: (start_x, start_y),
end: (end_x, end_y),
rng: rand::thread_rng(),
}
}
}

View File

@ -9,9 +9,16 @@ use crate::position::HasPosition;
const FG_BROWN: Color = Color::Rgb(186, 74, 0);
pub struct LevelWidget {}
pub struct LevelWidget {
use_fog_of_war: bool,
}
impl LevelWidget {
pub fn new(use_fog_of_war: bool) -> Self {
LevelWidget {
use_fog_of_war
}
}
fn set_cell(&self, buf: &mut Buffer, x: u16, y: u16, symbol: &str, fg: Color, bg: Color) {
buf.
get_mut(x, y).
@ -39,7 +46,7 @@ impl StatefulWidget for LevelWidget {
let level = state.get_mutable_level(player_level);
let level_x = (x - al) as i16;
let level_y = (y - at) as i16;
match level.get_element(level_x, level_y) {
match level.get_element(level_x, level_y, self.use_fog_of_war) {
(Some(structure_element), None, None) => {
match structure_element {
StructureElement::Start => {

View File

@ -1,7 +1,10 @@
use std::io::Result;
use std::cmp::min;
use std::io::{Result, Stdout};
use std::io::stdout;
use std::string::ToString;
use std::time::Instant;
use clap::Parser;
use crossterm::{
event::{self, KeyCode, KeyEventKind},
ExecutableCommand,
@ -16,6 +19,7 @@ use ratatui::widgets::{Block, Borders, BorderType, Wrap};
use ratatui::widgets::block::{Position, Title};
use whoami::realname;
use crate::dungeon_slayer::PlayerStats;
use crate::game::{Game, GameState};
use crate::level_widget::LevelWidget;
use crate::player::Player;
@ -29,19 +33,42 @@ mod level_widget;
mod level_generator;
mod artifacts;
mod monster;
mod dungeon_slayer;
/// length of a game frame in ms
pub const FRAME_LENGTH: u64 = 100;
#[derive(Parser)]
#[command(author, version, about = "A small game in the tradition of rogue.", long_about = None)]
struct CliOptions {
#[arg(short, long, action)]
manual: bool,
}
//
fn main() -> Result<()> {
let mut game = Game::new(Player::new(realname().as_str(), 10));
let cli_options = CliOptions::parse();
stdout().execute(EnterAlternateScreen)?;
enable_raw_mode()?;
let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
terminal.clear()?;
if cli_options.manual {
show_manual(&mut terminal);
} else {
play_game(&mut terminal)?;
}
stdout().execute(LeaveAlternateScreen)?;
disable_raw_mode()?;
Ok(())
}
/// play the game ;)
fn play_game(terminal: &mut Terminal<CrosstermBackend<Stdout>>) -> Result<()> {
let player_stats = PlayerStats::create_random();
let mut game = Game::new(Player::new(realname().as_str(), player_stats));
let start_time = Instant::now();
let mut ticks = 0;
loop {
@ -80,7 +107,7 @@ fn main() -> Result<()> {
width: level::LEVEL_WIDTH as u16,
height: level::LEVEL_HEIGHT as u16,
};
frame.render_stateful_widget(LevelWidget {}, map_area, &mut game);
frame.render_stateful_widget(LevelWidget::new(game.uses_fog_of_war()), map_area, &mut game);
let stats_area = Rect {
x: area.x + 50,
@ -129,20 +156,40 @@ fn main() -> Result<()> {
messages_area,
);
})?;
let mut player_moved = false;
if event::poll(std::time::Duration::from_millis(FRAME_LENGTH))? {
if let event::Event::Key(key) = event::read()? {
if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('v') {
game.messages.insert(0, format!("You are playing version '{}'.", env!("GIT_HASH")).to_string());
}
// disabling the d key (disable fog of war) in release builds!
#[cfg(debug_assertions)]
if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('d') {
game.messages.insert(0, "toggle fog of war!".to_string());
game.toggle_fog_of_war();
}
if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') {
break;
}
if key.kind == KeyEventKind::Press {
let new_pos = match key.code {
KeyCode::Left => { game.move_player(-1, 0) }
KeyCode::Right => { game.move_player(1, 0) }
KeyCode::Up => { game.move_player(0, -1) }
KeyCode::Down => { game.move_player(0, 1) }
KeyCode::Left => {
player_moved = true;
game.move_player(-1, 0)
}
KeyCode::Right => {
player_moved = true;
game.move_player(1, 0)
}
KeyCode::Up => {
player_moved = true;
game.move_player(0, -1)
}
KeyCode::Down => {
player_moved = true;
game.move_player(0, 1)
}
_ => { (0, 0) }
};
if !game.player_fights_monster() {
@ -153,7 +200,7 @@ fn main() -> Result<()> {
}
}
}
game.update_level(ticks);
game.update_level(ticks, player_moved);
if game.get_game_state() != GameState::RUNNING {
break;
}
@ -181,13 +228,13 @@ fn main() -> Result<()> {
"Quitting is for cowards! You'll better try again!".to_string()
}
GameState::LOST => {
"Sorry, you died in the dungeon. Better luck next time!".to_string()
format!("Sorry, you died in the dungeon. Better luck next time!\nLast message:\n{}", game.messages[0]).to_string()
}
GameState::WON => {
"Congratulation! You mastered your way through the dungeon and won the game.".to_string()
}
};
text += format!("\nYou gained {} experience.", game.get_player().get_experience()).as_str();
text += format!("\n\nYou gained {} experience.", game.get_player().get_experience()).as_str();
text += format!("\nYou collected {} gold.", game.get_player().get_gold()).as_str();
text += format!("\nYou played {} seconds.", playtime.as_secs()).as_str();
let paragraph = Paragraph::new(text).block(block).wrap(Wrap { trim: true });
@ -201,7 +248,51 @@ fn main() -> Result<()> {
}
}
}
stdout().execute(LeaveAlternateScreen)?;
disable_raw_mode()?;
Ok(())
}
/// this function shows some manual text
fn show_manual(terminal: &mut Terminal<CrosstermBackend<Stdout>>) {
let mut page = 0;
let pages = [
"Background story\n\n\
You are a traveller and on your journey....
".to_string(),
"To control your character (depicted by the 8) you can use the cursor keys (←, ↑, →, ↓). \n\n\
To interact simply walk into the entity to interact with. Possible entities are creates \
(depicted by C), potions (depicted by P) or enemies.".to_string(),
];
loop {
let _ = terminal.draw(|frame| {
let mut area = frame.size();
let w = area.width / 2;
let h = area.height / 2;
area.x += w - 20;
area.y += h - 10;
area.width = 40;
area.height = 20;
let block = Block::default()
.title(Title::from(format!(" Manual ({}/{})", page + 1, pages.len())).alignment(Alignment::Center).position(Position::Top))
.title(Title::from("`q` to quit, `↑` and `↓` to scroll.").position(Position::Bottom))
.borders(Borders::ALL)
.border_style(Style::default().fg(Color::White))
.border_type(BorderType::Rounded)
.style(Style::default().bg(Color::Black));
let paragraph = Paragraph::new(pages[page].as_str()).block(block).wrap(Wrap { trim: true });
frame.render_widget(paragraph, area);
});
if event::poll(std::time::Duration::from_millis(16)).unwrap_or(false) {
if let event::Event::Key(key) = event::read().unwrap() {
if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') {
break;
}
if key.kind == KeyEventKind::Press && key.code == KeyCode::Up {
page = page.saturating_sub(1);
}
if key.kind == KeyEventKind::Press && key.code == KeyCode::Down {
page = min(pages.len() - 1, page + 1);
}
}
}
}
}

View File

@ -1,6 +1,10 @@
use ratatui::prelude::Color;
use crate::dungeon_slayer::MonsterStats;
use crate::level::Level;
use crate::position::{HasPosition, Position};
use rand::Rng;
pub trait Monster: HasPosition {
fn get_name(&self) -> &str;
@ -10,6 +14,9 @@ pub trait Monster: HasPosition {
// fn get_immutable_position(&self) -> &Position;
fn get_experience_gain(&self) -> usize;
fn get_ticks_between_steps(&self) -> u128;
fn get_defense(&self) -> u8;
fn get_hit(&self) -> u8;
fn get_next_move(&self, level: &Level, player_pos: &Position) -> (i16, i16);
#[cfg(test)]
fn get_life(&self) -> usize;
}
@ -25,7 +32,11 @@ macro_rules! default_monster {
self.life = self.life.saturating_sub(by);
}
fn get_ticks_between_steps(&self) -> u128 { self.ticks_between_steps }
fn get_defense(&self) -> u8 { self.monster_stats.defense }
fn get_hit(&self) -> u8 { self.monster_stats.hit }
fn get_next_move(&self, level: &Level, player_pos: &Position) -> (i16, i16) {
self.calc_move(level, player_pos)
}
#[cfg(test)]
fn get_life(&self) -> usize { self.life }
}
@ -40,6 +51,72 @@ macro_rules! default_monster {
)+)
}
/// Lower Daemon
/// Page: 107
/// GH: 1
pub struct LowerDaemon {
name: String,
life: usize,
position: Position,
symbol: String,
color: Color,
experience_gain: usize,
ticks_between_steps: u128,
monster_stats: MonsterStats,
}
impl crate::monster::LowerDaemon {
pub fn new_with_position(position: Position) -> Self {
let monster_stats = MonsterStats {
body: 5,
agility: 5,
mind: 5,
strength: 2,
toughness: 2,
movement: 2,
dexterity: 2,
wisdom: 2,
aura: 2,
max_life: 9,
defense: 9,
initiative: 7,
walk: 3,
hit: 8,
shoot: 0,
cast: 0,
targeted_cast: 0,
};
Self {
name: "lower daemon".to_string(),
life: monster_stats.max_life as usize,
position,
symbol: String::from("d"),
color: Color::Black,
experience_gain: 104,
ticks_between_steps: 30,
monster_stats,
}
}
fn calc_move(&self, _level: &Level, player_pos: &Position) -> (i16, i16) {
let d = self.position.distance(player_pos);
if d == 1 {
return self.position.get_direction(player_pos);
}
match rand::thread_rng().gen_range(0..5) {
1 => { (1, 0) }
2 => { (-1, 0) }
3 => { (0, 1) }
4 => { (0, -1) }
_ => { (0, 0) }
}
}
}
default_monster!(LowerDaemon);
/// Rat
/// Page: 119
/// GH: 1
pub struct Rat {
name: String,
life: usize,
@ -48,23 +125,56 @@ pub struct Rat {
color: Color,
experience_gain: usize,
ticks_between_steps: u128,
monster_stats: MonsterStats,
}
impl Rat {
pub fn new_with_position(position: Position) -> Self {
let monster_stats = MonsterStats {
body: 2,
agility: 4,
mind: 1,
strength: 1,
toughness: 0,
movement: 2,
dexterity: 0,
wisdom: 0,
aura: 0,
max_life: 3,
defense: 2,
initiative: 6,
walk: 3,
hit: 4,
shoot: 0,
cast: 0,
targeted_cast: 0,
};
Self {
name: "rat".to_string(),
life: 2,
life: monster_stats.max_life as usize,
position,
symbol: String::from("R"),
color: Color::Black,
experience_gain: 5,
ticks_between_steps: 5,
experience_gain: 26,
ticks_between_steps: 25,
monster_stats,
}
}
fn calc_move(&self, _level: &Level, _player_pos: &Position) -> (i16, i16) {
match rand::thread_rng().gen_range(0..5) {
1 => { (1, 0) }
2 => { (-1, 0) }
3 => { (0, 1) }
4 => { (0, -1) }
_ => { (0, 0) }
}
}
}
default_monster!(Rat);
/// Orc
/// Page: 118
/// GH: 2
pub struct Orc {
name: String,
life: usize,
@ -73,18 +183,48 @@ pub struct Orc {
color: Color,
experience_gain: usize,
ticks_between_steps: u128,
monster_stats: MonsterStats,
}
impl Orc {
pub fn new_with_position(position: Position) -> Self {
let monster_stats = MonsterStats {
body: 10,
agility: 6,
mind: 2,
strength: 2,
toughness: 3,
movement: 0,
dexterity: 3,
wisdom: 1,
aura: 0,
max_life: 23,
defense: 14,
initiative: 1,
walk: 4,
hit: 13,
shoot: 10,
cast: 0,
targeted_cast: 0,
};
Self {
name: "orc".to_string(),
life: 4,
life: monster_stats.max_life as usize,
position,
symbol: String::from("O"),
color: Color::DarkGray,
experience_gain: 10,
ticks_between_steps: 10,
experience_gain: 63,
ticks_between_steps: 50,
monster_stats,
}
}
fn calc_move(&self, _level: &Level, _player_pos: &Position) -> (i16, i16) {
match rand::thread_rng().gen_range(0..5) {
1 => { (1, 0) }
2 => { (-1, 0) }
3 => { (0, 1) }
4 => { (0, -1) }
_ => { (0, 0) }
}
}
}
@ -108,11 +248,17 @@ fn monsters_can_move() {
#[test]
fn monsters_can_die() {
let mut m = Rat::new_with_position(Position::new(0, 0, 0));
assert_eq!(m.get_life(), 2);
assert_eq!(m.get_life(), 3);
assert_eq!(m.is_dead(), false);
m.decrease_life(1);
assert_eq!(m.get_life(), 1);
m.decrease_life(2);
assert_eq!(m.get_life(), 2);
m.decrease_life(3);
assert_eq!(m.get_life(), 0);
assert_eq!(m.is_dead(), true);
}
#[test]
fn test_rat_values() {
let m = Rat::new_with_position(Position::new(0, 0, 0));
assert_eq!(m.monster_stats.max_life, 3);
}

View File

@ -1,32 +1,36 @@
use std::cmp::{max, min};
use crate::dungeon_slayer::PlayerStats;
use crate::position::{HasPosition, Position};
pub struct Player {
name: String,
position: Position,
life: i16,
max_life: i16,
gold: usize,
experience: usize,
pub(crate) player_stats: PlayerStats,
}
impl Player {
pub fn new(name: &str, max_life: i16) -> Player {
pub fn new(name: &str, player_stats: PlayerStats) -> Player {
Player {
name: name.to_string(),
position: Position::new(0, 0, 0),
life: max_life,
max_life,
life: player_stats.get_max_life() as i16,
gold: 0,
experience: 0,
player_stats,
}
}
pub fn get_name(&self) -> String {
return self.name.clone();
}
pub fn change_life(&mut self, by: i16) {
self.life = max(0, min(self.max_life, self.life + by));
pub fn decrease_life(&mut self, by: u8) {
self.life = max(0, self.life.saturating_sub(by as i16));
}
pub fn increase_life(&mut self, by: u8) {
self.life = min(self.life.saturating_add(by as i16), self.get_max_life());
}
pub fn get_life(&self) -> i16 {
self.life
@ -34,9 +38,9 @@ impl Player {
/// returns true if the player is dead (life <= 0)
pub fn is_dead(&self) -> bool { self.life <= 0 }
/// returns true if the player's life is at maximum
pub fn is_healthy(&self) -> bool { self.life == self.max_life }
pub fn is_healthy(&self) -> bool { self.life == self.get_max_life() }
pub fn get_max_life(&self) -> i16 {
self.max_life
self.player_stats.get_max_life() as i16
}
/// add the given amount to the players gold stash
@ -65,16 +69,37 @@ fn test_get_name() {
name: "Teddy Tester".to_string(),
position: Position::new(0, 1, 1),
life: 5,
max_life: 10,
gold: 0,
experience: 0,
player_stats: PlayerStats {
body: 0,
agility: 0,
mind: 0,
strength: 0,
toughness: 0,
movement: 0,
dexterity: 0,
wisdom: 0,
aura: 0,
},
};
assert_eq!(p.get_name(), "Teddy Tester");
}
#[test]
fn test_can_receive_gold() {
let mut p = Player::new("Teddy Tester", 10);
let player_stats = PlayerStats {
body: 8,
agility: 8,
mind: 4,
strength: 3,
toughness: 3,
movement: 1,
dexterity: 1,
wisdom: 0,
aura: 0,
};
let mut p = Player::new("Teddy Tester", player_stats);
assert_eq!(p.get_gold(), 0);
p.retrieve_gold(13);
@ -88,22 +113,43 @@ fn test_change_life() {
name: "Teddy Tester".to_string(),
position: Position::new(0, 1, 1),
life: 5,
max_life: 10,
gold: 0,
experience: 0,
player_stats: PlayerStats {
body: 0,
agility: 0,
mind: 0,
strength: 0,
toughness: 0,
movement: 0,
dexterity: 0,
wisdom: 0,
aura: 0,
},
};
assert_eq!(p.get_life(), 5);
p.change_life(-2);
p.decrease_life(2);
assert_eq!(p.get_life(), 3);
p.change_life(10);
p.increase_life(10);
assert_eq!(p.get_life(), 10);
p.change_life(-12);
p.decrease_life(12);
assert_eq!(p.get_life(), 0);
}
#[test]
fn player_can_move() {
let mut p = Player::new("Teddy Tester", 10);
let player_stats = PlayerStats {
body: 8,
agility: 8,
mind: 4,
strength: 3,
toughness: 3,
movement: 1,
dexterity: 1,
wisdom: 0,
aura: 0,
};
let mut p = Player::new("Teddy Tester", player_stats);
assert_eq!(p.get_position(), &Position::new(0, 0, 0));
p.get_position().change(1, 2);
assert_eq!(p.get_position(), &Position::new(0, 1, 2));
@ -121,9 +167,19 @@ fn test_max_life() {
name: "Teddy Tester".to_string(),
position: Position::new(0, 1, 1),
life: 5,
max_life: 10,
gold: 0,
experience: 0,
player_stats: PlayerStats {
body: 0,
agility: 0,
mind: 0,
strength: 0,
toughness: 0,
movement: 0,
dexterity: 0,
wisdom: 0,
aura: 0,
},
};
assert_eq!(p.get_max_life(), 10);
}

View File

@ -1,4 +1,4 @@
use std::cmp::max;
use std::cmp::{max, min};
/// describes an character (PC or NPC) in the dungeon that has a position.
pub trait HasPosition {
@ -43,6 +43,28 @@ impl Position {
}
pub fn get_y(&self) -> usize { self.y }
/// calculate the distance to the other position using the manhattan metric
pub fn distance(&self, other: &Self) -> usize {
self.x.abs_diff(other.x) + self.y.abs_diff(other.y)
}
/// get the direction (step size 1) towards the other position
pub fn get_direction(&self, other: &Self) -> (i16, i16) {
(
max(min(other.x as i16 - self.x as i16, 1), -1),
max(min(other.y as i16 - self.y as i16, 1), -1)
)
}
}
#[test]
fn test_get_direction() {
let p1 = Position::new(0, 10, 10);
let p2 = Position::new(0, 8, 8);
assert_eq!(p1.get_direction(&p2), (-1, -1));
let p2 = Position::new(0, 11, 10);
assert_eq!(p1.get_direction(&p2), (1, 0));
}
#[test]