Compare commits

...

90 Commits

Author SHA1 Message Date
Joachim Lusiardi 51123ecd8e version bump and index generation 2024-11-07 09:57:32 +01:00
Joachim Lusiardi 4d77265b2f remove debug output 2024-11-07 09:47:49 +01:00
Joachim Lusiardi c91d57f049 next try 2024-11-07 09:46:15 +01:00
Joachim Lusiardi 8f151836bd next try 2024-11-07 09:41:40 +01:00
Joachim Lusiardi 9d862011a7 testing 2024-11-07 09:37:22 +01:00
Joachim Lusiardi d068620c3f more tuning 2024-11-07 09:35:30 +01:00
Joachim Lusiardi 6660c11306 more debug 2024-11-07 09:29:24 +01:00
Joachim Lusiardi 1d8896d1ad debugging 2024-11-07 09:27:31 +01:00
Joachim Lusiardi 252c1c244d make key secure in container 2024-11-07 09:24:19 +01:00
Joachim Lusiardi ef3a6026f5 minor fixes 2024-11-07 09:22:19 +01:00
Joachim Lusiardi 542616cb0b version bump 2024-11-07 09:15:44 +01:00
Joachim Lusiardi 9a6c8f5116 try to auto publish to website 2024-11-07 09:15:24 +01:00
Joachim Lusiardi d82e0d2d48 version updates 2024-11-06 14:33:11 +01:00
Joachim Lusiardi a542e4b1c0 add mechanism for level gain 2024-11-06 14:29:30 +01:00
Joachim Lusiardi 3249529f94 cleanup 2024-11-06 09:22:22 +01:00
Joachim Lusiardi 72f7be2ed8 more work on level generators 2024-11-05 12:02:45 +01:00
Joachim Lusiardi 5311f56ca0 extract minimal room size as constant 2024-11-03 10:32:04 +01:00
Joachim Lusiardi df80dfdd8a introduce custom type for the graph 2024-11-01 13:08:02 +01:00
Joachim Lusiardi 8b23c565b8 make connections more variable 2024-11-01 12:06:50 +01:00
Joachim Lusiardi 789a41cb3f make connections more variable 2024-11-01 12:02:11 +01:00
Joachim Lusiardi d42d8a12b4 make spiders more visible 2024-11-01 08:49:12 +01:00
Joachim Lusiardi 8ee142586b make monsters visible 2024-10-31 22:39:11 +01:00
Joachim Lusiardi 1878959e69 Clippy 2024-10-31 22:36:23 +01:00
Joachim Lusiardi 8bae1c7668 formatted 2024-10-31 22:34:35 +01:00
Joachim Lusiardi 3096386ad1 improve paths 2024-10-31 21:52:04 +01:00
Joachim Lusiardi f5d257e826 more work on generator and tests 2024-10-31 15:20:39 +01:00
Joachim Lusiardi a82a847ecd more tests 2024-10-31 09:58:15 +01:00
Joachim Lusiardi 50d98bfb4d work on level generation including tests 2024-10-31 07:48:22 +01:00
Joachim Lusiardi c429784775 run tests on all branches 2024-10-30 13:06:26 +01:00
Joachim Lusiardi e96660cea0 redo some colors 2024-10-30 13:01:28 +01:00
Joachim Lusiardi c6492c28c2 work on level generator 2024-10-30 08:56:45 +01:00
Joachim Lusiardi 7f288dbcd1 first version of the level new generator
monsters and artefact are missing
roomsize is fixed
2024-10-29 06:48:45 +01:00
Joachim Lusiardi 74831857cf fix monster percentage 2024-10-27 06:24:40 +01:00
Joachim Lusiardi 1ae7ff45ab Rename treasure room 2024-10-27 06:24:14 +01:00
Joachim Lusiardi b833b43c7c Extract constants and make monsters variable per level 2024-10-26 17:00:51 +02:00
Joachim Lusiardi e490011b4e use macros to create monsters 2024-10-25 07:21:34 +02:00
Joachim Lusiardi 8267ad083f fix player tests 2024-10-24 09:09:29 +02:00
Joachim Lusiardi 38dc7285c2 try to improve monster handling 2024-10-24 08:57:52 +02:00
Joachim Lusiardi 6f4c37728f make size of levels variable 2024-10-23 15:54:33 +02:00
Joachim Lusiardi 5111fec1fa fixed message while changing levels 2024-10-23 15:53:28 +02:00
Joachim Lusiardi 9fb3c83b67 more documentation 2024-10-23 15:53:04 +02:00
Joachim Lusiardi 9ae713b6c8 make variable inventory slots 2024-10-22 13:39:43 +02:00
Joachim Lusiardi 5949b2a2d6 limit inventory to 10 slots 2024-10-21 21:59:55 +02:00
Joachim Lusiardi 2b8f7eebba unused potions now are collected in the inventory and can be consumed with the p key 2024-10-21 21:52:07 +02:00
Joachim Lusiardi a0635de65a reorder key handling 2024-10-21 20:37:52 +02:00
Joachim Lusiardi d6f4fdaa5b add CI/CD 2024-10-21 08:30:24 +02:00
Joachim Lusiardi 8dfe56a3c2 randomize content of chests and potions 2024-10-21 08:27:55 +02:00
Joachim Lusiardi b3d85ac7b3 Improved fights between player and monster 2024-10-21 08:26:51 +02:00
Joachim Lusiardi cefb0cc5f2 improve combat system 2024-10-20 22:12:28 +02:00
Joachim Lusiardi efc4cdd363 updated deps
fixed clippy remarks
2024-10-20 14:59:20 +02:00
Joachim Lusiardi 210d590e38 prevent player from leaving the field 2024-01-03 09:12:00 +01:00
Joachim Lusiardi e4018d9cce remove unused import 2024-01-01 15:34:52 +01:00
Joachim Lusiardi f6bb0a9297 version can be displayed as message 2023-12-31 18:10:09 +01:00
Joachim Lusiardi b6d61e4bd1 Merge remote-tracking branch 'origin/include_git_hash' into add_messages 2023-12-31 17:45:42 +01:00
Joachim Lusiardi 85496e3200 make git commit hash available at compile time 2023-12-31 17:41:59 +01:00
Joachim Lusiardi 4770a21abe for changes to add messages 2023-12-31 15:59:52 +01:00
Joachim Lusiardi a69e89c806 Only consume potions if they have an effect 2023-12-30 16:44:23 +01:00
Joachim Lusiardi b3d64f7438 Monsters can attack player now 2023-12-30 16:31:27 +01:00
Joachim Lusiardi b88bc67c50 monsters move and attack the player 2023-12-26 19:11:41 +01:00
Joachim Lusiardi 2098bedabe make monsters more like players 2023-12-26 11:38:23 +01:00
Joachim Lusiardi c0d51f501f extract has_position trait 2023-12-25 13:47:15 +01:00
Joachim Lusiardi bb8a24aa91 clean up monsters 2023-12-25 13:26:45 +01:00
Joachim Lusiardi 67faae44b1 Prevent crashes when terminal is too small 2023-12-25 08:44:44 +01:00
Joachim Lusiardi de5ea76913 step to xp 2023-12-22 20:10:30 +01:00
Joachim Lusiardi 6082a740e9 make chest's gold depend on level 2023-12-22 09:52:50 +01:00
Joachim Lusiardi db96dc5c8a Add gold to the result message 2023-12-21 23:13:13 +01:00
Joachim Lusiardi 2a86201c3e add 3 distinct outcomes for the game 2023-12-21 23:02:06 +01:00
Joachim Lusiardi 6b6206370b Make enemies randomized 2023-12-18 17:04:48 +01:00
Joachim Lusiardi 73315a7636 monsters as trait 2023-12-18 16:11:19 +01:00
Joachim Lusiardi 7ac3b76e6c add some documentation 2023-12-17 22:00:42 +01:00
Joachim Lusiardi f87712e8d2 clean up code 2023-12-17 19:48:58 +01:00
Joachim Lusiardi 8b21e179c2 fight monsters, collect artifacts 2023-12-17 16:14:17 +01:00
User Jlusiardi 643f3b76f9 More work 2023-12-09 22:43:06 +01:00
Joachim Lusiardi 206a49fb08 reworked level widget to stateful widget 2023-12-09 20:16:03 +01:00
Joachim Lusiardi 6e2441aad1 give different artifacts differen looks 2023-12-09 20:05:39 +01:00
Joachim Lusiardi 4a024a47d9 randomize artifact generation 2023-12-09 17:39:26 +01:00
Joachim Lusiardi e47036bd8d more tests 2023-12-09 08:43:41 +01:00
Joachim Lusiardi 7b0eaf6640 add test & fix bug 2023-12-06 21:02:40 +01:00
Joachim Lusiardi 6aee9d974f Move works again 2023-12-06 03:18:59 +01:00
Joachim Lusiardi 21a292b7ad make stuff public 2023-12-05 17:13:39 +01:00
Joachim Lusiardi aa3fa6efb1 Work on levelgenerator 2023-12-04 18:41:21 +01:00
Joachim Lusiardi 2eeb95e3a3 Add variable artifacts 2023-12-03 23:59:05 +01:00
Joachim Lusiardi 07c629bdaa add gold to the player 2023-12-03 21:20:16 +01:00
Joachim Lusiardi 220607133a Add Artifacts 2023-12-03 13:44:29 +01:00
Joachim Lusiardi 900739190d Monsters can be removed 2023-12-03 10:41:43 +01:00
Joachim Lusiardi 209a277684 Monsters can move 2023-12-03 09:36:58 +01:00
Joachim Lusiardi 1ba1ed7de4 Monster in Level 2023-12-03 09:25:03 +01:00
Joachim Lusiardi ee1f11cd1f Cleanup 2023-11-27 21:24:43 +01:00
Joachim Lusiardi 677acf771a first steps with refs 2023-11-27 19:21:10 +01:00
Joachim Lusiardi 227e44dd43 Work on more references 2023-11-26 20:14:33 +01:00
21 changed files with 3518 additions and 103 deletions

View File

@ -0,0 +1,16 @@
name: publish package
on:
push:
branches-ignore:
- main
jobs:
Explore-Gitea-Actions:
runs-on: ubuntu-latest
steps:
- name: Check out repository code
uses: actions/checkout@v4
- name: run tests
run: |
cd ${{ gitea.workspace }}
cargo test

View File

@ -0,0 +1,28 @@
name: publish package
on:
push:
branches:
- main
jobs:
Explore-Gitea-Actions:
runs-on: ubuntu-latest
steps:
- name: Check out repository code
uses: actions/checkout@v4
- name: run tests
run: |
cd ${{ gitea.workspace }}
cargo test --release
- name: build & release package
run: |
cd ${{ gitea.workspace }}
cargo build --release
cargo deb
ls -al target/debian
UPLOAD_FILE=$(ls target/debian/*.deb)
curl --user jlusiardi:${{ secrets.UPLOAD_TOKEN }} --upload-file ${UPLOAD_FILE} https://gitea.intern.haus-in-hirschaid.de/api/packages/jlusiardi/debian/pool/bionic/main/upload
echo -e "${{ secrets.DEPLOY_PRIVATE_KEY }}" > /tmp/ssh_key
chmod 0600 /tmp/ssh_key
scp -o StrictHostKeyChecking=no -i /tmp/ssh_key ${UPLOAD_FILE} jlusiardi@april2023.lusiardi.de:/var/www/p17.lusiardi.de/el_diabolo
ssh -o StrictHostKeyChecking=no -i /tmp/ssh_key jlusiardi@april2023.lusiardi.de /var/www/p17.lusiardi.de/el_diabolo/generate_index.sh

1
.gitignore vendored
View File

@ -1 +1,2 @@
/target /target
*.profraw

524
Cargo.lock generated
View File

@ -38,12 +38,27 @@ version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07" checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07"
[[package]]
name = "bumpalo"
version = "3.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec"
[[package]] [[package]]
name = "cassowary" name = "cassowary"
version = "0.3.0" version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53" checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"
[[package]]
name = "castaway"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0abae9be0aaf9ea96a3b1b8b1b55c602ca751eba1b1500220cea4ecbafe7c0d5"
dependencies = [
"rustversion",
]
[[package]] [[package]]
name = "cfg-if" name = "cfg-if"
version = "1.0.0" version = "1.0.0"
@ -51,16 +66,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]] [[package]]
name = "crossterm" name = "compact_str"
version = "0.27.0" version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f476fe445d41c9e991fd07515a6f463074b782242ccf4a5b7b1d1012e70824df" checksum = "6050c3a16ddab2e412160b31f2c871015704239bca62f72f6e5f0be631d3f644"
dependencies = [
"castaway",
"cfg-if",
"itoa",
"rustversion",
"ryu",
"static_assertions",
]
[[package]]
name = "crossterm"
version = "0.28.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6"
dependencies = [ dependencies = [
"bitflags 2.4.1", "bitflags 2.4.1",
"crossterm_winapi", "crossterm_winapi",
"libc",
"mio", "mio",
"parking_lot", "parking_lot",
"rustix",
"signal-hook", "signal-hook",
"signal-hook-mio", "signal-hook-mio",
"winapi", "winapi",
@ -75,6 +104,41 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "darling"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95133861a8032aaea082871032f5815eb9e98cef03fa916ab4500513994df9e5"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn",
]
[[package]]
name = "darling_macro"
version = "0.20.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806"
dependencies = [
"darling_core",
"quote",
"syn",
]
[[package]] [[package]]
name = "either" name = "either"
version = "1.9.0" version = "1.9.0"
@ -83,10 +147,53 @@ checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07"
[[package]] [[package]]
name = "el_diabolo" name = "el_diabolo"
version = "0.1.0" version = "0.2.2"
dependencies = [ dependencies = [
"crossterm", "crossterm",
"macros",
"petgraph",
"rand",
"ratatui", "ratatui",
"whoami",
]
[[package]]
name = "equivalent"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
[[package]]
name = "errno"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fixedbitset"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "getrandom"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe9006bed769170c11f845cf00c7c1e9092aeb3f268e007c3e760ac68008070f"
dependencies = [
"cfg-if",
"libc",
"wasi",
] ]
[[package]] [[package]]
@ -101,30 +208,83 @@ dependencies = [
[[package]] [[package]]
name = "heck" name = "heck"
version = "0.4.1" version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "hermit-abi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "indexmap"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d530e1a18b1cb4c484e6e34556a0d948706958449fca0cab753d649f2bce3d1f"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]] [[package]]
name = "indoc" name = "indoc"
version = "2.0.4" version = "2.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e186cfbae8084e513daff4240b4797e342f988cecda4fb6c939150f96315fd8" checksum = "b248f5224d1d606005e02c97f5aa4e88eeb230488bcc03bc9ca4d7991399f2b5"
[[package]]
name = "instability"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b23a0c8dfe501baac4adf6ebbfa6eddf8f0c07f56b058cc1288017e32397846c"
dependencies = [
"quote",
"syn",
]
[[package]] [[package]]
name = "itertools" name = "itertools"
version = "0.11.0" version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [ dependencies = [
"either", "either",
] ]
[[package]] [[package]]
name = "libc" name = "itoa"
version = "0.2.149" version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a08173bc88b7955d1b3145aa561539096c421ac8debde8cbc3612ec635fee29b" checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b"
[[package]]
name = "js-sys"
version = "0.3.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cee9c64da59eae3b50095c18d3e74f8b73c0b86d2792824ff01bbce68ba229ca"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "libc"
version = "0.2.161"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9489c2807c139ffd9c1794f4af0ebe86a828db53ecdc7fea2111d0fed085d1"
[[package]]
name = "linux-raw-sys"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89"
[[package]] [[package]]
name = "lock_api" name = "lock_api"
@ -152,11 +312,22 @@ dependencies = [
] ]
[[package]] [[package]]
name = "mio" name = "macros"
version = "0.8.9" version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3dce281c5e46beae905d4de1870d8b1509a9142b62eedf18b443b011ca8343d0"
dependencies = [ dependencies = [
"darling",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "mio"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80e04d1dcff3aae0704555fe5fee3bcfaf3d1fdf8a7e521d5b9d2b42acb52cec"
dependencies = [
"hermit-abi",
"libc", "libc",
"log", "log",
"wasi", "wasi",
@ -187,9 +358,9 @@ checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"libc", "libc",
"redox_syscall", "redox_syscall 0.4.1",
"smallvec", "smallvec",
"windows-targets", "windows-targets 0.48.5",
] ]
[[package]] [[package]]
@ -199,39 +370,88 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c"
[[package]] [[package]]
name = "proc-macro2" name = "petgraph"
version = "1.0.69" version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da" checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db"
dependencies = [
"fixedbitset",
"indexmap",
]
[[package]]
name = "ppv-lite86"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]
name = "proc-macro2"
version = "1.0.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e"
dependencies = [ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.33" version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
] ]
[[package]] [[package]]
name = "ratatui" name = "rand"
version = "0.24.0" version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ebc917cfb527a566c37ecb94c7e3fd098353516fb4eb6bea17015ade0182425" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom",
]
[[package]]
name = "ratatui"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b"
dependencies = [ dependencies = [
"bitflags 2.4.1", "bitflags 2.4.1",
"cassowary", "cassowary",
"compact_str",
"crossterm", "crossterm",
"indoc", "indoc",
"instability",
"itertools", "itertools",
"lru", "lru",
"paste", "paste",
"strum", "strum",
"unicode-segmentation", "unicode-segmentation",
"unicode-width", "unicode-truncate",
"unicode-width 0.2.0",
] ]
[[package]] [[package]]
@ -243,12 +463,40 @@ dependencies = [
"bitflags 1.3.2", "bitflags 1.3.2",
] ]
[[package]]
name = "redox_syscall"
version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b6dfecf2c74bce2466cabf93f6664d6998a69eb21e39f4207930065b27b771f"
dependencies = [
"bitflags 2.4.1",
]
[[package]]
name = "rustix"
version = "0.38.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8acb788b847c24f28525660c4d7758620a7210875711f79e7f663cc152726811"
dependencies = [
"bitflags 2.4.1",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]] [[package]]
name = "rustversion" name = "rustversion"
version = "1.0.14" version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4"
[[package]]
name = "ryu"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"
[[package]] [[package]]
name = "scopeguard" name = "scopeguard"
version = "1.2.0" version = "1.2.0"
@ -267,9 +515,9 @@ dependencies = [
[[package]] [[package]]
name = "signal-hook-mio" name = "signal-hook-mio"
version = "0.2.3" version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af" checksum = "34db1a06d485c9142248b7a054f034b349b212551f3dfd19c94d45a754a217cd"
dependencies = [ dependencies = [
"libc", "libc",
"mio", "mio",
@ -292,19 +540,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a" checksum = "942b4a808e05215192e39f4ab80813e599068285906cc91aa64f923db842bd5a"
[[package]] [[package]]
name = "strum" name = "static_assertions"
version = "0.25.0" version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "strum"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"
dependencies = [ dependencies = [
"strum_macros", "strum_macros",
] ]
[[package]] [[package]]
name = "strum_macros" name = "strum_macros"
version = "0.25.3" version = "0.26.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23dc1fa9ac9c169a78ba62f0b841814b7abae11bdd047b9c58f893439e309ea0" checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"
dependencies = [ dependencies = [
"heck", "heck",
"proc-macro2", "proc-macro2",
@ -315,9 +575,9 @@ dependencies = [
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.38" version = "2.0.85"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e96b79aaa137db8f61e26363a0c9b47d8b4ec75da28b7d1d614c2303e232408b" checksum = "5023162dfcd14ef8f32034d8bcd4cc5ddc61ef7a247c024a33e24e1f24d21b56"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -337,10 +597,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36"
[[package]] [[package]]
name = "unicode-width" name = "unicode-truncate"
version = "0.1.11" version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85" checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf"
dependencies = [
"itertools",
"unicode-segmentation",
"unicode-width 0.1.14",
]
[[package]]
name = "unicode-width"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
[[package]]
name = "unicode-width"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd"
[[package]] [[package]]
name = "version_check" name = "version_check"
@ -354,6 +631,87 @@ version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasite"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b"
[[package]]
name = "wasm-bindgen"
version = "0.2.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ed0d4f68a3015cc185aff4db9506a015f4b96f95303897bfa23f846db54064e"
dependencies = [
"cfg-if",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b56f625e64f3a1084ded111c4d5f477df9f8c92df113852fa5a374dbda78826"
dependencies = [
"bumpalo",
"log",
"once_cell",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0162dbf37223cd2afce98f3d0785506dcb8d266223983e4b5b525859e6e182b2"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0eb82fcb7930ae6219a7ecfd55b217f5f0893484b7a13022ebb2b2bf20b5283"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ab9b36309365056cd639da3134bf87fa8f3d86008abf99e612384a6eecd459f"
[[package]]
name = "web-sys"
version = "0.3.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50c24a44ec86bb68fbecd1b3efed7e85ea5621b39b35ef2766b66cd984f8010f"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "whoami"
version = "1.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "372d5b87f58ec45c384ba03563b03544dc5fadc3983e434b286913f5b4a9bb6d"
dependencies = [
"redox_syscall 0.5.7",
"wasite",
"web-sys",
]
[[package]] [[package]]
name = "winapi" name = "winapi"
version = "0.3.9" version = "0.3.9"
@ -378,11 +736,11 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.48.0" version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [ dependencies = [
"windows-targets", "windows-targets 0.52.6",
] ]
[[package]] [[package]]
@ -391,13 +749,29 @@ version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
dependencies = [ dependencies = [
"windows_aarch64_gnullvm", "windows_aarch64_gnullvm 0.48.5",
"windows_aarch64_msvc", "windows_aarch64_msvc 0.48.5",
"windows_i686_gnu", "windows_i686_gnu 0.48.5",
"windows_i686_msvc", "windows_i686_msvc 0.48.5",
"windows_x86_64_gnu", "windows_x86_64_gnu 0.48.5",
"windows_x86_64_gnullvm", "windows_x86_64_gnullvm 0.48.5",
"windows_x86_64_msvc", "windows_x86_64_msvc 0.48.5",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
] ]
[[package]] [[package]]
@ -406,42 +780,90 @@ version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]] [[package]]
name = "windows_aarch64_msvc" name = "windows_aarch64_msvc"
version = "0.48.5" version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]] [[package]]
name = "windows_i686_gnu" name = "windows_i686_gnu"
version = "0.48.5" version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]] [[package]]
name = "windows_i686_msvc" name = "windows_i686_msvc"
version = "0.48.5" version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]] [[package]]
name = "windows_x86_64_gnu" name = "windows_x86_64_gnu"
version = "0.48.5" version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]] [[package]]
name = "windows_x86_64_gnullvm" name = "windows_x86_64_gnullvm"
version = "0.48.5" version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]] [[package]]
name = "windows_x86_64_msvc" name = "windows_x86_64_msvc"
version = "0.48.5" version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]] [[package]]
name = "zerocopy" name = "zerocopy"
version = "0.7.19" version = "0.7.19"

View File

@ -1,10 +1,28 @@
[workspace]
members = ["macros"]
[package] [package]
name = "el_diabolo" name = "el_diabolo"
version = "0.1.0" version = "0.2.2"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
ratatui = "0.24.0" ratatui = "0.29.0"
crossterm = "0.27.0" crossterm = "0.28.1"
rand = "0.8.5"
petgraph = "0.6.5"
whoami = "1.5.2"
macros = { path = "./macros" }
[package.metadata.deb]
maintainer = "Joachim Lusiardi <joachim@lusiardi.de>"
copyright = "2024, Joachim Lusiardi <joachim@lusiardi.de>"
extended-description = """Little roguelike game"""
depends = "$auto"
section = "game"
priority = "optional"
assets = [
["target/release/el_diabolo", "/usr/bin/", "755"],
]

10
build.rs Normal file
View File

@ -0,0 +1,10 @@
use std::process::Command;
fn main() {
let output = Command::new("git")
.args(["rev-parse", "--short", "HEAD"])
.output()
.unwrap();
let git_hash = String::from_utf8(output.stdout).unwrap();
println!("cargo:rustc-env=GIT_HASH={}", git_hash);
}

10
coverage.md Normal file
View File

@ -0,0 +1,10 @@
```
cargo install grcov
rustup component add llvm-tools-preview
```
```
RUSTFLAGS="-Cinstrument-coverage" cargo clean
RUSTFLAGS="-Cinstrument-coverage" cargo test
grcov . --binary-path ./target/debug/deps/ -s . -t html --branch --ignore-not-existing --ignore '../*' --ignore "/*" -o target/coverage/html
```

17
macros/Cargo.toml Normal file
View File

@ -0,0 +1,17 @@
[package]
name = "macros"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "macros"
path = "src/lib.rs"
proc-macro = true
[dependencies]
syn = "2.0.85"
quote = "1.0.37"
proc-macro2 = "1.0.89"
darling= "0.20.10"

57
macros/src/lib.rs Normal file
View File

@ -0,0 +1,57 @@
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
#[proc_macro_derive(CreateMonsters)]
pub fn create_monsters(input: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(input as syn::File);
let (enum_item, _) = match &input.items[0] {
syn::Item::Enum(enum_item) => (enum_item, &enum_item.attrs),
_ => panic!("must be an enum"),
};
let structs = enum_item.variants.iter().map(|variant| {
let variant_name = &variant.ident;
let t = quote! {
pub struct #variant_name {
name: String,
life: usize,
position: Position,
symbol: String,
color: Color,
experience_gain: usize,
ticks_between_steps: u128,
damage_range: RangeInclusive<usize>,
}
impl Monster for #variant_name {
fn get_name(&self) -> &str { &self.name }
fn is_dead(&self) -> bool { self.life <= 0 }
fn get_experience_gain(&self) -> usize { self.experience_gain }
fn get_representation(&self) -> (&str, Color) { (&self.symbol, self.color) }
fn decrease_life(&mut self, by: usize) {
self.life = self.life.saturating_sub(by);
}
fn get_ticks_between_steps(&self) -> u128 { self.ticks_between_steps }
fn damage(&self) -> usize { rand::thread_rng().gen_range(self.damage_range.clone()) }
#[cfg(test)]
fn get_life(&self) -> usize { self.life }
}
impl HasPosition for #variant_name {
fn get_position(&mut self) -> &mut Position {
&mut self.position
}
fn get_immutable_position(&self) -> &Position {
&self.position
}
}
};
t
});
let output = quote::quote! {
#(#structs)*
};
output.into()
}

122
src/artifacts.rs Normal file
View File

@ -0,0 +1,122 @@
use rand::Rng;
use ratatui::style::Color;
use crate::player::Player;
use crate::position::Position;
pub trait Artifact {
//! An artifact that can be collected by the player
/// get the character and color used to draw the artifact into the level
fn get_representation(&self) -> (&str, Color);
/// get the position of the artifact in the level
fn get_immutable_position(&self) -> &Position;
/// call to apply the effects of the artifact to the player
fn collect(&mut self, player: &mut Player, messages: &mut Vec<String>);
/// returns if the artifact was collected and can be removed from the level
fn was_collected(&self) -> bool;
}
/// An artifact that contains a random amount of gold pieces.
pub struct Chest {
/// the chests position
position: Position,
/// the chests value
gold: usize,
}
impl Chest {
/// create a chest at the given position with a random amount of gold.
/// The gold amount depends on the level, the deeper you go, the more you get.
pub fn new(position: Position) -> Self {
let min_gold = 10 * (position.get_level() + 1);
let max_gold = min_gold + 10 * position.get_level();
Self {
position,
gold: rand::thread_rng().gen_range(min_gold..=max_gold),
}
}
}
impl Artifact for Chest {
fn get_representation(&self) -> (&str, Color) {
("C", Color::Cyan)
}
fn get_immutable_position(&self) -> &Position {
&self.position
}
fn collect(&mut self, player: &mut Player, messages: &mut Vec<String>) {
player.retrieve_gold(self.gold);
messages.insert(
0,
format!("opened chest and collected {} gold.", self.gold).to_string(),
);
self.gold = 0;
}
fn was_collected(&self) -> bool {
self.gold == 0
}
}
#[derive(Clone, Copy)]
/// An artifact that gives the player some health on consumption.
pub struct Potion {
/// a potion that restores some health
position: Position,
health: usize,
was_collected: bool,
}
impl Potion {
pub fn new(position: Position) -> Self {
let min_health_gain = 5 + position.get_level();
let max_health_gain = min_health_gain + 3 * position.get_level();
Self {
position,
health: rand::thread_rng().gen_range(min_health_gain..=max_health_gain),
was_collected: false,
}
}
pub fn get_health(&self) -> usize {
self.health
}
}
impl Artifact for Potion {
fn get_representation(&self) -> (&str, Color) {
("P", Color::Green)
}
fn get_immutable_position(&self) -> &Position {
&self.position
}
fn collect(&mut self, player: &mut Player, messages: &mut Vec<String>) {
//! called when the player walked on to a potion.
//!
//! Depending on health status and inventory usage the potion will
//! be consumed directly or moved to inventory.
if !player.is_healthy() {
let old = player.get_life();
player.change_life(self.health.try_into().unwrap());
let new = player.get_life();
messages.insert(
0,
format!("picked up potion and gained {} health.", new - old).to_string(),
);
self.health = 0;
self.was_collected = true;
} else if player.add_to_inventory(self) {
messages.insert(0, "move potion to inventory.".to_string());
self.was_collected = true;
} else {
messages.insert(0, "inventory is full.".to_string());
}
}
fn was_collected(&self) -> bool {
self.was_collected
}
}

137
src/constants.rs Normal file
View File

@ -0,0 +1,137 @@
use std::{collections::HashMap, ops::RangeInclusive};
use crate::{monster::MonsterTypes, room::RoomType};
/// the number of rooms in vertical direction
pub const ROOMS_HORIZONTAL: usize = 8;
/// the number of rooms in horizontal direction
pub const ROOMS_VERTICAL: usize = 7;
/// the width of a room in the grid of rooms (number of characters)
pub const ROOM_WIDTH: usize = 9;
/// the height of a room in the grid of rooms (number of characters)
pub const ROOM_HEIGHT: usize = 6;
// the minmal width of a room
pub const ROOM_MIN_WIDTH: usize = 4;
// the minmal height of a room
pub const ROOM_MIN_HEIGHT: usize = 4;
/// How many levels does the dungeon have?
pub const LEVELS: usize = 4;
/// length of a game frame in ms
pub const FRAME_LENGTH: u64 = 100;
/// define the minimum width of a terminal to run the game, must be at least the level width plus some space for stats and messages
pub const MIN_WIDTH: u16 = 120;
/// define the minimum height of a terminal to run the game, this must be at least the level height!
pub const MIN_HEIGHT: u16 = LEVEL_HEIGHT as u16;
/// the calculated width of a level
pub const LEVEL_WIDTH: usize = 1 + ROOMS_HORIZONTAL * ROOM_WIDTH;
/// the calculated height of a level
pub const LEVEL_HEIGHT: usize = 1 + ROOMS_VERTICAL * ROOM_HEIGHT;
pub fn get_monsters_per_level() -> Vec<HashMap<MonsterTypes, std::ops::RangeInclusive<u8>>> {
let tmp = [
// level 1
vec![(MonsterTypes::Rat, 50), (MonsterTypes::Spider, 50)],
// level 2
vec![(MonsterTypes::Rat, 50), (MonsterTypes::Snake, 50)],
// level 3
vec![
(MonsterTypes::Orc, 34),
(MonsterTypes::Skeleton, 33),
(MonsterTypes::Snake, 33),
],
// level 4
vec![
(MonsterTypes::Orc, 34),
(MonsterTypes::Skeleton, 33),
(MonsterTypes::Snake, 33),
],
];
if tmp.len() < LEVELS {
panic!(
"Only {} monster sets defined for {} levels!",
tmp.len(),
LEVELS
);
}
let mut result: Vec<HashMap<MonsterTypes, std::ops::RangeInclusive<u8>>> = vec![];
for (idx, level) in tmp.iter().enumerate() {
let mut sum = 0;
let mut map: HashMap<MonsterTypes, RangeInclusive<u8>> = HashMap::new();
for monster in level {
map.insert(monster.0, RangeInclusive::new(sum + 1, sum + monster.1));
sum += monster.1;
}
if sum != 100 {
panic!(
"all percentages must add to 100 (was {}) per level, error in level {}!",
sum,
idx + 1
);
}
result.push(map);
}
result
}
pub fn get_room_type_per_level() -> Vec<HashMap<RoomType, std::ops::RangeInclusive<u8>>> {
let tmp = [
// level 1
vec![
(RoomType::EmptyRoom, 50),
(RoomType::ArtifactRoom, 10),
(RoomType::MonsterRoom, 20),
(RoomType::BasicRoom, 20),
],
// level 2
vec![
(RoomType::EmptyRoom, 50),
(RoomType::BasicRoom, 25),
(RoomType::MonsterRoom, 12),
(RoomType::ArtifactRoom, 13),
],
// level 3
vec![
(RoomType::EmptyRoom, 50),
(RoomType::BasicRoom, 25),
(RoomType::MonsterRoom, 25),
],
// level 4
vec![
(RoomType::BasicRoom, 33),
(RoomType::MonsterRoom, 33),
(RoomType::ArtifactRoom, 34),
],
];
if tmp.len() < LEVELS {
panic!(
"Only {} room sets defined for {} levels!",
tmp.len(),
LEVELS
);
}
let mut result: Vec<HashMap<RoomType, std::ops::RangeInclusive<u8>>> = vec![];
for (idx, level) in tmp.iter().enumerate() {
let mut sum = 0;
let mut map: HashMap<RoomType, RangeInclusive<u8>> = HashMap::new();
for room in level {
map.insert(room.0, RangeInclusive::new(sum + 1, sum + room.1));
sum += room.1;
}
if sum != 100 {
panic!(
"all percentages must add to 100 (was {}) per level, error in level {}!",
sum,
idx + 1
);
}
result.push(map);
}
result
}

View File

@ -1,7 +1,261 @@
use crate::level::Level; use crate::constants::LEVELS;
use crate::level::{Level, StructureElement};
use crate::level_generator::LevelGenerator;
use crate::player::Player; use crate::player::Player;
use crate::position::{HasPosition, Position};
pub struct Game { #[derive(PartialEq)]
pub player: Player, /// represents a state of a game
pub levels: [Level; 25] pub enum GameState {
/// the game is ongoing (neither won or lost)
Running,
/// the player died
Lost,
/// the player reached the Ω
Won,
}
/// the main structure to hold all information about the ongoing game
pub struct Game {
/// the player
player: Player,
/// the levels of the game
levels: Vec<Level>,
/// messages that are displayed in the ui
pub messages: Vec<String>,
}
impl Game {
pub fn new(p: Player) -> Game {
let mut v: Vec<Level> = Vec::with_capacity(LEVELS);
for d in 0..LEVELS {
v.push(LevelGenerator::generate(d, d == 0, d == LEVELS - 1).render());
}
let mut g = Game {
player: p,
levels: v,
messages: Vec::with_capacity(10),
};
let start = { g.get_level(0).start };
g.get_mutable_player()
.get_position()
.set(0, start.0, start.1);
g.get_mutable_level(0)
.discover(&Position::new(0, start.0, start.1));
g
}
/// returns true if the player is standing on the End element
fn player_reached_goal(&mut self) -> bool {
match self.next_element(0, 0) {
None => {}
Some(a) => {
if a == StructureElement::End {
return true;
}
}
};
false
}
/// returns the state of the game (depending on player's life and position)
pub fn get_game_state(&mut self) -> GameState {
if self.player.is_dead() {
return GameState::Lost;
}
if self.player_reached_goal() {
return GameState::Won;
}
GameState::Running
}
pub fn get_player(&self) -> &Player {
&self.player
}
pub fn get_mutable_player(&mut self) -> &mut Player {
&mut self.player
}
pub fn get_level(&self, level: usize) -> &Level {
&self.levels[level]
}
pub fn get_mutable_level(&mut self, level: usize) -> &mut Level {
&mut self.levels[level]
}
/// check if the player can move in the given direction. This only checks for structure element
/// limitation as walls.
fn can_move(&mut self, dx: i16, dy: i16) -> bool {
let player_pos = &self.player.get_position();
let level = &mut self.levels[player_pos.get_level()];
level.can_player_move(&self.player, dx, dy)
}
/// returns the position (as tuple) of the next level's start point.
fn next_start(&self) -> (usize, usize, usize) {
let level = self.player.get_immutable_position().get_level() + 1;
let (x, y) = self.levels[level].start;
(level, x, y)
}
/// returns the position (as tuple) of the previous level's end point.
fn prev_end(&self) -> (usize, usize, usize) {
let level = self.player.get_immutable_position().get_level() - 1;
let (x, y) = self.levels[level].end;
(level, x, y)
}
/// get the next structure element sen from the player's position into the given direction.
fn next_element(&mut self, dx: i16, dy: i16) -> Option<StructureElement> {
let player_pos = &self.player.get_position();
let new_x: i16 = player_pos.get_x() as i16 + dx;
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
}
/// move the game's player into the given direction. If on the target field there is a stair,
/// the player follows the stair up/down to the next level.
/// Discovery is performed on the new location of the player.
/// The returned value is the direction that will bring the player back to his original field.
pub fn move_player(&mut self, mut dx: i16, mut dy: i16) -> (i16, i16) {
// verify the player can do the move
if !self.can_move(dx, dy) {
return (-dx, -dy);
}
let player_pos = &self.player.get_position();
let mut player_level = player_pos.get_level();
let structure = self.next_element(dx, dy);
// use stairs if walked onto one
if let Some(e) = structure {
match e {
StructureElement::StairDown => {
(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 + 1));
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 + 1));
self.get_mutable_player()
.get_position()
.set(next_level, x, y);
}
_ => {}
}
};
// update position and discover area on new position
let (new_x, new_y) = self.get_mutable_player().get_position().change(dx, dy);
self.get_mutable_level(player_level)
.discover(&Position::new(player_level, new_x, new_y));
(-dx, -dy)
}
pub fn player_fights_monster(&mut self) -> bool {
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);
match m {
None => {}
Some(m) => {
let player_dmg = self.player.damage();
m.decrease_life(player_dmg);
if m.is_dead() {
let level_up: bool = self.player.gain_experience(m.get_experience_gain());
self.messages.insert(
0,
format!(
"you hit {} for {} damage and kill it.",
m.get_name(),
player_dmg
)
.to_string(),
);
if level_up {
self.messages.insert(
0,
format!(
"you reach a new experience level, it's now {}",
self.player.get_experience_level(),
)
.to_string(),
);
}
} else {
self.messages.insert(
0,
format!("you hit {} for {} damage.", m.get_name(), player_dmg).to_string(),
);
let monster_dmg = m.damage() as i16;
self.player.change_life(-monster_dmg);
self.messages.insert(
0,
format!("{} hits you for {} damage.", m.get_name(), monster_dmg)
.to_string(),
);
}
return m.is_dead();
}
};
true
}
pub fn player_collects_artifact(&mut self) {
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);
match a {
None => {}
Some(a) => {
a.collect(&mut self.player, &mut self.messages);
}
}
}
/// updates the player's current level. This will remove collected artifacts and dead monsters.
pub fn update_level(&mut self, ticks: u128) {
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);
}
}
#[test]
fn game_has_correct_number_of_levels() {
let p = Player::new("foo", 42);
let g = Game::new(p);
assert_eq!(g.levels.len(), LEVELS);
}
#[test]
fn game_has_player() {
let p = Player::new("foo", 42);
let g = Game::new(p);
assert_eq!(g.get_player().get_name(), "foo");
assert_eq!(g.get_player().get_immutable_position().get_level(), 0);
}
#[test]
fn game_has_mutable_player() {
let p = Player::new("foo", 42);
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);
}
#[test]
fn game_get_level() {
let p = Player::new("foo", 42);
let mut g = Game::new(p);
g.get_level(0);
assert_ne!(g.get_level(0).start, (0, 0));
g.get_mutable_level(0).discover(&Position::new(0, 1, 1));
} }

View File

@ -1,38 +1,418 @@
use std::cmp::{max, min};
use rand::rngs::ThreadRng;
use rand::Rng;
use crate::artifacts::Artifact;
#[cfg(test)]
use crate::artifacts::{Chest, Potion};
use crate::constants::LEVEL_HEIGHT;
use crate::constants::LEVEL_WIDTH;
use crate::monster::Monster;
#[cfg(test)]
use crate::monster::{Orc, Rat};
use crate::player::Player;
use crate::position::HasPosition;
use crate::position::Position;
#[derive(Copy, Clone, Debug, PartialEq)] #[derive(Copy, Clone, Debug, PartialEq)]
enum LevelElement { pub enum StructureElement {
Start,
End,
Wall, Wall,
Floor, Floor,
StairDown, StairDown,
StairUp, StairUp,
Unknown,
} }
#[derive(Copy, Clone, Debug, PartialEq)] type PossibleArtifact<'a> = Option<&'a mut Box<(dyn Artifact + 'static)>>;
type PossibleMonster<'a> = Option<&'a mut Box<(dyn Monster + 'static)>>;
pub struct Level { pub struct Level {
structure: [[LevelElement; 25]; 80], pub(crate) level: usize,
pub(crate) structure: [[StructureElement; LEVEL_HEIGHT]; LEVEL_WIDTH],
pub(crate) discovered: [[bool; LEVEL_HEIGHT]; LEVEL_WIDTH],
pub(crate) monsters: Vec<Box<dyn Monster>>,
pub(crate) artifacts: Vec<Box<dyn Artifact>>,
/// the position of the start in the level (either stair up or start point)
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 { impl Level {
pub fn new() -> Level { pub fn get_element(
let mut s = [[LevelElement::Wall; 25]; 80]; &mut self,
s[4][4] = LevelElement::StairDown; x: i16,
s[75][20] = LevelElement::StairUp; y: i16,
) -> (Option<StructureElement>, PossibleMonster, PossibleArtifact) {
if x < 0 || y < 0 {
return (None, None, None);
}
let x = x as usize;
let y = y as usize;
if x >= LEVEL_WIDTH || y >= LEVEL_HEIGHT {
return (None, None, None);
}
if !self.discovered[x][y] {
// #[cfg(test)]
return (Some(StructureElement::Unknown), None, None);
}
let search_pos = &Position::new(self.level, x, y);
let mut res_m: Option<&mut Box<dyn Monster>> = None;
for m in &mut self.monsters {
if m.get_immutable_position() == search_pos {
res_m = Some(m);
}
}
let mut res_a: Option<&mut Box<dyn Artifact>> = None;
for a in &mut self.artifacts {
if a.get_immutable_position() == search_pos {
res_a = Some(a);
}
}
(Some(self.structure[x][y]), res_m, res_a)
}
/// discover the area with in the level around the given position
pub fn discover(&mut self, pos: &Position) {
let x = pos.get_x();
let y = pos.get_y();
// uncover fields directly next to the player
for x_r in max(x - 1, 0)..=min(x + 1, LEVEL_WIDTH - 1) {
for y_r in max(y - 1, 0)..=min(y + 1, LEVEL_HEIGHT - 1) {
self.discovered[x_r][y_r] = true;
}
}
// uncover fields up to 2 fields right of the player
for x_r in x..=min(x + 2, LEVEL_WIDTH - 1) {
self.discovered[x_r][y] = true;
if self.structure[x_r][y] == StructureElement::Wall {
break;
}
}
// uncover fields up to 2 fields below of the player
for y_r in y..=min(y + 2, LEVEL_HEIGHT - 1) {
self.discovered[x][y_r] = true;
if self.structure[x][y_r] == StructureElement::Wall {
break;
}
}
// uncover fields up to 2 fields left of the player
for x_r in (max(x, 2)..x + 2).rev() {
self.discovered[x_r - 2][y] = true;
if self.structure[x_r - 2][y] == StructureElement::Wall {
break;
}
}
// uncover fields up to 2 fields above of the player
for y_r in (max(y, 2)..y + 2).rev() {
self.discovered[x][y_r - 2] = true;
if self.structure[x][y_r - 2] == StructureElement::Wall {
break;
}
}
}
pub fn update(&mut self, ticks: u128, player: &mut Player, messages: &mut Vec<String>) {
for (index, a) in &mut self.artifacts.iter().enumerate() {
if a.was_collected() {
self.artifacts.remove(index);
break;
}
}
for index in 0..self.monsters.len() {
if self.monsters[index].is_dead() {
continue;
}
if 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),
};
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
{
let monster_dmg = self.monsters[index].damage() as i16;
player.change_life(-monster_dmg);
if player.is_dead() {
messages.insert(
0,
format!(
"{} hits you for {} damage and kills you.",
self.monsters[index].get_name(),
monster_dmg
)
.to_string(),
);
} else {
messages.insert(
0,
format!(
"{} hits you for {} damage.",
self.monsters[index].get_name(),
monster_dmg
)
.to_string(),
);
// player not dead => monster can occupy new position
self.monsters[index].get_position().change(-dx, -dy);
// player fights back
let player_dmg = player.damage();
self.monsters[index].decrease_life(player_dmg);
if self.monsters[index].is_dead() {
let level_up: bool = player
.gain_experience(self.monsters[index].get_experience_gain());
messages.insert(
0,
format!(
"you hit {} for {} damage and kill it.",
self.monsters[index].get_name(),
player_dmg
)
.to_string(),
);
if level_up {
messages.insert(
0,
format!(
"you reach a new experience level, it's now {}",
player.get_experience_level(),
)
.to_string(),
);
}
} else {
messages.insert(
0,
format!(
"you hit {} for {} damage.",
self.monsters[index].get_name(),
player_dmg
)
.to_string(),
);
}
}
}
break;
}
}
}
for (index, m) in &mut self.monsters.iter().enumerate() {
if m.is_dead() {
self.monsters.remove(index);
break;
}
}
}
pub fn can_monster_move(&self, agent: &dyn Monster, dx: i16, dy: i16) -> bool {
let agent_pos = agent.get_immutable_position();
let new_x: usize = (agent_pos.get_x() as i16 + dx) as usize;
let new_y: usize = (agent_pos.get_y() as i16 + dy) as usize;
// verify we cannot leave the playing field
if new_x >= LEVEL_WIDTH || new_y >= LEVEL_HEIGHT {
return false;
}
for index in 0..self.monsters.len() {
let pos = self.monsters[index].get_immutable_position();
if pos.get_x() == new_x && pos.get_y() == new_y {
return false;
}
}
self.structure[new_x][new_y] != StructureElement::Wall
}
pub fn can_player_move(&self, agent: &Player, dx: i16, dy: i16) -> bool {
let agent_pos = agent.get_immutable_position();
let new_x: usize = (agent_pos.get_x() as i16 + dx) as usize;
let new_y: usize = (agent_pos.get_y() as i16 + dy) as usize;
// verify we cannot leave the playing field
if new_x >= LEVEL_WIDTH || new_y >= LEVEL_HEIGHT {
return false;
}
self.structure[new_x][new_y] != StructureElement::Wall
}
#[cfg(test)]
pub fn new(level: usize) -> Level {
let mut s = [[StructureElement::Wall; LEVEL_HEIGHT]; LEVEL_WIDTH];
for x in 2..LEVEL_WIDTH - 2 {
for y in 2..LEVEL_HEIGHT - 2 {
s[x][y] = StructureElement::Floor;
}
}
Level { Level {
structure: s level,
structure: s,
discovered: [[false; LEVEL_HEIGHT]; LEVEL_WIDTH],
monsters: Vec::with_capacity(10),
artifacts: Vec::with_capacity(10),
start: (0, 0),
end: (0, 0),
rng: rand::thread_rng(),
} }
} }
pub fn get_element(&self, x: usize, y: usize) -> Option<LevelElement> { #[cfg(test)]
if x >= 80 || y >= 25 { pub fn add_monster(&mut self, mut monster: impl Monster + 'static) -> Result<(), String> {
return None; if self.level != monster.get_position().get_level() {
return Err("Wrong Level".to_string());
} }
Some(self.structure[x][y]) for m in &mut self.monsters {
if m.get_position() == monster.get_position() {
return Err("Position already used".to_string());
}
}
self.monsters.push(Box::new(monster));
Ok(())
}
#[cfg(test)]
pub fn add_artifact(&mut self, artifact: impl Artifact + 'static) -> Result<(), String> {
if self.level != artifact.get_immutable_position().get_level() {
return Err("Wrong Level".to_string());
}
for a in &mut self.artifacts {
if a.get_immutable_position() == artifact.get_immutable_position() {
return Err("Position already used".to_string());
}
}
self.artifacts.push(Box::new(artifact));
Ok(())
} }
} }
#[test] #[test]
fn test_get_element() { fn test_get_element() {
let l = Level::new(); let mut l = Level::new(0);
assert_eq!(l.get_element(0, 0).unwrap(), LevelElement::Wall); assert_eq!(l.get_element(-1, -1).0, None);
assert_eq!(l.get_element(4, 4).unwrap(), LevelElement::StairDown); assert_eq!(l.get_element(0, 0).0.unwrap(), StructureElement::Unknown);
assert_eq!(l.get_element(79, 24).unwrap(), LevelElement::Wall); assert_eq!(
assert_eq!(l.get_element(80, 25), None); 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
);
}
#[test]
fn test_discover_get_element() {
let mut l = Level::new(0);
assert_eq!(l.get_element(10, 10).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);
}
#[test]
fn test_discover_can_add_monster() {
let mut l = Level::new(0);
let m = Rat::new_with_position(Position::new(1, 2, 3));
assert_eq!(l.add_monster(m), Err("Wrong Level".to_string()));
let mut m = Orc::new_with_position(Position::new(0, 2, 3));
m.get_position().set(0, 2, 3);
assert_eq!(l.add_monster(m), Ok(()));
let m = Rat::new_with_position(Position::new(0, 2, 3));
assert_eq!(l.add_monster(m), Err("Position already used".to_string()));
let m = Rat::new_with_position(Position::new(0, 2, 4));
assert_eq!(l.add_monster(m), Ok(()));
}
#[test]
fn test_discover_can_add_artifact() {
let mut l = Level::new(0);
let a = Chest::new(Position::new(1, 2, 3));
assert_eq!(l.add_artifact(a), Err("Wrong Level".to_string()));
let a = Chest::new(Position::new(0, 2, 3));
assert_eq!(l.add_artifact(a), Ok(()));
let a = Potion::new(Position::new(0, 2, 3));
assert_eq!(l.add_artifact(a), Err("Position already used".to_string()));
let a = Chest::new(Position::new(0, 1, 3));
assert_eq!(l.add_artifact(a), Ok(()));
}
#[test]
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());
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);
assert_eq!(elem.0.unwrap(), StructureElement::Floor);
assert!(elem.1.is_some());
let m = elem.1.unwrap();
assert_eq!(m.get_life(), 2);
m.decrease_life(2);
assert_eq!(l.get_element(10, 10).1.unwrap().get_life(), 0);
}
#[test]
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());
let a = Chest::new(Position::new(0, 10, 10));
assert_eq!(l.add_artifact(a), Ok(()));
let elem = l.get_element(10, 10);
assert_eq!(elem.0.unwrap(), StructureElement::Floor);
assert!(elem.2.is_some());
}
#[test]
fn test_discover_get_monster_can_move() {
let mut l = Level::new(0);
let p = Position::new(0, 10, 10);
l.discover(&p);
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();
m.get_position().change(1, 1);
let m = l.get_element(10, 10).1;
assert!(m.is_none());
let m = l.get_element(11, 11).1;
assert!(m.is_some());
assert_eq!(m.unwrap().get_life(), 2);
} }

954
src/level_generator.rs Normal file
View File

@ -0,0 +1,954 @@
use petgraph::algo::min_spanning_tree;
use petgraph::data::*;
use petgraph::graph::Edge;
use petgraph::graph::Graph;
use petgraph::graph::UnGraph;
use rand::Rng;
use rand::{rngs::ThreadRng, seq::SliceRandom};
use crate::artifacts::Artifact;
use crate::artifacts::Chest;
use crate::artifacts::Potion;
use crate::constants::get_monsters_per_level;
use crate::constants::ROOM_HEIGHT;
use crate::constants::ROOM_WIDTH;
use crate::monster::create_monster_by_type;
use crate::monster::Monster;
use crate::position::Position;
use crate::room::Connection;
use crate::{
constants::{
get_room_type_per_level, LEVEL_HEIGHT, LEVEL_WIDTH, ROOMS_HORIZONTAL, ROOMS_VERTICAL,
},
level::{Level, StructureElement},
room::{Room, RoomType},
};
type GeneratorGraph = Graph<(usize, usize), usize, petgraph::Undirected>;
pub struct LevelGenerator {
level: usize,
rooms: [[Room; ROOMS_VERTICAL]; ROOMS_HORIZONTAL],
rng: ThreadRng,
}
enum Direction {
Horizontal,
Vertical,
}
impl LevelGenerator {
fn generate_rooms_to_place(
rng: &mut ThreadRng,
level: usize,
first: bool,
last: bool,
) -> Vec<Room> {
let mut rooms_to_place: Vec<Room> = Vec::with_capacity(ROOMS_VERTICAL * ROOMS_HORIZONTAL);
let mut start_room = Room::new(rng);
if first {
start_room.kind = RoomType::Start;
} else {
start_room.kind = RoomType::StairUp;
}
rooms_to_place.push(start_room);
for _ in 2..ROOMS_HORIZONTAL * ROOMS_VERTICAL {
let mut room = Room::new(rng);
room.kind = LevelGenerator::select_room_type(level, rng);
if room.kind != RoomType::EmptyRoom {
rooms_to_place.push(room);
}
}
let mut end_room = Room::new(rng);
if last {
end_room.kind = RoomType::End;
} else {
end_room.kind = RoomType::StairDown;
}
rooms_to_place.push(end_room);
rooms_to_place
}
fn place_rooms(
rng: &mut ThreadRng,
rooms_to_place: &mut Vec<Room>,
) -> [[Room; ROOMS_VERTICAL]; ROOMS_HORIZONTAL] {
let mut rooms: [[Room; 7]; 8] = [[Room::new(rng); ROOMS_VERTICAL]; ROOMS_HORIZONTAL];
let mut room_row = rng.gen_range(0..ROOMS_VERTICAL);
let mut room_col = rng.gen_range(0..ROOMS_HORIZONTAL);
rooms[room_col][room_row] = rooms_to_place.pop().unwrap();
while let Some(room) = rooms_to_place.pop() {
let mut placed = false;
// randomize going horizontal or vertical
let mut directions_to_try = vec![Direction::Horizontal, Direction::Vertical];
directions_to_try.shuffle(rng);
while !directions_to_try.is_empty() {
match directions_to_try.pop().unwrap() {
Direction::Horizontal => {
let mut free_cols: Vec<usize> = vec![];
for (col, room_col) in rooms.iter().enumerate().take(ROOMS_HORIZONTAL) {
if room_col[room_row].kind == RoomType::EmptyRoom {
free_cols.push(col);
}
}
if free_cols.is_empty() {
continue;
}
free_cols.shuffle(rng);
room_col = *free_cols.first().unwrap();
rooms[room_col][room_row] = room;
placed = true;
break;
}
Direction::Vertical => {
let mut free_rows: Vec<usize> = vec![];
for row in 0..ROOMS_VERTICAL {
if rooms[room_col][row].kind == RoomType::EmptyRoom {
free_rows.push(row);
}
}
if free_rows.is_empty() {
continue;
}
free_rows.shuffle(rng);
room_row = *free_rows.first().unwrap();
rooms[room_col][room_row] = room;
placed = true;
break;
}
}
}
// all fields in the row/column was full so we can place it at any empty position
if !placed {
let mut free_pos: Vec<(usize, usize)> = vec![];
for (col, room_col) in rooms.iter().enumerate().take(ROOMS_HORIZONTAL) {
for (row, room) in room_col.iter().enumerate().take(ROOMS_VERTICAL) {
if room.kind == RoomType::EmptyRoom {
free_pos.push((col, row));
}
}
}
let selected_pos = free_pos[rng.gen_range(0..free_pos.len())];
rooms[selected_pos.0][selected_pos.1] = room;
}
}
rooms
}
fn create_mst(rooms: &[[Room; ROOMS_VERTICAL]; ROOMS_HORIZONTAL]) -> GeneratorGraph {
// calculate the weight of an edge
fn calc_edge_weight(delta: usize) -> usize {
delta * delta
}
let mut graph: GeneratorGraph = UnGraph::<(usize, usize), usize>::default();
for (col, tgt_col) in rooms.iter().enumerate().take(ROOMS_HORIZONTAL) {
for (row, room) in tgt_col.iter().enumerate().take(ROOMS_VERTICAL) {
if room.kind != RoomType::EmptyRoom {
graph.add_node((col, row));
}
}
}
for col in 0..ROOMS_HORIZONTAL {
for row in 0..ROOMS_VERTICAL {
if rooms[col][row].kind == RoomType::EmptyRoom {
continue;
}
if let Some(src_index) = graph.node_indices().find(|i| graph[*i] == (col, row)) {
for (col_1, tgt_col) in rooms
.iter()
.enumerate()
.take(ROOMS_HORIZONTAL)
.skip(col + 1)
{
if tgt_col[row].kind != RoomType::EmptyRoom {
if let Some(tgt_index) =
graph.node_indices().find(|i| graph[*i] == (col_1, row))
{
graph.add_edge(
src_index,
tgt_index,
calc_edge_weight(col.abs_diff(col_1)),
);
break;
}
}
}
for row_1 in row + 1..ROOMS_VERTICAL {
if rooms[col][row_1].kind != RoomType::EmptyRoom {
if let Some(tgt_index) =
graph.node_indices().find(|i| graph[*i] == (col, row_1))
{
graph.add_edge(
src_index,
tgt_index,
calc_edge_weight(row.abs_diff(row_1)),
);
break;
}
}
}
}
}
}
let mut mst: GeneratorGraph = Graph::from_elements(min_spanning_tree(&graph));
// readd some of the short edges that were remove (all between a weight of 1 to 10)
let initial_edges = graph.raw_edges();
let minimal_edges = mst.raw_edges();
let mut extra_edges: Vec<Edge<usize>> = vec![];
for init_edge in initial_edges {
let start_node = init_edge.source();
let end_node = init_edge.target();
let mut found = false;
for min_edge in minimal_edges {
if min_edge.source() == start_node && min_edge.target() == end_node {
found = true;
break;
}
}
if !found {
extra_edges.push(init_edge.clone());
}
}
extra_edges.sort_by(|a, b| a.weight.cmp(&b.weight));
for e in extra_edges
.iter()
.filter(|x| x.weight > 1)
.filter(|x| x.weight < 7)
{
mst.add_edge(e.source(), e.target(), e.weight);
}
mst
}
fn create_connections(
rooms: &mut [[Room; ROOMS_VERTICAL]; ROOMS_HORIZONTAL],
mst: &GeneratorGraph,
) {
for edge in mst.raw_edges() {
// the tuples are (col, row)
let (src_node_col, src_node_row) = mst[edge.source()];
let (tgt_node_col, tgt_node_row) = mst[edge.target()];
let src_room = rooms[src_node_col][src_node_row];
let tgt_room = rooms[tgt_node_col][tgt_node_row];
if src_node_col == tgt_node_col {
// Right
let start_col =
src_node_col * ROOM_WIDTH + src_room.offset_x + (src_room.width + 1) / 2;
let start_row =
src_node_row * ROOM_HEIGHT + src_room.offset_y + src_room.height + 1;
let end_col =
tgt_node_col * ROOM_WIDTH + tgt_room.offset_x + (tgt_room.width + 1) / 2;
let end_row = 1 + tgt_node_row * ROOM_HEIGHT - 1 + tgt_room.offset_y;
rooms[src_node_col][src_node_row].connection_down = Some(Connection {
start_pos: (start_col, start_row),
end_pos: (end_col, end_row),
});
} else {
// Down
let start_col =
1 + (src_node_col * ROOM_WIDTH) + src_room.offset_x + src_room.width;
let start_row =
1 + src_node_row * ROOM_HEIGHT + src_room.offset_y + (src_room.height - 1) / 2;
let end_col = 1 + tgt_node_col * ROOM_WIDTH - 1 + tgt_room.offset_x;
let end_row =
1 + tgt_node_row * ROOM_HEIGHT + tgt_room.offset_y + (tgt_room.height - 1) / 2;
rooms[src_node_col][src_node_row].connection_right = Some(Connection {
start_pos: (start_col, start_row),
end_pos: (end_col, end_row),
});
}
}
}
pub fn generate(level: usize, first: bool, last: bool) -> Self {
let mut rng = rand::thread_rng();
let mut rooms_to_place: Vec<Room> =
LevelGenerator::generate_rooms_to_place(&mut rng, level, first, last);
let mut rooms: [[Room; 7]; 8] = LevelGenerator::place_rooms(&mut rng, &mut rooms_to_place);
let mst: GeneratorGraph = LevelGenerator::create_mst(&rooms);
LevelGenerator::create_connections(&mut rooms, &mst);
LevelGenerator { level, rooms, rng }
}
fn select_monster(position: Position, rng: &mut ThreadRng) -> Box<dyn Monster> {
let level = position.get_level();
let value = rng.gen_range(1..=100);
let t = get_monsters_per_level();
if level < t.len() {
for (mtype, range) in &t[level] {
if range.contains(&value) {
return create_monster_by_type(mtype, position);
}
}
}
panic!("no monster selectable!");
}
fn select_room_type(level: usize, rng: &mut ThreadRng) -> RoomType {
let value = rng.gen_range(1..=100);
let t = get_room_type_per_level();
if level < t.len() {
for (mtype, range) in &t[level] {
if range.contains(&value) {
return *mtype;
}
}
}
panic!("no room selectable!");
}
pub fn render(&mut self) -> Level {
let mut structure = [[StructureElement::Wall; LEVEL_HEIGHT]; LEVEL_WIDTH];
let mut start_pos = (0, 0);
let mut end_pos = (0, 0);
let mut monsters: Vec<Box<dyn Monster>> = Vec::with_capacity(10);
let mut artifacts: Vec<Box<dyn Artifact>> = Vec::with_capacity(10);
for col in 0..ROOMS_HORIZONTAL {
for row in 0..ROOMS_VERTICAL {
let room = self.rooms[col][row];
let position = room.render(&mut structure, col, row);
match room.kind {
RoomType::Start => start_pos = position,
RoomType::End => end_pos = position,
RoomType::StairUp => start_pos = position,
RoomType::StairDown => end_pos = position,
RoomType::BasicRoom => {}
RoomType::ArtifactRoom => {
match self.rng.gen_range(1..=100) {
1..=50 => {
artifacts.push(Box::new(Chest::new(Position::new(
self.level, position.0, position.1,
))));
}
_ => {
artifacts.push(Box::new(Potion::new(Position::new(
self.level, position.0, position.1,
))));
}
};
}
RoomType::MonsterRoom => {
monsters.push(LevelGenerator::select_monster(
Position::new(self.level, position.0, position.1),
&mut self.rng,
));
}
RoomType::EmptyRoom => {}
}
}
}
for col in 0..ROOMS_HORIZONTAL {
for row in 0..ROOMS_VERTICAL {
if let Some(connection) = self.rooms[col][row].connection_down {
// println!("down");
connection.render(&mut self.rng, &mut structure);
}
if let Some(connection) = self.rooms[col][row].connection_right {
// println!("right");
connection.render(&mut self.rng, &mut structure);
}
}
}
Level {
level: self.level,
structure,
discovered: [[false; LEVEL_HEIGHT]; LEVEL_WIDTH],
monsters,
artifacts,
start: start_pos,
end: end_pos,
rng: rand::thread_rng(),
}
}
}
#[test]
fn test_level_gen() {
for _ in 0..1000 {
LevelGenerator::generate(0, true, false).render();
}
}
#[test]
fn test_level_gen_respects_level() {
let level = LevelGenerator::generate(0, true, false).render();
assert_eq!(0, level.level);
let level = LevelGenerator::generate(1, true, false).render();
assert_eq!(1, level.level);
}
#[cfg(test)]
fn find_room_types(rooms: &Vec<Room>) -> (bool, bool, bool, bool) {
let mut start_found = false;
let mut end_found: bool = false;
let mut down_found: bool = false;
let mut up_found: bool = false;
for room in rooms {
if room.kind == RoomType::Start {
start_found = true;
}
if room.kind == RoomType::End {
end_found = true;
}
if room.kind == RoomType::StairDown {
down_found = true;
}
if room.kind == RoomType::StairUp {
up_found = true;
}
}
(start_found, up_found, down_found, end_found)
}
#[test]
fn test_rooms_to_place_first_level() {
let mut rng = rand::thread_rng();
let res = LevelGenerator::generate_rooms_to_place(&mut rng, 0, true, false);
assert!(
res.len() <= ROOMS_HORIZONTAL * ROOMS_VERTICAL,
"too many rooms created"
);
assert!(0 < res.len(), "too many rooms created");
let (start_found, up_found, down_found, end_found) = find_room_types(&res);
assert!(start_found);
assert!(!end_found);
assert!(down_found);
assert!(!up_found);
}
#[test]
fn test_rooms_to_place_middle_level() {
let mut rng = rand::thread_rng();
let res = LevelGenerator::generate_rooms_to_place(&mut rng, 1, false, false);
assert!(
res.len() <= ROOMS_HORIZONTAL * ROOMS_VERTICAL,
"too many rooms created"
);
assert!(0 < res.len(), "too many rooms created");
let (start_found, up_found, down_found, end_found) = find_room_types(&res);
assert!(!start_found);
assert!(!end_found);
assert!(down_found);
assert!(up_found);
}
#[test]
fn test_rooms_to_place_last_level() {
let mut rng = rand::thread_rng();
let res = LevelGenerator::generate_rooms_to_place(&mut rng, 2, false, true);
assert!(
res.len() <= ROOMS_HORIZONTAL * ROOMS_VERTICAL,
"too many rooms created"
);
assert!(0 < res.len(), "too many rooms created");
let (start_found, up_found, down_found, end_found) = find_room_types(&res);
assert!(!start_found);
assert!(end_found);
assert!(!down_found);
assert!(up_found);
}
#[cfg(test)]
fn check_valid_placement(rooms: &[[Room; ROOMS_VERTICAL]; ROOMS_HORIZONTAL]) -> bool {
for col in 0..ROOMS_HORIZONTAL {
for row in 0..ROOMS_VERTICAL {
if rooms[col][row].kind != RoomType::EmptyRoom {
let mut count = 0;
for test_col in 0..ROOMS_HORIZONTAL {
if rooms[test_col][row].kind != RoomType::EmptyRoom {
count += 1;
}
}
for test_row in 0..ROOMS_VERTICAL {
if rooms[col][test_row].kind != RoomType::EmptyRoom {
count += 1;
}
}
if count < 3 {
return false;
}
}
}
}
true
}
#[cfg(test)]
fn count_rooms(rooms: &[[Room; ROOMS_VERTICAL]; ROOMS_HORIZONTAL]) -> usize {
let mut res = 0;
for col in 0..ROOMS_HORIZONTAL {
for row in 0..ROOMS_VERTICAL {
if rooms[col][row].kind != RoomType::EmptyRoom {
res += 1;
}
}
}
res
}
#[test]
fn test_place_rooms() {
let mut rng = rand::thread_rng();
for count in 2..ROOMS_HORIZONTAL * ROOMS_VERTICAL {
let mut rooms: Vec<Room> = vec![Room::new(&mut rng), Room::new(&mut rng)];
rooms[0].kind = RoomType::Start;
rooms[1].kind = RoomType::End;
for t in 2..count {
rooms.push(Room::new(&mut rng));
rooms[t].kind = RoomType::BasicRoom;
}
let res = LevelGenerator::place_rooms(&mut rng, &mut rooms);
assert_eq!(count_rooms(&res), count, "counting {}", count);
assert!(check_valid_placement(&res));
}
}
#[test]
fn test_create_mst() {
let mut rng = rand::thread_rng();
let mut rooms = [[Room::new(&mut rng); ROOMS_VERTICAL]; ROOMS_HORIZONTAL];
let res: GeneratorGraph = LevelGenerator::create_mst(&rooms);
assert_eq!(res.node_count(), 0);
assert_eq!(res.edge_count(), 0);
rooms[1][1].kind = RoomType::BasicRoom;
let res = LevelGenerator::create_mst(&rooms);
assert_eq!(res.node_count(), 1);
assert_eq!(res.edge_count(), 0);
rooms[1][3].kind = RoomType::BasicRoom;
let res = LevelGenerator::create_mst(&rooms);
assert_eq!(res.node_count(), 2);
assert_eq!(res.edge_count(), 1);
rooms[3][1].kind = RoomType::BasicRoom;
let res = LevelGenerator::create_mst(&rooms);
assert_eq!(res.node_count(), 3);
assert_eq!(res.edge_count(), 2);
rooms[3][3].kind = RoomType::BasicRoom;
let res = LevelGenerator::create_mst(&rooms);
assert_eq!(res.node_count(), 4);
assert_eq!(res.edge_count(), 4);
rooms[3][5].kind = RoomType::BasicRoom;
let res = LevelGenerator::create_mst(&rooms);
assert_eq!(res.node_count(), 5);
assert_eq!(res.edge_count(), 5);
}
#[test]
fn test_create_connections() {
let mut rng = rand::thread_rng();
let mut rooms = [[Room::new(&mut rng); ROOMS_VERTICAL]; ROOMS_HORIZONTAL];
rooms[1][0].width = ROOM_WIDTH - 1;
rooms[1][0].offset_x = 0;
rooms[1][0].height = ROOM_HEIGHT - 1;
rooms[1][0].offset_y = 0;
rooms[1][0].kind = RoomType::BasicRoom;
rooms[3][0].width = ROOM_WIDTH - 1;
rooms[3][0].offset_x = 0;
rooms[3][0].height = ROOM_HEIGHT - 1;
rooms[3][0].offset_y = 0;
rooms[3][0].kind = RoomType::BasicRoom;
let mst: GeneratorGraph = LevelGenerator::create_mst(&rooms);
println!("{:?}", mst);
LevelGenerator::create_connections(&mut rooms, &mst);
assert!(rooms[1][0].connection_right.is_some());
assert_eq!(
rooms[1][0].connection_right.unwrap().start_pos,
(18, 3),
"wrong start"
);
assert_eq!(
rooms[1][0].connection_right.unwrap().end_pos,
(27, 3),
"wrong end"
);
assert!(rooms[1][0].connection_down.is_none());
assert!(rooms[3][0].connection_down.is_none());
assert!(rooms[3][0].connection_right.is_none());
}
#[test]
fn test_create_connections_2() {
let mut rng = rand::thread_rng();
let mut rooms = [[Room::new(&mut rng); ROOMS_VERTICAL]; ROOMS_HORIZONTAL];
rooms[1][0].width = ROOM_WIDTH - 1;
rooms[1][0].offset_x = 0;
rooms[1][0].height = ROOM_HEIGHT - 1;
rooms[1][0].offset_y = 0;
rooms[1][0].kind = RoomType::BasicRoom;
rooms[3][0].width = ROOM_WIDTH - 2;
rooms[3][0].offset_x = 1;
rooms[3][0].height = ROOM_HEIGHT - 1;
rooms[3][0].offset_y = 0;
rooms[3][0].kind = RoomType::BasicRoom;
let mst: GeneratorGraph = LevelGenerator::create_mst(&rooms);
LevelGenerator::create_connections(&mut rooms, &mst);
assert!(rooms[1][0].connection_right.is_some());
assert_eq!(
rooms[1][0].connection_right.unwrap().start_pos,
(18, 3),
"wrong start"
);
assert_eq!(
rooms[1][0].connection_right.unwrap().end_pos,
(28, 3),
"wrong end"
);
assert!(rooms[1][0].connection_down.is_none());
assert!(rooms[3][0].connection_down.is_none());
assert!(rooms[3][0].connection_right.is_none());
}
#[test]
fn test_create_connections_d_1() {
let mut rng = rand::thread_rng();
let mut rooms = [[Room::new(&mut rng); ROOMS_VERTICAL]; ROOMS_HORIZONTAL];
rooms[0][1].width = ROOM_WIDTH - 1;
rooms[0][1].offset_x = 0;
rooms[0][1].height = ROOM_HEIGHT - 1;
rooms[0][1].offset_y = 0;
rooms[0][1].kind = RoomType::BasicRoom;
rooms[0][3].width = ROOM_WIDTH - 1;
rooms[0][3].offset_x = 0;
rooms[0][3].height = ROOM_HEIGHT - 1;
rooms[0][3].offset_y = 0;
rooms[0][3].kind = RoomType::BasicRoom;
let mst: GeneratorGraph = LevelGenerator::create_mst(&rooms);
println!("{:?}", mst);
LevelGenerator::create_connections(&mut rooms, &mst);
assert!(rooms[0][1].connection_down.is_some());
assert!(rooms[0][1].connection_right.is_none());
assert!(rooms[0][3].connection_down.is_none());
assert!(rooms[0][3].connection_right.is_none());
assert_eq!(
rooms[0][1].connection_down.unwrap().start_pos,
(4, 12),
"wrong start"
);
assert_eq!(
rooms[0][1].connection_down.unwrap().end_pos,
(4, 18),
"wrong end"
);
}
#[test]
fn test_create_connections_d_2() {
// test full sized rooms for downwards connection
let mut rng = rand::thread_rng();
let mut rooms = [[Room::new(&mut rng); ROOMS_VERTICAL]; ROOMS_HORIZONTAL];
rooms[1][1].width = ROOM_WIDTH - 1;
rooms[1][1].offset_x = 0;
rooms[1][1].height = ROOM_HEIGHT - 1;
rooms[1][1].offset_y = 0;
rooms[1][1].kind = RoomType::BasicRoom;
rooms[1][3].width = ROOM_WIDTH - 1;
rooms[1][3].offset_x = 0;
rooms[1][3].height = ROOM_HEIGHT - 1;
rooms[1][3].offset_y = 0;
rooms[1][3].kind = RoomType::BasicRoom;
let mst: GeneratorGraph = LevelGenerator::create_mst(&rooms);
LevelGenerator::create_connections(&mut rooms, &mst);
assert!(rooms[1][1].connection_down.is_some());
assert_eq!(
rooms[1][1].connection_down.unwrap().start_pos,
(13, 12),
"wrong start"
);
assert_eq!(
rooms[1][1].connection_down.unwrap().end_pos,
(13, 18),
"wrong end"
);
assert!(rooms[1][1].connection_right.is_none());
assert!(rooms[1][2].connection_down.is_none());
assert!(rooms[1][2].connection_right.is_none());
}
#[test]
fn test_create_connections_d_3() {
// test reduced width rooms (with overlap) for downwards connection
let mut rng = rand::thread_rng();
let mut rooms = [[Room::new(&mut rng); ROOMS_VERTICAL]; ROOMS_HORIZONTAL];
rooms[1][1].width = 5;
rooms[1][1].offset_x = 0;
rooms[1][1].height = ROOM_HEIGHT - 1;
rooms[1][1].offset_y = 0;
rooms[1][1].kind = RoomType::BasicRoom;
rooms[1][3].width = 5;
rooms[1][3].offset_x = 4;
rooms[1][3].height = ROOM_HEIGHT - 1;
rooms[1][3].offset_y = 0;
rooms[1][3].kind = RoomType::BasicRoom;
let mst: GeneratorGraph = LevelGenerator::create_mst(&rooms);
LevelGenerator::create_connections(&mut rooms, &mst);
assert!(rooms[1][1].connection_down.is_some());
assert_eq!(
rooms[1][1].connection_down.unwrap().start_pos,
(ROOM_WIDTH + 3, ROOM_HEIGHT * 2),
"wrong start"
);
assert_eq!(
rooms[1][1].connection_down.unwrap().end_pos,
(ROOM_WIDTH + 7, ROOM_HEIGHT * 3),
"wrong end"
);
assert!(rooms[1][1].connection_right.is_none());
assert!(rooms[1][3].connection_down.is_none());
assert!(rooms[1][3].connection_right.is_none());
}
#[test]
fn test_create_connections_d_4() {
// test reduced width rooms (with NO overlap) for downwards connection
let mut rng = rand::thread_rng();
let mut rooms = [[Room::new(&mut rng); ROOMS_VERTICAL]; ROOMS_HORIZONTAL];
rooms[1][1].width = 3;
rooms[1][1].offset_x = 0;
rooms[1][1].height = ROOM_HEIGHT - 1;
rooms[1][1].offset_y = 0;
rooms[1][1].kind = RoomType::BasicRoom;
rooms[1][3].width = 3;
rooms[1][3].offset_x = 5;
rooms[1][3].height = ROOM_HEIGHT - 1;
rooms[1][3].offset_y = 0;
rooms[1][3].kind = RoomType::BasicRoom;
let mst: GeneratorGraph = LevelGenerator::create_mst(&rooms);
LevelGenerator::create_connections(&mut rooms, &mst);
assert!(rooms[1][1].connection_down.is_some());
assert_eq!(
rooms[1][1].connection_down.unwrap().start_pos,
(ROOM_WIDTH + 2, ROOM_HEIGHT * 2),
"wrong start"
);
assert_eq!(
rooms[1][1].connection_down.unwrap().end_pos,
(ROOM_WIDTH + 7, ROOM_HEIGHT * 3),
"wrong end"
);
assert!(rooms[1][1].connection_right.is_none());
assert!(rooms[1][3].connection_down.is_none());
assert!(rooms[1][3].connection_right.is_none());
}
#[test]
fn test_create_connections_d_5() {
// test reduced and moved width rooms (with NO overlap) for downwards connection
let mut rng = rand::thread_rng();
let mut rooms = [[Room::new(&mut rng); ROOMS_VERTICAL]; ROOMS_HORIZONTAL];
rooms[1][1].width = 3;
rooms[1][1].offset_x = 0;
rooms[1][1].height = 4;
rooms[1][1].offset_y = 0;
rooms[1][1].kind = RoomType::BasicRoom;
rooms[1][3].width = 3;
rooms[1][3].offset_x = 5;
rooms[1][3].height = 4;
rooms[1][3].offset_y = 1;
rooms[1][3].kind = RoomType::BasicRoom;
let mst: GeneratorGraph = LevelGenerator::create_mst(&rooms);
LevelGenerator::create_connections(&mut rooms, &mst);
assert!(rooms[1][1].connection_down.is_some());
assert_eq!(
rooms[1][1].connection_down.unwrap().start_pos,
(11, 11),
"wrong start"
);
assert_eq!(
rooms[1][1].connection_down.unwrap().end_pos,
(16, 19),
"wrong end"
);
assert!(rooms[1][1].connection_right.is_none());
assert!(rooms[1][3].connection_down.is_none());
assert!(rooms[1][3].connection_right.is_none());
}
#[test]
fn test_create_connections_right_1() {
let mut rng = rand::thread_rng();
let mut rooms = [[Room::new(&mut rng); ROOMS_VERTICAL]; ROOMS_HORIZONTAL];
rooms[1][1].width = ROOM_WIDTH - 1;
rooms[1][1].offset_x = 0;
rooms[1][1].height = ROOM_HEIGHT - 1;
rooms[1][1].offset_y = 0;
rooms[1][1].kind = RoomType::BasicRoom;
rooms[3][1].width = ROOM_WIDTH - 1;
rooms[3][1].offset_x = 0;
rooms[3][1].height = ROOM_HEIGHT - 1;
rooms[3][1].offset_y = 0;
rooms[3][1].kind = RoomType::BasicRoom;
let mst: GeneratorGraph = LevelGenerator::create_mst(&rooms);
LevelGenerator::create_connections(&mut rooms, &mst);
assert!(rooms[1][1].connection_down.is_none());
assert!(rooms[1][1].connection_right.is_some());
assert_eq!(
rooms[1][1].connection_right.unwrap().start_pos,
(18, 9),
"wrong start"
);
assert_eq!(
rooms[1][1].connection_right.unwrap().end_pos,
(27, 9),
"wrong end"
);
assert!(rooms[3][1].connection_down.is_none());
assert!(rooms[3][1].connection_right.is_none());
}
#[test]
fn test_create_connections_right_2() {
// test reduced width rooms (with overlap) for downwards connection
let mut rng = rand::thread_rng();
let mut rooms = [[Room::new(&mut rng); ROOMS_VERTICAL]; ROOMS_HORIZONTAL];
rooms[1][1].width = ROOM_WIDTH - 1;
rooms[1][1].offset_x = 0;
rooms[1][1].height = 4;
rooms[1][1].offset_y = 0;
rooms[1][1].kind = RoomType::BasicRoom;
rooms[3][1].width = ROOM_WIDTH - 1;
rooms[3][1].offset_x = 0;
rooms[3][1].height = 4;
rooms[3][1].offset_y = 2;
rooms[3][1].kind = RoomType::BasicRoom;
let mst: GeneratorGraph = LevelGenerator::create_mst(&rooms);
LevelGenerator::create_connections(&mut rooms, &mst);
assert!(rooms[1][1].connection_down.is_none());
assert!(rooms[1][1].connection_right.is_some());
assert_eq!(
rooms[1][1].connection_right.unwrap().start_pos,
(18, 8),
"wrong start"
);
assert_eq!(
rooms[1][1].connection_right.unwrap().end_pos,
(27, 10),
"wrong end"
);
assert!(rooms[1][2].connection_down.is_none());
assert!(rooms[1][2].connection_right.is_none());
}
#[test]
fn test_create_connections_right_3() {
// test reduced width rooms (with NO overlap) for downwards connection
let mut rng = rand::thread_rng();
let mut rooms = [[Room::new(&mut rng); ROOMS_VERTICAL]; ROOMS_HORIZONTAL];
rooms[1][1].width = ROOM_WIDTH - 1;
rooms[1][1].offset_x = 0;
rooms[1][1].height = 2;
rooms[1][1].offset_y = 0;
rooms[1][1].kind = RoomType::BasicRoom;
rooms[3][1].width = ROOM_WIDTH - 1;
rooms[3][1].offset_x = 0;
rooms[3][1].height = 2;
rooms[3][1].offset_y = 4;
rooms[3][1].kind = RoomType::BasicRoom;
let mst: GeneratorGraph = LevelGenerator::create_mst(&rooms);
LevelGenerator::create_connections(&mut rooms, &mst);
assert!(rooms[1][1].connection_down.is_none());
assert!(rooms[1][1].connection_right.is_some());
assert_eq!(
rooms[1][1].connection_right.unwrap().start_pos,
(18, 7),
"wrong start"
);
assert_eq!(
rooms[1][1].connection_right.unwrap().end_pos,
(27, 11),
"wrong end"
);
assert!(rooms[1][3].connection_down.is_none());
assert!(rooms[1][3].connection_right.is_none());
}
#[test]
fn test_create_connections_right_4() {
// test reduced width rooms (with NO overlap) for downwards connection
let mut rng = rand::thread_rng();
let mut rooms = [[Room::new(&mut rng); ROOMS_VERTICAL]; ROOMS_HORIZONTAL];
rooms[1][1].width = 4;
rooms[1][1].offset_x = 3;
rooms[1][1].height = 2;
rooms[1][1].offset_y = 0;
rooms[1][1].kind = RoomType::BasicRoom;
rooms[3][1].width = 3;
rooms[3][1].offset_x = 3;
rooms[3][1].height = 2;
rooms[3][1].offset_y = 4;
rooms[3][1].kind = RoomType::BasicRoom;
let mst: GeneratorGraph = LevelGenerator::create_mst(&rooms);
LevelGenerator::create_connections(&mut rooms, &mst);
assert!(rooms[1][1].connection_down.is_none());
assert!(rooms[1][1].connection_right.is_some());
assert_eq!(
rooms[1][1].connection_right.unwrap().start_pos,
(17, 7),
"wrong start"
);
assert_eq!(
rooms[1][1].connection_right.unwrap().end_pos,
(30, 11),
"wrong end"
);
assert!(rooms[1][3].connection_down.is_none());
assert!(rooms[1][3].connection_right.is_none());
}
// /*
// println!(" 0 1 2 3 4 5 6 7");
// for r in 0..ROOMS_VERTICAL {
// print!("{} ", r);
// for c in 0..ROOMS_HORIZONTAL {
// match res[c][r].kind {
// RoomType::Start => print!("S "),
// RoomType::End => print!("E "),
// RoomType::StairUp => print!("< "),
// RoomType::StairDown => print!("> "),
// RoomType::BasicRoom => print!("_ "),
// RoomType::ArtifactRoom => print!("A "),
// RoomType::MonsterRoom => print!("M "),
// RoomType::EmptyRoom => print!(" "),
// };
// }
// println!();
// }
// println!();
// */

30
src/level_ladder.rs Normal file
View File

@ -0,0 +1,30 @@
pub struct LevelLadder {
curr: usize,
next: usize,
}
impl Iterator for LevelLadder {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
let current = self.curr;
self.curr = self.next;
self.next += current;
// Since there's no endpoint to a Fibonacci sequence, the `Iterator`
// will never return `None`, and `Some` is always returned.
Some(current * 30)
}
}
// Returns a Fibonacci sequence generator
pub fn get_level_ladder() -> LevelLadder {
LevelLadder { curr: 1, next: 2 }
}
#[test]
fn test_level_ladder() {
let mut iter = get_level_ladder();
assert_eq!(iter.next(), Some(30));
}

98
src/level_widget.rs Normal file
View File

@ -0,0 +1,98 @@
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::widgets::{StatefulWidget, Widget};
use crate::game::Game;
use crate::level::StructureElement;
use crate::position::HasPosition;
const FG_BROWN: Color = Color::Rgb(140, 34, 0);
const BACKGROUND: Color = Color::Black;
pub struct LevelWidget {}
impl LevelWidget {
fn set_cell(&self, buf: &mut Buffer, x: u16, y: u16, symbol: &str, fg: Color, bg: Color) {
buf[(x, y)].set_symbol(symbol).set_bg(bg).set_fg(fg);
}
fn set_bold_cell(&self, buf: &mut Buffer, x: u16, y: u16, symbol: &str, fg: Color, bg: Color) {
buf[(x, y)]
.set_symbol(symbol)
.set_bg(bg)
.set_fg(fg)
.set_style(Style::new().add_modifier(Modifier::BOLD));
}
}
impl StatefulWidget for LevelWidget {
type State = Game;
fn render(self, area: Rect, buf: &mut Buffer, state: &mut Self::State) {
let al: u16 = area.left();
let at: u16 = area.top();
{
let player = state.get_mutable_player();
let player_pos = player.get_immutable_position();
let player_level = player_pos.get_level();
// draw the level elements
for x in al..area.right() {
for y in at..area.bottom() {
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) {
(Some(structure_element), None, None) => {
match structure_element {
StructureElement::Start => {
self.set_cell(buf, x, y, "α", Color::White, BACKGROUND);
}
StructureElement::End => {
self.set_cell(buf, x, y, "Ω", Color::White, BACKGROUND);
}
StructureElement::Wall => {
// TODO add fancy walls with https://en.wikipedia.org/wiki/Box-drawing_characters
self.set_cell(buf, x, y, "#", FG_BROWN, FG_BROWN);
}
StructureElement::Floor => {
self.set_cell(buf, x, y, " ", FG_BROWN, BACKGROUND);
}
StructureElement::StairDown => {
self.set_cell(buf, x, y, ">", Color::White, BACKGROUND);
}
StructureElement::StairUp => {
self.set_cell(buf, x, y, "<", Color::White, BACKGROUND);
}
StructureElement::Unknown => {
self.set_cell(buf, x, y, "", Color::Gray, BACKGROUND);
}
}
}
(_, Some(m), _) => {
let (s, c) = m.get_representation();
self.set_cell(buf, x, y, s, c, BACKGROUND);
}
(_, _, Some(t)) => {
let (s, c) = t.get_representation();
self.set_bold_cell(buf, x, y, s, c, BACKGROUND);
}
(None, None, None) => {}
};
}
}
}
{
let player = state.get_mutable_player();
let player_pos = player.get_immutable_position();
let player_x = al + player_pos.get_x() as u16;
let player_y = at + player_pos.get_y() as u16;
self.set_cell(buf, player_x, player_y, "8", Color::LightRed, BACKGROUND);
}
}
}
impl Widget for LevelWidget {
fn render(self, _area: Rect, _buf: &mut Buffer) {}
}

View File

@ -1,16 +1,256 @@
use crate::game::Game; use std::io::stdout;
use crate::level::Level; use std::io::Result;
use std::time::Instant;
use constants::FRAME_LENGTH;
use constants::LEVELS;
use constants::LEVEL_HEIGHT;
use constants::LEVEL_WIDTH;
use constants::MIN_HEIGHT;
use constants::MIN_WIDTH;
use crossterm::{
event::{self, KeyCode, KeyEventKind},
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
ExecutableCommand,
};
use ratatui::prelude::*;
use ratatui::widgets::{Block, BorderType, Borders, Wrap};
use ratatui::{
prelude::{CrosstermBackend, Terminal},
widgets::Paragraph,
};
use whoami::realname;
use crate::game::{Game, GameState};
use crate::level_widget::LevelWidget;
use crate::player::Player; use crate::player::Player;
use crate::position::HasPosition;
mod artifacts;
mod constants;
mod game; mod game;
mod player;
mod level; mod level;
mod level_generator;
mod level_ladder;
mod level_widget;
mod monster;
mod player;
mod position; mod position;
mod room;
fn main() { //
let g = Game { fn main() -> Result<()> {
player: Player::new("Teddy Tester", 10), let mut game = Game::new(Player::new(realname().as_str(), 30));
levels: [Level::new();25]
stdout().execute(EnterAlternateScreen)?;
enable_raw_mode()?;
let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;
terminal.clear()?;
let start_time = Instant::now();
let mut ticks = 0;
loop {
terminal.draw(|frame| {
let mut area = frame.area();
frame.render_widget(
Block::default().style(Style::default().bg(Color::Green)),
area,
);
// don't draw stuff except an info box if the terminal is too small (less than 80x25)
// to prevent the read drawing code from crashing the game.
if area.width < MIN_WIDTH || area.height < MIN_HEIGHT {
let block = Block::default()
.title("Info")
.borders(Borders::ALL)
.border_style(Style::default().fg(Color::White))
.border_type(BorderType::Rounded)
.style(Style::default().bg(Color::Black));
let paragraph = Paragraph::new(format!(
"Terminal needs to be at leas {}x{}!",
MIN_WIDTH, MIN_HEIGHT
))
.block(block)
.wrap(Wrap { trim: true });
frame.render_widget(paragraph, area);
return;
}
if area.width > MIN_WIDTH {
area.x = (area.width - MIN_WIDTH) / 2;
area.width = MIN_WIDTH;
}
if area.height > MIN_HEIGHT {
area.y = (area.height - LEVEL_HEIGHT as u16) / 2;
area.height = LEVEL_HEIGHT as u16;
}
let map_area = Rect {
x: area.x,
y: area.y,
width: LEVEL_WIDTH as u16,
height: LEVEL_HEIGHT as u16,
}; };
println!("{}",g.player.get_name()); frame.render_stateful_widget(LevelWidget {}, map_area, &mut game);
let stats_area = Rect {
x: area.x + map_area.width,
y: area.y,
width: MIN_WIDTH - map_area.width,
height: map_area.height / 2 + 1,
};
let block = Block::default()
.title_top(
Line::from(format!(" {} ", game.get_player().get_name())).centered()
)
.borders(Borders::TOP)
.border_style(Style::default().fg(Color::White))
.border_type(BorderType::Rounded)
.style(Style::default().bg(Color::Blue));
frame.render_widget(
Paragraph::new(format!(
"Health: {} of {}\nExp: {}\nGold: {}\nLevel: {} of {}\nInventory used: {} of {}",
game.get_player().get_life(),
game.get_player().get_max_life(),
game.get_player().get_experience(),
game.get_player().get_gold(),
game.get_player().get_immutable_position().get_level() + 1,
LEVELS,
game.get_player().inventory_size().0,
game.get_player().inventory_size().1,
))
.block(block)
.wrap(Wrap { trim: true }),
stats_area,
);
let messages_area = Rect {
x: area.x + map_area.width,
y: area.y + map_area.height / 2 + 1,
width: MIN_WIDTH - map_area.width,
height: map_area.height / 2,
};
// Display the latest messages from the game to the user
let block = Block::default()
.title_top(
Line::from(" messages ").centered()
)
.borders(Borders::TOP)
.border_style(Style::default().fg(Color::White))
.border_type(BorderType::Rounded)
.style(Style::default().bg(Color::Blue));
let paragraph1 = if game.messages.is_empty() {
"".to_string()
} else {
format!("> {}", game.messages.join("\n> "))
};
frame.render_widget(
Paragraph::new(paragraph1)
.block(block)
.wrap(Wrap { trim: true }),
messages_area,
);
})?;
if event::poll(std::time::Duration::from_millis(FRAME_LENGTH))? {
if let event::Event::Key(key) = event::read()? {
if key.kind == KeyEventKind::Press {
match key.code {
KeyCode::Char('v') => {
game.messages.insert(
0,
format!("You are playing version '{}'.", env!("GIT_HASH"))
.to_string(),
);
}
KeyCode::Char('p') => {
let gained_health = game.get_mutable_player().consume_inventory();
if gained_health > 0 {
game.messages.insert(
0,
format!(
"used a potion from inventory and gained {} health.",
gained_health
)
.to_string(),
);
}
}
KeyCode::Char('q') => {
break;
}
KeyCode::Left | KeyCode::Down | KeyCode::Right | KeyCode::Up => {
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),
_ => (0, 0),
};
if !game.player_fights_monster() {
// player attacked monster but did not kill it
game.move_player(new_pos.0, new_pos.1);
}
game.player_collects_artifact();
}
_ => {}
}
}
}
}
game.update_level(ticks);
if game.get_game_state() != GameState::Running {
break;
}
ticks += 1;
}
let playtime = start_time.elapsed();
loop {
let _ = terminal.draw(|frame| {
let mut area = frame.area();
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_top(Line::from(" Game ended ").centered())
.title_bottom(Line::from("Press `q` to quit!"))
.borders(Borders::ALL)
.border_style(Style::default().fg(Color::White))
.border_type(BorderType::Rounded)
.style(Style::default().bg(Color::Black));
let mut text = match game.get_game_state() {
GameState::Running => {
"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()
}
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!("\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 });
frame.render_widget(paragraph, area);
});
if event::poll(std::time::Duration::from_millis(16))? {
if let event::Event::Key(key) = event::read()? {
if key.kind == KeyEventKind::Press && key.code == KeyCode::Char('q') {
break;
}
}
}
}
stdout().execute(LeaveAlternateScreen)?;
disable_raw_mode()?;
Ok(())
} }

131
src/monster.rs Normal file
View File

@ -0,0 +1,131 @@
use std::ops::RangeInclusive;
use crate::position::{HasPosition, Position};
use macros::CreateMonsters;
use rand::Rng;
use ratatui::prelude::Color;
pub trait Monster: HasPosition {
fn get_name(&self) -> &str;
fn is_dead(&self) -> bool;
fn get_representation(&self) -> (&str, Color);
fn decrease_life(&mut self, by: usize);
// fn get_immutable_position(&self) -> &Position;
fn get_experience_gain(&self) -> usize;
fn get_ticks_between_steps(&self) -> u128;
#[cfg(test)]
fn get_life(&self) -> usize;
fn damage(&self) -> usize;
}
#[derive(CreateMonsters, PartialEq, Eq, Hash, Clone, Copy)]
pub enum MonsterTypes {
Rat,
Orc,
Snake,
Skeleton,
Spider,
}
macro_rules! create_monster {
($t:ident $(, $k:ident : $v:expr)*$(,)?) => (
impl $t {
pub fn new_with_position(position: Position) -> Self {
Self {
position,
$($k: $v,)*
}
}
}
)
}
create_monster!(
Rat,
name:"rat".to_string(),
life: 2,
symbol: String::from("r"),
color: Color::White,
experience_gain: 5,
ticks_between_steps: 5,
damage_range: 1..=2,
);
create_monster!(
Spider,
name:"spider".to_string(),
life: 3,
symbol: String::from("s"),
color: Color::Yellow,
experience_gain: 7,
ticks_between_steps: 7,
damage_range: 2..=3,
);
create_monster!(
Orc,
name: "orc".to_string(),
life: 4,
symbol: String::from("O"),
color: Color::Gray,
experience_gain: 10,
ticks_between_steps: 10,
damage_range: 2..=3,
);
create_monster!(
Snake,
name: "snake".to_string(),
life: 3,
symbol: String::from("s"),
color: Color::White,
experience_gain: 10,
ticks_between_steps: 20,
damage_range: 1..=4,
);
create_monster!(
Skeleton,
name: "skeleton".to_string(),
life: 3,
symbol: String::from("S"),
color: Color::Gray,
experience_gain: 20,
ticks_between_steps: 10,
damage_range: 1..=5,
);
pub fn create_monster_by_type(monster_type: &MonsterTypes, position: Position) -> Box<dyn Monster> {
match monster_type {
MonsterTypes::Rat => Box::new(Rat::new_with_position(position)),
MonsterTypes::Orc => Box::new(Orc::new_with_position(position)),
MonsterTypes::Snake => Box::new(Snake::new_with_position(position)),
MonsterTypes::Skeleton => Box::new(Skeleton::new_with_position(position)),
MonsterTypes::Spider => Box::new(Spider::new_with_position(position)),
}
}
#[test]
fn monsters_can_move() {
let mut m = Rat::new_with_position(Position::new(0, 0, 0));
assert_eq!(m.get_position(), &Position::new(0, 0, 0));
m.get_position().change(1, 2);
assert_eq!(m.get_position(), &Position::new(0, 1, 2));
m.get_position().change(2, 1);
assert_eq!(m.get_position(), &Position::new(0, 3, 3));
m.get_position().set(1, 2, 3);
m.get_position().change(2, 1);
assert_eq!(m.get_position(), &Position::new(1, 4, 4));
}
#[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.is_dead(), false);
m.decrease_life(1);
assert_eq!(m.get_life(), 1);
m.decrease_life(2);
assert_eq!(m.get_life(), 0);
assert_eq!(m.is_dead(), true);
}

View File

@ -1,28 +1,129 @@
use rand::Rng;
use std::cmp::{max, min}; use std::cmp::{max, min};
use crate::position::Position;
use crate::artifacts::Potion;
use crate::level_ladder::get_level_ladder;
use crate::position::{HasPosition, Position};
pub struct Player { pub struct Player {
name: String, name: String,
position: Position, position: Position,
life: i16, life: i16,
max_life: i16, max_life: i16,
gold: usize,
experience: usize,
inventory: Vec<Potion>,
inventory_slots: usize,
level: usize,
} }
impl Player { impl Player {
pub fn new(name: &str, max_life: i16) -> Player { pub fn new(name: &str, max_life: i16) -> Player {
Player { Player {
name: name.to_string(), name: name.to_string(),
position: Position::new(0, 1, 1), position: Position::new(0, 0, 0),
life: max_life, life: max_life,
max_life, max_life,
gold: 0,
experience: 0,
inventory: vec![],
inventory_slots: 2,
level: 1,
} }
} }
pub fn get_name(&self) -> String { pub fn get_name(&self) -> String {
return self.name.clone(); self.name.clone()
} }
pub fn change_life(&mut self, by: i16) { pub fn change_life(&mut self, by: i16) {
self.life = max(0, min(self.max_life, self.life + by)); self.life = max(0, min(self.max_life, self.life + by));
} }
pub fn get_life(&self) -> i16 {
self.life
}
/// 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 get_max_life(&self) -> i16 {
self.max_life
}
/// add the given amount to the players gold stash
pub fn retrieve_gold(&mut self, amount: usize) {
self.gold += amount
}
/// return the size of the players gold stash
pub fn get_gold(&self) -> usize {
self.gold
}
pub fn gain_experience(&mut self, amount: usize) -> bool {
let mut result = false;
for (i, level_step) in get_level_ladder().enumerate() {
if self.experience <= level_step && self.experience + amount > level_step {
self.level += 1;
self.max_life += 5;
self.life = self.max_life;
result = true;
break;
}
if i > self.level {
break;
}
}
self.experience += amount;
result
}
pub fn get_experience_level(&self) -> usize {
self.level
}
pub fn get_experience(&self) -> usize {
self.experience
}
pub fn damage(&self) -> usize {
rand::thread_rng().gen_range(1..4)
}
pub fn add_to_inventory(&mut self, potion: &Potion) -> bool {
if self.inventory.len() < self.inventory_slots {
self.inventory.push(*potion);
true
} else {
false
}
}
pub fn inventory_size(&self) -> (usize, usize) {
(self.inventory.len(), self.inventory_slots)
}
pub fn consume_inventory(&mut self) -> usize {
if self.is_healthy() {
return 0;
}
if let Some(potion) = self.inventory.pop() {
self.change_life(potion.get_health() as i16);
return potion.get_health();
}
0
}
}
impl HasPosition for Player {
fn get_position(&mut self) -> &mut Position {
&mut self.position
}
fn get_immutable_position(&self) -> &Position {
&self.position
}
} }
#[test] #[test]
@ -32,10 +133,25 @@ fn test_get_name() {
position: Position::new(0, 1, 1), position: Position::new(0, 1, 1),
life: 5, life: 5,
max_life: 10, max_life: 10,
gold: 0,
experience: 0,
inventory: vec![],
inventory_slots: 1,
level: 0,
}; };
assert_eq!(p.get_name(), "Teddy Tester"); assert_eq!(p.get_name(), "Teddy Tester");
} }
#[test]
fn test_can_receive_gold() {
let mut p = Player::new("Teddy Tester", 10);
assert_eq!(p.get_gold(), 0);
p.retrieve_gold(13);
p.retrieve_gold(10);
assert_eq!(p.get_gold(), 23);
}
#[test] #[test]
fn test_change_life() { fn test_change_life() {
let mut p = Player { let mut p = Player {
@ -43,12 +159,47 @@ fn test_change_life() {
position: Position::new(0, 1, 1), position: Position::new(0, 1, 1),
life: 5, life: 5,
max_life: 10, max_life: 10,
gold: 0,
experience: 0,
inventory: vec![],
inventory_slots: 1,
level: 0,
}; };
assert_eq!(p.life, 5); assert_eq!(p.get_life(), 5);
p.change_life(-2); p.change_life(-2);
assert_eq!(p.life, 3); assert_eq!(p.get_life(), 3);
p.change_life(10); p.change_life(10);
assert_eq!(p.life, 10); assert_eq!(p.get_life(), 10);
p.change_life(-12); p.change_life(-12);
assert_eq!(p.life, 0); assert_eq!(p.get_life(), 0);
}
#[test]
fn player_can_move() {
let mut p = Player::new("Teddy Tester", 10);
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));
p.get_position().change(2, 1);
assert_eq!(p.get_position(), &Position::new(0, 3, 3));
p.get_position().set(1, 2, 3);
p.get_position().change(2, 1);
assert_eq!(p.get_position(), &Position::new(1, 4, 4));
assert_eq!(p.get_immutable_position(), &Position::new(1, 4, 4));
}
#[test]
fn test_max_life() {
let p = Player {
name: "Teddy Tester".to_string(),
position: Position::new(0, 1, 1),
life: 5,
max_life: 10,
gold: 0,
experience: 0,
inventory: vec![],
inventory_slots: 1,
level: 0,
};
assert_eq!(p.get_max_life(), 10);
} }

View File

@ -1,15 +1,74 @@
use std::cmp::max;
/// describes an character (PC or NPC) in the dungeon that has a position.
pub trait HasPosition {
/// returns a mutable position
fn get_position(&mut self) -> &mut Position;
/// returns an immutable position
fn get_immutable_position(&self) -> &Position;
}
#[derive(PartialEq, Debug, Clone, Copy)]
pub struct Position { pub struct Position {
level: u8, level: usize,
x: u8, x: usize,
y: u8, y: usize,
} }
impl Position { impl Position {
pub fn new(level: u8, x: u8, y: u8) -> Self { pub fn new(level: usize, x: usize, y: usize) -> Self {
Self { Self { level, x, y }
level,
x,
y,
} }
pub fn change(&mut self, dx: i16, dy: i16) -> (usize, usize) {
self.x = max((self.x as i16) + dx, 0) as usize;
self.y = max((self.y as i16) + dy, 0) as usize;
(self.x, self.y)
}
pub fn set(&mut self, level: usize, x: usize, y: usize) {
self.level = level;
self.x = x;
self.y = y;
}
pub fn get_level(&self) -> usize {
self.level
}
pub fn get_x(&self) -> usize {
self.x
}
pub fn get_y(&self) -> usize {
self.y
} }
} }
#[test]
fn test_position_change() {
let mut p = Position::new(0, 10, 10);
let res = p.change(-1, 1);
assert_eq!(res, (9, 11));
assert_eq!(p.get_x(), 9);
assert_eq!(p.get_y(), 11);
let res = p.change(-9, 1);
assert_eq!(res, (0, 12));
assert_eq!(p.get_x(), 0);
assert_eq!(p.get_y(), 12);
let res = p.change(-1, -13);
assert_eq!(res, (0, 0));
assert_eq!(p.get_x(), 0);
assert_eq!(p.get_y(), 0);
}
#[test]
fn test_position_set() {
let mut p = Position::new(0, 10, 10);
p.set(1, 2, 3);
assert_eq!(p.get_level(), 1);
assert_eq!(p.get_x(), 2);
assert_eq!(p.get_y(), 3);
}

280
src/room.rs Normal file
View File

@ -0,0 +1,280 @@
use std::{
cmp::{max, min},
ops::RangeInclusive,
};
use crate::{
constants::{
LEVEL_HEIGHT, LEVEL_WIDTH, ROOM_HEIGHT, ROOM_MIN_HEIGHT, ROOM_MIN_WIDTH, ROOM_WIDTH,
},
level::StructureElement,
};
use rand::rngs::ThreadRng;
use rand::Rng;
#[derive(PartialEq, Copy, Clone, Eq, Hash, Debug)]
pub enum RoomType {
Start,
End,
StairUp,
StairDown,
BasicRoom,
ArtifactRoom,
MonsterRoom,
EmptyRoom,
}
#[derive(Copy, Clone, Debug)]
pub struct Connection {
pub start_pos: (usize, usize),
pub end_pos: (usize, usize),
}
impl Connection {
pub fn render(
&self,
rng: &mut ThreadRng,
tgt: &mut [[StructureElement; LEVEL_HEIGHT]; LEVEL_WIDTH],
) {
fn calc_range(a: usize, b: usize) -> RangeInclusive<usize> {
if a > b {
b..=a
} else {
a..=b
}
}
// the tuples are (col, row)
let abs_d_col =
max(self.start_pos.0, self.end_pos.0) - min(self.start_pos.0, self.end_pos.0);
let abs_d_row =
max(self.start_pos.1, self.end_pos.1) - min(self.start_pos.1, self.end_pos.1);
if abs_d_col == 0 {
for row in calc_range(self.end_pos.1, self.start_pos.1) {
tgt[self.end_pos.0][row] = StructureElement::Floor;
}
} else if abs_d_row == 0 {
for col in calc_range(self.end_pos.0, self.start_pos.0) {
tgt[col][self.end_pos.1] = StructureElement::Floor;
}
} else {
let d_row = self.end_pos.1 as i32 - self.start_pos.1 as i32;
if d_row > 0 {
// more up/down
let d_row = self.end_pos.1 - self.start_pos.1;
let vert_offset = if d_row > 3 {
rng.gen_range(1..=d_row - 1)
} else {
d_row / 2
};
for r in self.start_pos.1..=(self.start_pos.1 + vert_offset) {
tgt[self.start_pos.0][r] = StructureElement::Floor;
}
for c in calc_range(self.end_pos.0, self.start_pos.0) {
tgt[c][self.start_pos.1 + vert_offset] = StructureElement::Floor;
}
for r in (self.start_pos.1 + vert_offset)..=self.end_pos.1 {
tgt[self.end_pos.0][r] = StructureElement::Floor;
}
} else {
// more left/right
let d_col = self.end_pos.0 - self.start_pos.0;
let horizont_offset = if d_col > 3 {
rng.gen_range(1..=d_col - 1)
} else {
d_col / 2
};
for tgt_col in tgt
.iter_mut()
.skip(self.start_pos.0)
.take(horizont_offset + 1)
{
tgt_col[self.start_pos.1] = StructureElement::Floor;
}
for r in calc_range(self.end_pos.1, self.start_pos.1) {
tgt[self.start_pos.0 + horizont_offset][r] = StructureElement::Floor;
}
for tgt_col in tgt
.iter_mut()
.take(self.end_pos.0 + 1)
.skip(self.start_pos.0 + horizont_offset)
{
tgt_col[self.end_pos.1] = StructureElement::Floor;
}
}
}
}
}
#[derive(Copy, Clone, Debug)]
pub struct Room {
pub kind: RoomType,
pub offset_x: usize,
pub offset_y: usize,
pub width: usize,
pub height: usize,
pub special: (usize, usize),
pub connection_down: Option<Connection>,
pub connection_right: Option<Connection>,
}
impl Room {
pub fn new(rng: &mut ThreadRng) -> Self {
let width = rng.gen_range(ROOM_MIN_WIDTH..ROOM_WIDTH);
let height = rng.gen_range(ROOM_MIN_HEIGHT..ROOM_HEIGHT);
let offset_x = rng.gen_range(0..(ROOM_WIDTH - width));
let offset_y = rng.gen_range(0..(ROOM_HEIGHT - height));
let sx = offset_x + rng.gen_range(1..width - 1);
let sy = offset_y + rng.gen_range(1..height - 1);
Self {
kind: RoomType::EmptyRoom,
offset_x,
offset_y,
width,
height,
special: (sx, sy),
connection_down: None,
connection_right: None,
}
}
// pub fn get_x_range(&self) -> Range<usize> {
// self.offset_x..self.offset_x + self.width
// }
// pub fn get_y_range(&self) -> Range<usize> {
// self.offset_y..self.offset_y + self.height
// }
pub fn render(
&self,
tgt: &mut [[StructureElement; LEVEL_HEIGHT]; LEVEL_WIDTH],
col: usize,
row: usize,
) -> (usize, usize) {
let top = 1 + row * ROOM_HEIGHT;
let left = 1 + col * ROOM_WIDTH;
for col in tgt.iter_mut().skip(left).take(ROOM_WIDTH) {
//left..left + ROOM_WIDTH {
for row_element in col.iter_mut().skip(top).take(ROOM_HEIGHT) {
// top..top + ROOM_HEIGHT {
*row_element = StructureElement::Wall;
}
}
if self.kind == RoomType::EmptyRoom {
return (0, 0);
}
// render floor elements
for x in 0..self.width {
for y in 0..self.height {
tgt[left + self.offset_x + x][top + self.offset_y + y] = StructureElement::Floor;
}
}
match self.kind {
RoomType::Start => {
tgt[left + self.special.0][top + self.special.1] = StructureElement::Start;
}
RoomType::End => {
tgt[left + self.special.0][top + self.special.1] = StructureElement::End;
}
RoomType::StairUp => {
tgt[left + self.special.0][top + self.special.1] = StructureElement::StairUp;
}
RoomType::StairDown => {
tgt[left + self.special.0][top + self.special.1] = StructureElement::StairDown;
}
_ => {}
};
(left + self.special.0, top + self.special.1)
}
}
#[test]
fn test_room_creation() {
let mut rng = rand::thread_rng();
let room = Room::new(&mut rng);
assert_eq!(room.kind, RoomType::EmptyRoom);
for _ in 0..1000 {
let room = Room::new(&mut rng);
assert!((3..=ROOM_WIDTH).contains(&room.width));
}
}
#[cfg(test)]
fn all_wall(
tgt: &mut [[StructureElement; LEVEL_HEIGHT]; LEVEL_WIDTH],
col: usize,
row: usize,
) -> bool {
let top = 1 + row * ROOM_HEIGHT;
let left = 1 + col * ROOM_WIDTH;
for x in left..left + ROOM_WIDTH {
for y in top..top + ROOM_HEIGHT {
if tgt[x][y] != StructureElement::Wall {
return false;
}
}
}
true
}
#[cfg(test)]
fn has_structure_element(
tgt: &mut [[StructureElement; LEVEL_HEIGHT]; LEVEL_WIDTH],
col: usize,
row: usize,
element: StructureElement,
) -> bool {
let top = 1 + row * ROOM_HEIGHT;
let left = 1 + col * ROOM_WIDTH;
for x in left..left + ROOM_WIDTH {
for y in top..top + ROOM_HEIGHT {
if tgt[x][y] == element {
return true;
}
}
}
false
}
#[test]
fn test_room_render_empty() {
let mut rng = rand::thread_rng();
let room = Room::new(&mut rng);
assert_eq!(room.kind, RoomType::EmptyRoom);
let mut structure = [[StructureElement::Floor; LEVEL_HEIGHT]; LEVEL_WIDTH];
room.render(&mut structure, 0, 0);
assert!(all_wall(&mut structure, 0, 0));
}
#[test]
fn test_room_render_basic() {
let mut rng = rand::thread_rng();
let mut room = Room::new(&mut rng);
room.kind = RoomType::BasicRoom;
let mut structure = [[StructureElement::Floor; LEVEL_HEIGHT]; LEVEL_WIDTH];
room.render(&mut structure, 1, 3);
assert!(!all_wall(&mut structure, 1, 3));
}
#[test]
fn test_room_render_start() {
let mut rng = rand::thread_rng();
let mut room = Room::new(&mut rng);
room.kind = RoomType::Start;
let mut structure = [[StructureElement::Floor; LEVEL_HEIGHT]; LEVEL_WIDTH];
room.render(&mut structure, 1, 3);
assert!(!all_wall(&mut structure, 1, 3));
assert!(has_structure_element(
&mut structure,
1,
3,
StructureElement::Start
));
}