Compare commits

...

59 commits

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

View file

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

4
.gitignore vendored
View file

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

860
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

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

674
LICENSE Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

38
README.md Normal file
View file

@ -0,0 +1,38 @@
# Rust Kroz
[![Build Status](https://drone.valter.cat/api/badges/valter/kroz-rs/status.svg)](https://drone.valter.cat/valter/kroz-rs)
This is an **UNOFFICIAL** attempt to rewrite (in Rust) the late 80s/early 90s text-mode action game series Kroz by Apogee Software founder Scott Miller.
The goal is to closely mimic the look and behavior of the original game, but not necessarily recreate it exactly. I plan on making the following changes to make it generally more accessible:
- Remove all the references to ordering/registration
- [The original game is free and open source now](http://legacy.3drealms.com/news/2009/03/several_old_games_released_as_freeware.html)
- Combine every episode into one executable
- Enable returning to the main menu from the game
- Load custom levels/campaigns from external files
- A built-in level editor would be nice
- Load custom tile graphics from an external file
- Settings for things like sound volume and controls
- Game speed will be fixed, possibly configurable
- The original game's speed varied with CPU speed
- Improve control response
- Support Windows, Linux, macOS, and the web
## Building
[Install Rust](https://rustup.rs/)
### Desktop
Run `cargo build` or `cargo run`
### Web
Run `npm run build` or `npm start`
## License
The original "Kroz" copyright 1987 - 2022 Apogee Entertainment Inc. All trademarks and copyrights reserved.
This project has no affiliation with Apogee Entertainment Inc. and the code within is licensed under the [GNU General Public License Version 3](https://www.gnu.org/licenses/gpl-3.0.en.html).

View file

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

1
js/index.js Normal file
View file

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

3701
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

18
package.json Normal file
View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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

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

View file

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

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

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

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

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

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

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

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

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

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

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

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

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

56
src/levels.rs Normal file
View file

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

34
src/lib.rs Normal file
View file

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

View file

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

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

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

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

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

View file

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

View file

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

View file

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

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

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

View file

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

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

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

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

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

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

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

435
src/tile_data.rs Normal file
View file

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

BIN
static/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

36
static/index.html Normal file
View file

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

36
webpack.config.js Normal file
View file

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