Compare commits

...

34 Commits

Author SHA1 Message Date
Martin Prokoph
c017d4c129 docs: update README with test cases 2025-09-13 22:41:12 +02:00
Martin Prokoph
b17e88f96d clean: improve code structure 2025-09-13 17:18:06 +02:00
Martin Prokoph
f881427a67 feat: save highscores per difficulty 2025-09-09 15:03:24 +02:00
Martin Prokoph
db537f84ae feat: less drastic difficulty scaling 2025-09-09 10:27:56 +02:00
Martin Prokoph
5490ff8b5d docs: update README 2025-09-09 10:25:23 +02:00
Martin Prokoph
f58cd493bb clean: housekeeping 2025-09-09 10:20:10 +02:00
Martin Prokoph
7cbe2466d8 fix: Windows support
eww...
2025-09-08 18:27:22 +02:00
Martin Prokoph
223c3356b9 feat: final game space sizing
Also fixes logo after changing ui scale
2025-09-06 22:20:47 +02:00
Martin Prokoph
5077f1c2ad fix: normalize music volume 2025-09-06 22:04:54 +02:00
Martin Prokoph
f05d0a9f45 fix(NightJson): correctly save empty maps 2025-09-06 21:38:48 +02:00
Martin Prokoph
918748b373 feat: support running the game from jar file 2025-09-06 21:27:15 +02:00
Martin Prokoph
f6a94e6cd8 clean code: extract inner classes 2025-09-03 14:17:47 +02:00
Martin Prokoph
6d03702ada docs: add README and LICENSE (GPLv3) 2025-09-03 00:09:29 +02:00
Martin Prokoph
67a12899c6 docs: add javadocs for nearly everything 2025-09-02 23:48:49 +02:00
Martin Prokoph
504018b9f8 NightJson: expand maps 2025-08-02 23:30:59 +02:00
Martin Prokoph
fcf7f2a4f1 NightJson: remove empty line before comment 2025-08-02 23:06:02 +02:00
Martin Prokoph
f3c211f0a6 clean(NightJson): improve code quality 2025-08-02 17:07:55 +02:00
Martin Prokoph
f7d0d21370 feat: add comments to settings file 2025-08-02 16:43:08 +02:00
Martin Prokoph
7fda6fdfe5 feat(NightJson): support minified JSON files 2025-08-02 16:42:40 +02:00
Martin Prokoph
e4c7896a15 feat(NightJson): add arbitrary key-val pairs via map 2025-08-02 11:38:03 +02:00
Martin Prokoph
dfba8b397e feat: add translation support 2025-08-02 11:15:53 +02:00
Martin Prokoph
ec1841a592 ui: improve highscore list style 2025-08-01 20:37:32 +02:00
Martin Prokoph
d10313ea76 feat: highscore dialog and list 2025-08-01 20:24:14 +02:00
Martin Prokoph
93c0ee5f95 feat: save highscores 2025-08-01 19:07:20 +02:00
Martin Prokoph
8037f9a323 feat(NightJson): add support for maps! 2025-08-01 19:06:44 +02:00
Martin Prokoph
6cc7b95852 feat: scale speed based on level 2025-08-01 17:59:48 +02:00
Martin Prokoph
a228e9ab1a feat: support and target Java 11 2025-08-01 17:02:46 +02:00
Martin Prokoph
4d175761a5 clean: improve code structure 2025-08-01 16:51:14 +02:00
Martin Prokoph
7ef6e246ff feat: preview of next shape 2025-07-09 13:00:48 +02:00
Martin Prokoph
7671bdec04 feat: add elapsed time, fix bugs 2025-06-29 18:24:02 +02:00
Martin Prokoph
39c290e22f feat: add line completed sound 2025-06-29 15:06:22 +02:00
Martin Prokoph
f226cb40e2 feat: add line completed sound 2025-06-29 15:06:01 +02:00
Martin Prokoph
0a2294cd3d ui(settings): add volume sliders 2025-06-29 14:30:09 +02:00
Martin Prokoph
b5f65bd2bb feat: add collision handling to rotation 2025-06-29 14:29:38 +02:00
45 changed files with 1992 additions and 377 deletions

2
.idea/misc.xml generated
View File

@@ -4,7 +4,7 @@
<component name="FrameworkDetectionExcludesConfiguration">
<file type="web" url="file://$PROJECT_DIR$" />
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="11" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

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>.

47
README.md Normal file
View File

@@ -0,0 +1,47 @@
# TetrisClone in Java 11 & Swing
### von Martin Prokoph
Erstellt für das Modul "Anwendungsorientierte Programmierung" im Studiengang Medieninformatik an der HTWK Leipzig.
Dieser Code wurde vollständig von mir und ohne die Verwendung von LLMs geschrieben.
An einigen Stellen wurde auf Wissen von StackOverflow und Baeldung zugegriffen dies ist immer in den JavaDocs gekennzeichnet.
Die Commit-Historie ist [auf meinem Gitea](https://git.midnightdust.eu/Motschen/TetrisClone/commits/branch/main) einsehbar.
Gradle ist als Build-Tool eingerichtet, um elegant Jar-Dateien zu bauen, dabei aber völlig optional.
Können Sie meinen Highscore schlagen?
![Screenshot des Tetris-Spiels](assets/ingame.png)
## Rechtliche Hinweise
»Tetris« ist eine eingetragene Marke von The Tetris Company, Inc.
Die Verwendung des Namens »Tetris« und des Spielkonzepts erfolgen lediglich zu Bildungszwecken.
# Testbeispiele
## Bewegung
Spiel starten
1. Nach links verschieben mit `A` oder `←`
2. Nach rechts verschieben mit `D` oder `→`
3. Schneller nach unten mit `S` oder `↓`
4. Direkt nach unten mit `Leertaste`
5. Rotieren mit `W` oder `↑`
Bei jeder Bewegung sollte vor dem Umsetzen geprüft werden, ob die neue Position valide (Nicht überschneidend und nicht außerhalb des Spielraums) ist.
## Logik
Sobald eine Reihe vervollständigt wird, sollte sie verschwinden.
Wenn die Teile über den oberen Rand ragen, soll das Spiel beendet werden.
Im Vorschaufenster sollte immer das nächste Tetrominio angezeigt werden.
![Screenshot, der zeigt, welche Zeilen verschwinden sollen](assets/line_completion.png)
## Highscores
Sobald das Spiel beendet wird und der Score den aktuell höchsten Score überschreitet, sollte eine Aufforderung zum Eingeben des Namens erscheinen.
Nach dem Bestätigen erscheint der Name in der Highscore-Liste und wird über Spielsitzungen hinweg gespeichert.
![Screenshot des Highscore-Dialogs](assets/highscore_dialog.png)
## Benutzeroberfläche
Die Darstellung der Benutzeroberfläche kann in den Einstellungen angepasst werden.
Dabei lässt sich die Sprache und die GUI-Skalierung auswählen.
Ansonsten sind auch noch Einstellungen zur Lautstärke und Schwierigkeit vorhanden.
## Sounds und Musik
Sofern die Lautstärke angemessen eingestellt und ein Lautsprecher angeschlossen ist, sollten beim Absetzen der Tetrominos, sowie beim Vervollständigen einer/mehrerer Reihen Töne zu hören sein.
Auch Musik sollte abgespielt werden, sobald das Spiel gestartet wird.
Töne und Musik wurden im Zrythm-DAW erzeugt.

BIN
assets/highscore_dialog.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

BIN
assets/ingame.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

BIN
assets/line_completion.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

View File

@@ -14,6 +14,11 @@ dependencies {
testImplementation("org.junit.jupiter:junit-jupiter")
}
tasks.jar {
manifest.attributes["Main-Class"] = "eu.midnightdust.yaytris.Tetris"
}
tasks.test {
useJUnitPlatform()
}

View File

@@ -0,0 +1,50 @@
package eu.midnightdust.yaytris;
import eu.midnightdust.yaytris.util.Difficulty;
import eu.midnightdust.yaytris.util.json.Comment;
import eu.midnightdust.yaytris.util.json.NightJson;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("unused") // Comments are unused in code, but are added to the JSON file for readability
public class HighScores {
private static final NightJson json = new NightJson(HighScores.class, "tetris_scores.json5");
public static Comment c1 = new Comment("Highscores for each difficulty");
public static Map<String, Integer> Noob = new HashMap<>();
public static Map<String, Integer> Easy = new HashMap<>();
public static Map<String, Integer> Normal = new HashMap<>();
public static Map<String, Integer> Hard = new HashMap<>();
public static Map<String, Integer> Extreme = new HashMap<>();
public static Map<String, Integer> WTF = new HashMap<>();
/**
* Saves a new high score for the specified player
*
* @param playerName the player's name, duh
* @param score the score to save
*/
public static void addScore(String playerName, int score) {
diffToMap(Settings.difficulty).put(playerName, score);
write();
}
public static Map<String, Integer> diffToMap(Difficulty difficulty) {
switch (difficulty) {
case EASY: return Easy;
case NORMAL: return Normal;
case HARD: return Hard;
case EXTREME: return Extreme;
case WTF: return WTF;
default: return Noob;
}
}
public static void load() {
json.readJson();
}
public static void write() {
json.writeJson();
}
}

View File

@@ -0,0 +1,22 @@
package eu.midnightdust.yaytris;
import javax.swing.UIManager;
public class Main {
/**
* The application's entry point.
* Initializes the UI library to match the system style.
* Also loads saved settings, translations, and highscores from JSON.
*
* @param args command line arguments will be ignored
*/
public static void main(String[] args) {
try {
System.setProperty("java.awt.headless", "false");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception | Error e) { System.out.printf("%s: %s\n", "Error setting system look and feel", e); }
Tetris.init();
}
}

View File

@@ -1,19 +1,28 @@
package eu.midnightdust.yaytris;
import eu.midnightdust.yaytris.util.Difficulty;
import eu.midnightdust.yaytris.util.NightJson;
import eu.midnightdust.yaytris.util.Language;
import eu.midnightdust.yaytris.util.json.Comment;
import eu.midnightdust.yaytris.util.json.NightJson;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
@SuppressWarnings("unused") // Comments are unused in code, but are added to the JSON file for readability
public class Settings {
private static final NightJson json = new NightJson(Settings.class, "tetris_settings.json5");
public static Comment c1 = new Comment("Volume of theme music (0-100)");
public static int musicVolume = 100;
public static Comment c2 = new Comment("Volume of sound effects (0-100)");
public static int soundVolume = 100;
public static Comment c3 = new Comment("Amount the user interface should be scaled");
public static float guiScale = 3.f;
public static Comment c4 = new Comment("Whether speed should scale with level (true/false)");
public static boolean shouldScaleSpeed = true;
public static Comment c5 = new Comment("One of %s", Arrays.toString(Difficulty.values()));
public static Difficulty difficulty = Difficulty.NORMAL;
//public static Map<String, Integer> highScores = new HashMap<>();
public static Comment c6 = new Comment("One of %s", Arrays.toString(Language.values()));
public static Language language = Language.ENGLISH;
public static void load() {
json.readJson();

View File

@@ -1,11 +1,13 @@
package eu.midnightdust.yaytris;
import eu.midnightdust.yaytris.game.Space;
import eu.midnightdust.yaytris.game.Tetromino;
import eu.midnightdust.yaytris.ui.ScoreMenu;
import eu.midnightdust.yaytris.ui.TetrisUI;
import eu.midnightdust.yaytris.util.SoundUtil;
import eu.midnightdust.yaytris.util.GravityTimerTask;
import eu.midnightdust.yaytris.util.sound.SoundUtil;
import javax.swing.*;
import java.time.LocalTime;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
@@ -16,26 +18,40 @@ public class Tetris {
private static Timer timer;
private static TetrisUI ui;
private static TimerTask gravityTask;
private static LocalTime startTime;
public static void main(String[] args) {
try {
System.setProperty("java.awt.headless", "false");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception | Error e) { System.out.printf("%s: %s\n", "Error setting system look and feel", e); }
public static void init() {
Settings.load();
timer = new Timer("Tetris falling pieces");
space = new Space();
ui = new TetrisUI();
}
public static TetrisUI getUi() {
return ui;
Translation.load(Settings.language.locale);
HighScores.load();
Tetris.timer = new Timer("Tetris falling pieces");
Tetris.space = new Space();
Tetris.ui = new TetrisUI();
}
/**
* Get the active game space
*
* @see Space
*/
public static Space getSpace() {
return space;
}
/**
* Get the ui instance
*
* @see TetrisUI
*/
public static TetrisUI getUi() {
return ui;
}
/**
* Resets the game space, preparing it for a new game.
*
* @see Space
*/
public static void resetSpace() {
SoundUtil.stopMusic("/music/theme.wav");
if (gravityTask != null) gravityTask.cancel();
@@ -43,30 +59,73 @@ public class Tetris {
space = new Space();
}
/**
* Starts a new game of Tetris :D
* This involves starting our gravity task, playing music and spawning the first {@link Tetromino}
*
* @see Space#spawnTetromino()
*/
public static void startGame() {
SoundUtil.playMusic("/music/theme.wav", true);
space.spawnTetromino();
gravityTask = new TimerTask() {
@Override
public void run() {
if (space.getCurrentTetromino() != null) {
space.getCurrentTetromino().fall(1);
ui.getGamePanel().repaint();
}
}
};
startTime = LocalTime.now();
gravityTask = new GravityTimerTask();
timer.scheduleAtFixedRate(gravityTask, 1, Settings.difficulty.getTimerPeriod());
}
/**
* Stops the current game.
* Disables falling, fades out music and handles saving of high scores.
*
* @see ScoreMenu
* @see HighScores
*/
public static void stopGame() {
SoundUtil.stopMusic("/music/theme.wav");
if (gravityTask != null) gravityTask.cancel();
timer.purge();
if (ui.getMenuPanel() instanceof ScoreMenu) ((ScoreMenu) ui.getMenuPanel()).gameOver();
ui.transferFocus();
if (HighScores.diffToMap(Settings.difficulty).values().stream().noneMatch(hs -> hs > space.getScore()))
ui.showHighscoreDialog(space.getScore());
}
/**
* Updates the displayed score
*
* @param score the new score
* @see ScoreMenu
*/
public static void updateScore(int score) {
if (ui.getMenuPanel() instanceof ScoreMenu) ((ScoreMenu) ui.getMenuPanel()).updateScore(score);
updateLevel(score);
}
}
/**
* Updates the elapsed time
*
* @see ScoreMenu
*/
public static void updateTime() {
if (ui.getMenuPanel() instanceof ScoreMenu) ((ScoreMenu) ui.getMenuPanel()).updateTime(startTime);
}
/**
* Updates the displayed level
*
* @param score the new score, from which the level will be calculated
* @see ScoreMenu
*/
public static void updateLevel(int score) {
int newLevel = Math.max(0, (int) (score / 1400f));
if (newLevel != space.level) {
if (gravityTask != null && Settings.shouldScaleSpeed) {
gravityTask.cancel();
gravityTask = new GravityTimerTask();
timer.scheduleAtFixedRate(gravityTask, 0, Math.max(10, Settings.difficulty.getTimerPeriod() - (Settings.difficulty.getTimerPeriod() / 16) * newLevel));
}
space.level = newLevel;
if (ui.getMenuPanel() instanceof ScoreMenu) ((ScoreMenu) ui.getMenuPanel()).updateLevel(newLevel);
}
}
}

View File

@@ -0,0 +1,39 @@
package eu.midnightdust.yaytris;
import eu.midnightdust.yaytris.util.json.NightJson;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class Translation {
public static Map<String, String> jsonMap = new HashMap<>();
/**
* Loads translation strings from the specified language via NightJSON.
*
* @param locale the language code (i.e. de_de, en_us)
* @see NightJson
*/
public static void load(String locale) {
String jsonString; // This workaround is needed to support reading translations from json files embedded in the .jar file
try (InputStream stream = Translation.class.getResourceAsStream(String.format("/translation/%s.json5", locale))) {
jsonString = stream != null ? new String(stream.readAllBytes()) : "";
} catch (IOException e) {
throw new RuntimeException(e);
}
NightJson json = new NightJson(Translation.class, "translation");
json.readJsonFromString(jsonString);
}
/**
* Translates the given key to the active language.
*
* @param key translation key
* @return the resolved translation in the current locale, if present. Otherwise, the key is returned.
*/
public static String t(String key, Object... args) {
return String.format(jsonMap.getOrDefault(key, key), args);
}
}

View File

@@ -1,6 +1,7 @@
package eu.midnightdust.yaytris.game;
import eu.midnightdust.yaytris.Tetris;
import eu.midnightdust.yaytris.util.SoundEffect;
import java.awt.Color;
import java.util.*;
@@ -12,26 +13,46 @@ public class Space {
private TetrominoShape nextShape;
private Tetromino currentTetromino;
private int score;
public int level;
/**
* Space saves the current state of the game map
*/
public Space() {
gameMap = new Color[14][8];
nextShape = getNextShape();
gameMap = new Color[19][10];
nextShape = generateNextShape();
score = 0;
}
/**
* Spawn the queued tetromino piece and generate the next one
*/
public void spawnTetromino() {
currentTetromino = new Tetromino(nextShape);
nextShape = getNextShape();
nextShape = generateNextShape();
}
/**
* @return the currently controlled tetromino piece
*/
public Tetromino getCurrentTetromino() {
return currentTetromino;
}
public TetrominoShape getNextShape() {
/**
* @return a randomly selected tetromino shape
*/
public TetrominoShape generateNextShape() {
return TetrominoShape.values()[random.nextInt(TetrominoShape.values().length)];
}
/**
* @return the queued tetromino shape
*/
public TetrominoShape getNextShape() {
return nextShape;
}
public int getMapWidth() {
return gameMap[0].length;
}
@@ -40,42 +61,65 @@ public class Space {
return gameMap.length;
}
/**
* Converts the current state of the space to an array and includes the falling tetromino.
*
* @return a representation of the space with the falling tetromino baked in
*/
public Color[][] getGameMapWithTetromino() {
Color[][] tempGameMap = new Color[gameMap.length][gameMap[0].length];
for (int y = 0; y < tempGameMap.length; y++) {
System.arraycopy(gameMap[y], 0, tempGameMap[y], 0, tempGameMap[y].length);
if (currentTetromino != null) {
Color[] newBlobs = currentTetromino.getLine(y);
for (int i = 0; i < newBlobs.length; i++) {
if (newBlobs[i] == null) continue;
tempGameMap[y][i] = newBlobs[i];
}
if (currentTetromino == null) continue;
Color[] newBlobs = currentTetromino.getLine(y);
for (int i = 0; i < newBlobs.length; i++) {
if (newBlobs[i] == null) continue;
tempGameMap[y][i] = newBlobs[i];
}
}
return tempGameMap;
}
/**
* Converts the current state of the space to an array.
*
* @return a representation of the space without the falling tetromino baked in
*/
public Color[][] getGameMap() {
return gameMap;
}
public int getScore() {
return score;
}
/**
* Handle line changes.
* Once a line is fully completed, it is removed from the space, the lines above are moved down and the score is increased.
* More lines completed at once increase the combo and therefore the score.
*/
public void onLinesChanged(Tetromino tetromino, int... lines) {
int combo = 0;
Set<Integer> completedLines = new TreeSet<>();
for (int line : lines) {
if (line >= getMapHeight()) continue;
if (line < 0) {
Tetris.stopGame();
return;
}
Color[] newBlobs = tetromino.getLine(line);
for (int i = 0; i < newBlobs.length; i++) {
if (newBlobs[i] == null) continue;
gameMap[line][i] = newBlobs[i];
}
if (Arrays.stream(gameMap[line]).noneMatch(Objects::isNull)) { // Line completed
combo += 10;
combo += 40;
completedLines.add(line);
combo *= completedLines.size();
}
}
if (!completedLines.isEmpty()) SoundEffect.LINE_COMPLETED.play();
for (int completedIndex = 0; completedIndex < completedLines.size(); completedIndex++) { // Remove completed lines
int line = completedLines.toArray(new Integer[0])[completedIndex];
for (int i = line; i >= 0; i--) {
@@ -83,6 +127,7 @@ public class Space {
}
}
increaseScore(combo);
this.spawnTetromino();
}
public void increaseScore(int amount) {

View File

@@ -12,16 +12,24 @@ public class Tetromino {
private Vec2i centerPos;
private int fallLength = 0;
/**
* This class handles the falling tetromino.
* @param shape the tetromino's shape
*/
public Tetromino(TetrominoShape shape) {
this.shape = shape;
this.collision = shape.boundary;
this.centerPos = Vec2i.of(2, 0);
this.centerPos = Vec2i.of(Tetris.getSpace().getMapWidth()/2-1, -1);
}
public void fall(int length) {
Vec2i newPos = centerPos.offset(Vec2i.of(0, length));
/**
* Moves the tetromino vertically.
* Upon hitting solid ground, the piece is released and {@link Space#onLinesChanged(Tetromino, int...)} is triggered.
*/
public boolean fall() {
Vec2i newPos = centerPos.offset(Vec2i.of(0, 1));
if (collidesVertically(newPos)) {
SoundEffect.BEEP.play();
SoundEffect.BOOP.play();
int[] affectedLines = new int[this.collision.length];
int line = centerPos.getY();
for (int i = 0; i < this.collision.length; i++) {
@@ -30,13 +38,17 @@ public class Tetromino {
}
Tetris.getSpace().onLinesChanged(this, affectedLines);
Tetris.getSpace().increaseScore(20-fallLength);
if (fallLength >= 1) Tetris.getSpace().spawnTetromino();
else Tetris.stopGame();
return false;
}
fallLength += 1;
centerPos = newPos;
return true;
}
/**
* Moves the tetromino horizontally.
* Accounts for collision and may prevent movement.
*/
public void move(int xOffset) {
Vec2i newPos = centerPos.offset(Vec2i.of(xOffset, 0));
if (collidesHorizontally(newPos, xOffset)) {
@@ -45,6 +57,11 @@ public class Tetromino {
centerPos = newPos;
}
/**
* Checks, whether the piece would overlap with a block that's already present on the map or would be out-of-bounds.
* @param newPos the new position
* @return true if collision is detected, false otherwise
*/
private boolean collidesVertically(Vec2i newPos) {
if (Tetris.getSpace() == null) return false;
@@ -55,29 +72,39 @@ public class Tetromino {
int maxCollisionY = collision.length - 1;
while (collision[maxCollisionY][i] == 0) maxCollisionY--; // Figure out the collision box's bounding
if (newPos.getY()+maxCollisionY >= Tetris.getSpace().getMapHeight() || newPos.getX() + i >= Tetris.getSpace().getMapWidth()) continue;
if (newPos.getY()+maxCollisionY < 0 || newPos.getY()+maxCollisionY >= Tetris.getSpace().getMapHeight() || newPos.getX() + i >= Tetris.getSpace().getMapWidth()) continue;
collides |= Tetris.getSpace().getGameMap()[newPos.getY() + maxCollisionY][newPos.getX() + i] != null;
}
}
return collides;
}
/**
* Checks, whether the piece would overlap with a block that's already present on the map or would be out-of-bounds.
* @param newPos the new position
* @param xOffset the direction of movement (-1 == left; 1 == right)
* @return true if collision is detected, false otherwise
*/
private boolean collidesHorizontally(Vec2i newPos, int xOffset) {
if (Tetris.getSpace() == null) return false;
boolean collides = newPos.getX() < 0 || newPos.getX() + collision[0].length > Tetris.getSpace().getMapWidth(); // Side check
if (!collides) { // Check for other tetrominos
for (int i = 0; i < collision.length; i++) {
int maxCollisionX = xOffset > 0 ? collision[i].length - 1 : 0;
while (collision[i][maxCollisionX] == 0) maxCollisionX += xOffset > 0 ? -1 : 1; // Figure out the collision box's bounding
int maxCollisionX = xOffset >= 0 ? collision[i].length - 1 : 0;
while (collision[i][maxCollisionX] == 0) maxCollisionX += xOffset >= 0 ? -1 : 1; // Figure out the collision box's bounding
if (newPos.getY()+maxCollisionX >= Tetris.getSpace().getMapHeight()) continue;
if (newPos.getY()+i < 0 || newPos.getY()+i >= Tetris.getSpace().getMapHeight()) continue;
collides |= Tetris.getSpace().getGameMap()[newPos.getY() + i][newPos.getX() + maxCollisionX] != null;
}
}
return collides;
}
/**
* Rotate the tetromino 90 degrees clockwise.
* Fails if the piece would collide vertically or horizontally.
*/
public void rotate() {
int M = collision.length;
int N = collision[0].length;
@@ -88,9 +115,20 @@ public class Tetromino {
newCollision[j][M-i-1] = collision[i][j];
}
}
int[][] prevCollision = this.collision;
this.collision = newCollision;
int offset = 0;
for (int i = 0; i < 4; i++) {
if (collidesHorizontally(this.centerPos.offset(Vec2i.of(offset, 0)), -i)) offset = -i;
}
if (collidesVertically(this.centerPos.offset(Vec2i.of(offset, 0))) || collidesHorizontally(this.centerPos.offset(Vec2i.of(offset, 0)), offset)) this.collision = prevCollision;
else this.centerPos = centerPos.offset(Vec2i.of(offset, 0));
}
/**
* Moves the tetromino piece to its world-view position.
* @return an array representing the line
*/
public Color[] getLine(int line) {
Color[] l = new Color[Tetris.getSpace().getMapWidth()];
for (int i = 0; i < l.length; i++) {
@@ -103,4 +141,13 @@ public class Tetromino {
}
return l;
}
/**
* Moves the tetromino down until it collides.
*/
public void fallToBottom() {
while (true) {
if (!fall()) break;
}
}
}

View File

@@ -5,44 +5,52 @@ import java.awt.Color;
public enum TetrominoShape {
SQUARE(new int[][]{
{1, 1},
{1, 2}
{1, 1}
}, Color.YELLOW),
LINE(new int[][]{
{1},
{2},
{1},
{1},
{1}
}, Color.BLUE),
T(new int[][]{
{0, 1, 0},
{1, 2, 1}
{1, 1, 1}
}, Color.RED),
L_LEFT(new int[][]{
{0, 1},
{0, 2},
{0, 1},
{1, 1}
}, Color.MAGENTA),
L_RIGHT(new int[][]{
{1, 0},
{2, 0},
{1, 0},
{1, 1}
}, Color.GREEN),
ZAP_LEFT(new int[][]{
{0, 1},
{1, 2},
{1, 1},
{1, 0}
}, Color.CYAN),
ZAP_RIGHT(new int[][]{
{1, 0},
{2, 1},
{1, 1},
{0, 1}
}, Color.ORANGE);
;
final int[][] boundary;
final Color color;
TetrominoShape(int[][] boundary, Color color) {
this.boundary = boundary;
this.color = color;
}
public int[][] getBoundary() {
return boundary;
}
public Color getColor() {
return color;
}
}

View File

@@ -1,16 +1,26 @@
package eu.midnightdust.yaytris.ui;
import eu.midnightdust.yaytris.util.CatppuccinColor;
import javax.swing.*;
import java.awt.*;
import static eu.midnightdust.yaytris.ui.TetrisUI.scale;
import static eu.midnightdust.yaytris.ui.TetrisUI.setFontScale;
public class AbstractMenu extends JPanel {
@Override
public Component add(Component comp) {
comp.setBounds(scale(60), scale(20+23*this.getComponentCount()), scale(100), scale(20));
if (comp instanceof JComponent) setFontScale((JComponent) comp);
comp.setBounds(scale(60), scale(20+getSpacing()*this.getComponentCount()), scale(100), scale(20));
if (comp instanceof JLabel) {
comp.setForeground(CatppuccinColor.TEXT.getColor());
}
if (comp instanceof JComponent) {
((JComponent) comp).setOpaque(false);
}
return super.add(comp);
}
public int getSpacing() {
return 23;
}
}

View File

@@ -16,6 +16,12 @@ public class GameCanvas extends JPanel {
this.texture = FileUtil.loadImage("/textures/tetromino.png");
}
/**
* Draw the current state of the game space.
*
* @param graphics the swing graphics instance
*/
@Override
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
if (graphics == null) return;
@@ -32,6 +38,13 @@ public class GameCanvas extends JPanel {
}
}
/**
* Replace a color's alpha channel.
*
* @param color the base color
* @param alpha the opacity (0-255)
* @return the color with the specified alpha channel value
*/
public static Color withAlpha(Color color, int alpha) {
return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
}

View File

@@ -0,0 +1,60 @@
package eu.midnightdust.yaytris.ui;
import eu.midnightdust.yaytris.HighScores;
import eu.midnightdust.yaytris.Settings;
import eu.midnightdust.yaytris.util.CatppuccinColor;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static eu.midnightdust.yaytris.Translation.t;
import static eu.midnightdust.yaytris.ui.TetrisUI.scale;
public class HighScoreMenu extends JPanel {
final TetrisUI ui;
HighScoreMenu(int x, int y, int width, int height, TetrisUI ui) {
this.ui = ui;
this.setBounds(x, y, width, height);
this.setLayout(null);
this.add(new JLabel(t("highscores.title", Settings.difficulty)));
List<String> highscores = new ArrayList<>();
Map<String, Integer> scores = HighScores.diffToMap(Settings.difficulty);
for (String key : scores.keySet()) {
highscores.add(String.format("%s %s", scores.get(key), key));
}
highscores.sort((s1, s2) -> Integer.compare(Integer.parseInt(s2.split("")[0].replace(" ", "")), Integer.parseInt(s1.split("")[0].replace(" ", ""))));
JList<String> highscoreList = new JList<>(highscores.toArray(String[]::new));
highscoreList.setBackground(CatppuccinColor.BASE.getColor());
highscoreList.setForeground(CatppuccinColor.TEXT.getColor());
highscoreList.setSelectionForeground(CatppuccinColor.CRUST.getColor());
JScrollPane highscoreScrollPane = new JScrollPane(highscoreList);
highscoreScrollPane.setBorder(new LineBorder(CatppuccinColor.SURFACE0.getColor(), 3, true));
this.add(highscoreScrollPane);
highscoreScrollPane.setBounds(scale(60), scale(43), scale(100), scale(80));
highscoreList.setBounds(scale(60), scale(43), scale(100), scale(80));
JButton backButton = new JButton(t("ui.back"));
backButton.addActionListener(ui::openMainMenu);
backButton.setBounds(scale(60), scale(140), scale(100), scale(20));
this.add(backButton);
}
@Override
public Component add(Component comp) {
if (comp instanceof JLabel) {
comp.setBounds(scale(60), scale(30), scale(100), scale(7));
comp.setForeground(CatppuccinColor.TEXT.getColor());
}
if (comp instanceof JComponent) {
((JComponent) comp).setOpaque(false);
}
return super.add(comp);
}
}

View File

@@ -2,6 +2,8 @@ package eu.midnightdust.yaytris.ui;
import javax.swing.*;
import static eu.midnightdust.yaytris.Translation.t;
public class MainMenu extends AbstractMenu {
final TetrisUI ui;
@@ -10,15 +12,19 @@ public class MainMenu extends AbstractMenu {
this.setBounds(x, y, width, height);
this.setLayout(null);
JButton startButton = new JButton("Start");
JButton startButton = new JButton(t("menu.start"));
startButton.addActionListener(ui::startGame);
this.add(startButton);
JButton settingsButton = new JButton("Einstellungen");
JButton settingsButton = new JButton(t("menu.settings"));
settingsButton.addActionListener(ui::openSettings);
this.add(settingsButton);
JButton leaveButton = new JButton("Spiel verlassen");
JButton highscoreButton = new JButton(t("menu.highscores"));
highscoreButton.addActionListener(ui::openHighscores);
this.add(highscoreButton);
JButton leaveButton = new JButton(t("menu.exit"));
leaveButton.addActionListener(e -> System.exit(0));
this.add(leaveButton);
}

View File

@@ -0,0 +1,47 @@
package eu.midnightdust.yaytris.ui;
import eu.midnightdust.yaytris.Tetris;
import eu.midnightdust.yaytris.game.TetrominoShape;
import eu.midnightdust.yaytris.util.FileUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
public class PreviewCanvas extends JPanel {
final TetrisUI ui;
final BufferedImage texture;
PreviewCanvas(TetrisUI ui) {
this.ui = ui;
this.texture = FileUtil.loadImage("/textures/tetromino.png");
}
/**
* Draw a preview of the next tetromino piece.
*
* @param graphics the swing graphics instance
*/
@Override
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
if (graphics == null) return;
TetrominoShape nextShape = Tetris.getSpace().getNextShape();
for (int y = 0; y < nextShape.getBoundary().length; y++) {
for (int x = 0; x < nextShape.getBoundary()[0].length; x++) {
Color color = nextShape.getBoundary()[y][x] == 0 ? null : nextShape.getColor(); // Get the color of the blob at these coordinates
if (color == null) continue; // Ignore empty cells
int blockSize = (int) Math.ceil((float) (this.getWidth() - this.getInsets().left - this.getInsets().right) / 4);
int startX = x * blockSize + getInsets().left + ((blockSize / 2) * (4 - nextShape.getBoundary()[0].length));
graphics.drawImage(texture, startX, y*blockSize + getInsets().top, blockSize, blockSize, color, this); // Draw out (grayscale) texture
graphics.setColor(withAlpha(color, 120)); // Overlay the texture with the blobs color
graphics.fillRect(startX, y*blockSize + getInsets().top, blockSize, blockSize);
}
}
}
public static Color withAlpha(Color color, int alpha) {
return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
}
}

View File

@@ -1,34 +1,76 @@
package eu.midnightdust.yaytris.ui;
import eu.midnightdust.yaytris.util.CatppuccinColor;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import static eu.midnightdust.yaytris.Translation.t;
import static eu.midnightdust.yaytris.ui.TetrisUI.scale;
public class ScoreMenu extends AbstractMenu {
final TetrisUI ui;
final PreviewCanvas previewCanvas;
final JLabel gameOverLabel;
final JLabel currentScoreLabel;
final JLabel currentLevelLabel;
final JLabel currentTimeLabel;
ScoreMenu(int x, int y, int width, int height, TetrisUI ui) {
this.ui = ui;
this.setBounds(x, y, width, height);
this.setLayout(null);
this.previewCanvas = new PreviewCanvas(ui);
this.previewCanvas.setBounds(scale(92), scale(4), scale(40), scale(40));
this.previewCanvas.setBackground(Color.BLACK);
this.previewCanvas.setBorder(new LineBorder(CatppuccinColor.SURFACE0.getColor()));
this.add(previewCanvas, 0);
this.gameOverLabel = new JLabel();
this.add(gameOverLabel);
this.currentScoreLabel = new JLabel("Score: 0");
this.currentScoreLabel = new JLabel(t("game.score", "0"));
this.add(currentScoreLabel);
JButton backButton = new JButton("Zurück");
this.currentLevelLabel = new JLabel(t("game.level", "0"));
this.add(currentLevelLabel);
this.currentTimeLabel = new JLabel(t("game.time", "00:00"));
this.add(currentTimeLabel);
JButton backButton = new JButton(t("ui.back"));
backButton.addActionListener(ui::openMainMenu);
this.add(backButton);
}
public void updateScore(int score) {
this.currentScoreLabel.setText("Score: %s".formatted(score));
this.currentScoreLabel.setText(t("game.score", score));
this.repaint();
}
public void updateTime(LocalTime startingTime) {
LocalTime timeElapsed = LocalTime.ofNanoOfDay(LocalTime.now().toNanoOfDay() - startingTime.toNanoOfDay());
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(timeElapsed.getHour() > 0 ? "HH:mm:ss" : "mm:ss");
this.currentTimeLabel.setText(t("game.time", timeFormatter.format(timeElapsed)));
this.repaint();
}
public void gameOver() {
this.gameOverLabel.setText("Game over :(");
this.gameOverLabel.setText(t("game.over"));
}
public void updateLevel(int level) {
this.currentLevelLabel.setText(t("game.level", level));
this.repaint();
}
@Override
public int getSpacing() {
return 17;
}
}

View File

@@ -1,10 +1,18 @@
package eu.midnightdust.yaytris.ui;
import eu.midnightdust.yaytris.Settings;
import eu.midnightdust.yaytris.Translation;
import eu.midnightdust.yaytris.util.CatppuccinColor;
import eu.midnightdust.yaytris.util.Difficulty;
import eu.midnightdust.yaytris.util.Language;
import javax.swing.*;
import java.awt.*;
public class SettingsMenu extends AbstractMenu {
import static eu.midnightdust.yaytris.Translation.t;
import static eu.midnightdust.yaytris.ui.TetrisUI.scale;
public class SettingsMenu extends JPanel {
final TetrisUI ui;
SettingsMenu(int x, int y, int width, int height, TetrisUI ui) {
@@ -12,15 +20,77 @@ public class SettingsMenu extends AbstractMenu {
this.setBounds(x, y, width, height);
this.setLayout(null);
JSlider scaleSlider = new JSlider(100, 500, (int) (Settings.guiScale * 100));
this.add(new JLabel(t("settings.volume.music")));
JSlider musicVolumeSlider = new JSlider(0, 100, Settings.musicVolume);
musicVolumeSlider.addChangeListener(change -> {
Settings.musicVolume = musicVolumeSlider.getValue();
Settings.write();
});
this.add(musicVolumeSlider);
this.add(new JLabel(t("settings.volume.sound")));
JSlider soundVolumeSlider = new JSlider(0, 100, Settings.soundVolume);
soundVolumeSlider.addChangeListener(change -> {
Settings.soundVolume = soundVolumeSlider.getValue();
Settings.write();
});
this.add(soundVolumeSlider);
this.add(new JLabel(t("settings.window_scaling")));
JSlider scaleSlider = new JSlider(100, 600, (int) (Settings.guiScale * 100));
scaleSlider.addChangeListener(change -> {
Settings.guiScale = scaleSlider.getValue() / 100f;
Settings.write();
});
this.add(scaleSlider);
JButton backButton = new JButton("Zurück");
this.add(new JLabel(t("settings.scale_speed")));
JCheckBox speedCheckbox = new JCheckBox("Aktiviert", Settings.shouldScaleSpeed);
speedCheckbox.addChangeListener(change -> {
Settings.shouldScaleSpeed = speedCheckbox.isSelected();
Settings.write();
});
this.add(speedCheckbox);
this.add(new JLabel(t("settings.difficulty")));
JComboBox<Difficulty> difficultySelector = new JComboBox<>(Difficulty.values());
difficultySelector.setSelectedItem(Settings.difficulty);
difficultySelector.addActionListener(action -> {
Settings.difficulty = (Difficulty) difficultySelector.getSelectedItem();
Settings.write();
});
this.add(difficultySelector);
difficultySelector.setSize(difficultySelector.getBounds().width,scale(10));
this.add(new JLabel(t("settings.language")));
JComboBox<Language> languageSelector = new JComboBox<>(Language.values());
languageSelector.setSelectedItem(Settings.language);
languageSelector.addActionListener(action -> {
Settings.language = (Language) languageSelector.getSelectedItem();
Settings.write();
Translation.load(Settings.language.locale);
ui.openSettings(action);
});
this.add(languageSelector);
languageSelector.setSize(languageSelector.getBounds().width,scale(10));
JButton backButton = new JButton(t("ui.back"));
backButton.addActionListener(ui::openMainMenu);
this.add(backButton);
}
int labelAmount = 0;
@Override
public Component add(Component comp) {
comp.setBounds(scale(60), scale(20+17*this.getComponentCount()-labelAmount*10), scale(100), scale(20));
if (comp instanceof JLabel) {
comp.setBounds(scale(60), scale(20+17*(this.getComponentCount())-labelAmount*10), scale(100), scale(7));
comp.setForeground(CatppuccinColor.TEXT.getColor());
labelAmount++;
}
if (comp instanceof JComponent) ((JComponent) comp).setOpaque(false);
return super.add(comp);
}
}

View File

@@ -1,7 +1,7 @@
package eu.midnightdust.yaytris.ui;
import eu.midnightdust.yaytris.HighScores;
import eu.midnightdust.yaytris.Tetris;
import eu.midnightdust.yaytris.game.Space;
import eu.midnightdust.yaytris.util.CatppuccinColor;
import javax.imageio.ImageIO;
@@ -12,34 +12,38 @@ import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.io.InputStream;
import static eu.midnightdust.yaytris.Settings.guiScale;
import static eu.midnightdust.yaytris.Translation.t;
public class TetrisUI extends JFrame implements KeyListener {
JLabel titleLabel;
GameCanvas gamePanel;
JPanel menuPanel;
Image titleImage;
/**
* Initialize the main Tetris GUI based on Swing
*/
public TetrisUI() {
Space space = new Space();
this.setLayout(null);
this.setTitle("Tetris");
this.setSize((int) (400 * guiScale), (int) (300 * guiScale));
this.setSize((int) (400 * guiScale), (int) (320 * guiScale));
this.setResizable(false);
this.getContentPane().setBackground(CatppuccinColor.MANTLE.getColor());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setWindowPosition(this, 0);
this.setLocationRelativeTo(null);
titleLabel = new JLabel("Tetris");
titleLabel.setForeground(Color.WHITE);
Image titleImage;
try {
titleImage = ImageIO.read(this.getClass().getResourceAsStream("/textures/logo.png"));
try (InputStream stream = this.getClass().getResourceAsStream("/textures/logo.png")) {
assert stream != null;
titleImage = ImageIO.read(stream);
} catch (IOException | NullPointerException ex) {
throw new RuntimeException(ex);
}
titleLabel = new JLabel();
titleLabel.setIcon(new ImageIcon(new ImageIcon(titleImage).getImage().getScaledInstance(scale(110), scale(30), Image.SCALE_DEFAULT)));
this.add(titleLabel);
gamePanel = new GameCanvas(this);
@@ -54,21 +58,25 @@ public class TetrisUI extends JFrame implements KeyListener {
this.setVisible(true);
}
/**
* Resize all elements to match the current GUI scale.
*/
private void rescale() {
this.setSize((int) (400 * guiScale), (int) (300 * guiScale));
this.setSize((int) (400 * guiScale), (int) (320 * guiScale));
titleLabel.setBounds(scale(225), scale(7), scale(110), scale(30));
gamePanel.setBounds(scale(10), scale(10), scale(150), scale(256));
for (Component comp : this.getComponents()){
if (comp instanceof JComponent) setFontScale((JComponent) comp);
}
titleLabel.setIcon(new ImageIcon(titleImage.getScaledInstance(scale(110), scale(30), Image.SCALE_DEFAULT)));
gamePanel.setBounds(scale(10), scale(10), scale(150), scale(282));
this.setLocationRelativeTo(null);
}
/**
* Calculate a size/coordinate in relation to the GUI size multiplicator.
*
* @param bound the regular size
*/
public static int scale(int bound) {
return (int) (bound * guiScale);
}
public static void setFontScale(JComponent label) {
//if (label.getFont() != null) label.setFont(label.getFont().deriveFont((float) label.getFont().getSize() * guiScale));
}
public GameCanvas getGamePanel() {
return gamePanel;
@@ -78,77 +86,97 @@ public class TetrisUI extends JFrame implements KeyListener {
return menuPanel;
}
/**
* Start the game let's go!
*
* @param actionEvent unnecessary, but allows for more elegant lambda statements :)
*/
public void startGame(ActionEvent actionEvent) {
Tetris.startGame();
//this.remove(menuPanel);
//menuPanel = null;
this.openScoreMenu(actionEvent);
this.requestFocus();
this.repaint();
}
public void openMainMenu(ActionEvent actionEvent) {
/**
* Open the main menu.
*
* @param actionEvent unnecessary, but allows for more elegant lambda statements :)
*/
public void openMainMenu(@SuppressWarnings("unused") ActionEvent actionEvent) {
if (this.menuPanel != null) this.remove(menuPanel);
Tetris.resetSpace();
rescale();
menuPanel = new MainMenu(scale(170), scale(40), scale(220), scale(226), this);
menuPanel = new MainMenu(scale(170), scale(40), scale(220), scale(252), this);
menuPanel.setBackground(CatppuccinColor.BASE.getColor());
menuPanel.setBorder(new LineBorder(CatppuccinColor.SURFACE0.getColor(), scale(2)));
this.add(menuPanel);
menuPanel.requestFocus();
this.transferFocus();
this.repaint();
}
public void openSettings(ActionEvent actionEvent) {
/**
* Open the settings panel.
*
* @param actionEvent unnecessary, but allows for more elegant lambda statements :)
*/
public void openSettings(@SuppressWarnings("unused") ActionEvent actionEvent) {
if (this.menuPanel != null) this.remove(menuPanel);
menuPanel = new SettingsMenu(scale(170), scale(40), scale(220), scale(226), this);
menuPanel = new SettingsMenu(scale(170), scale(40), scale(220), scale(252), this);
menuPanel.setBackground(CatppuccinColor.BASE.getColor());
menuPanel.setBorder(new LineBorder(CatppuccinColor.SURFACE0.getColor(), scale(2)));
this.add(menuPanel);
this.repaint();
}
public void openScoreMenu(ActionEvent actionEvent) {
/**
* Open a panel showing information about the current game session.
*
* @param actionEvent unnecessary, but allows for more elegant lambda statements :)
*/
public void openScoreMenu(@SuppressWarnings("unused") ActionEvent actionEvent) {
if (this.menuPanel != null) this.remove(menuPanel);
menuPanel = new ScoreMenu(scale(170), scale(40), scale(220), scale(226), this);
menuPanel = new ScoreMenu(scale(170), scale(40), scale(220), scale(252), this);
menuPanel.setBackground(CatppuccinColor.BASE.getColor());
menuPanel.setBorder(new LineBorder(CatppuccinColor.SURFACE0.getColor(), scale(2)));
this.add(menuPanel);
this.repaint();
}
// Source: https://stackoverflow.com/a/19746437
private void setWindowPosition(JFrame window, int screen) {
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] allDevices = env.getScreenDevices();
int topLeftX, topLeftY, screenX, screenY, windowPosX, windowPosY;
if (screen < allDevices.length && screen > -1) {
topLeftX = allDevices[screen].getDefaultConfiguration().getBounds().x;
topLeftY = allDevices[screen].getDefaultConfiguration().getBounds().y;
screenX = allDevices[screen].getDefaultConfiguration().getBounds().width;
screenY = allDevices[screen].getDefaultConfiguration().getBounds().height;
}
else {
topLeftX = allDevices[0].getDefaultConfiguration().getBounds().x;
topLeftY = allDevices[0].getDefaultConfiguration().getBounds().y;
screenX = allDevices[0].getDefaultConfiguration().getBounds().width;
screenY = allDevices[0].getDefaultConfiguration().getBounds().height;
}
windowPosX = ((screenX - window.getWidth()) / 2) + topLeftX;
windowPosY = ((screenY - window.getHeight()) / 2) + topLeftY;
window.setLocation(windowPosX, windowPosY);
/**
* Open a panel showing a list of highscores.
*
* @param actionEvent unnecessary, but allows for more elegant lambda statements :)
*/
public void openHighscores(@SuppressWarnings("unused") ActionEvent actionEvent) {
if (this.menuPanel != null) this.remove(menuPanel);
menuPanel = new HighScoreMenu(scale(170), scale(40), scale(220), scale(252), this);
menuPanel.setBackground(CatppuccinColor.BASE.getColor());
menuPanel.setBorder(new LineBorder(CatppuccinColor.SURFACE0.getColor(), scale(2)));
this.add(menuPanel);
this.repaint();
}
/**
* Open a popup asking for the player's name to save a new highscore.
*
* @param score the new highscore
*/
public void showHighscoreDialog(int score) {
String playerName = JOptionPane.showInputDialog(null, t("dialog.highscore.action"), t("dialog.highscore.title"), JOptionPane.PLAIN_MESSAGE);
if (playerName != null) HighScores.addScore(playerName, score);
}
/**
* Capture keyboard inputs during a game session.
*
* @param e the key event
* @see eu.midnightdust.yaytris.game.Space
*/
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_E:
Tetris.getSpace().spawnTetromino();
break;
case KeyEvent.VK_UP:
case KeyEvent.VK_W:
Tetris.getSpace().getCurrentTetromino().rotate();
@@ -163,10 +191,10 @@ public class TetrisUI extends JFrame implements KeyListener {
break;
case KeyEvent.VK_DOWN:
case KeyEvent.VK_S:
Tetris.getSpace().getCurrentTetromino().fall(1);
Tetris.getSpace().getCurrentTetromino().fall();
break;
case KeyEvent.VK_SPACE:
Tetris.getSpace().getCurrentTetromino().fall(12);
Tetris.getSpace().getCurrentTetromino().fallToBottom();
break;
}
gamePanel.repaint();

View File

@@ -2,11 +2,11 @@ package eu.midnightdust.yaytris.util;
import java.awt.*;
/*
Colors based on the [Catppuccin Mocha](https://github.com/catppuccin/catppuccin) color palette
/**
* Color scheme based on the <a href="https://github.com/catppuccin/catppuccin">Catppuccin Mocha</a> color palette
*/
public enum CatppuccinColor {
CRUST(0x11111b), MANTLE(0x181825), BASE(0x1e1e2e), SURFACE0(0x313244);
TEXT(0xcdd6f4), CRUST(0x11111b), MANTLE(0x181825), BASE(0x1e1e2e), SURFACE0(0x313244);
final Color color;
CatppuccinColor(int rgb) {

View File

@@ -1,14 +1,26 @@
package eu.midnightdust.yaytris.util;
public enum Difficulty {
NOOB(2000), EASY(1200), NORMAL(1000), HARD(750), EXTREME(100), WTF(30);
NOOB(2000), EASY(1200), NORMAL(1000), HARD(500), EXTREME(100), WTF(30, "WTF");
private final int timerPeriod;
private final String name;
Difficulty(int timerPeriod) {
this.timerPeriod = timerPeriod;
this.name = this.name().charAt(0) + this.name().substring(1).toLowerCase();
}
Difficulty(int timerPeriod, String name) {
this.timerPeriod = timerPeriod;
this.name = name;
}
public int getTimerPeriod() {
return timerPeriod;
}
@Override
public String toString() {
return this.name;
}
}

View File

@@ -1,9 +1,6 @@
package eu.midnightdust.yaytris.util;
import javax.imageio.ImageIO;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
@@ -17,21 +14,4 @@ public class FileUtil {
throw new RuntimeException(ex);
}
}
public static AudioInputStream loadAudio(String location) {
try (InputStream fileStream = FileUtil.class.getResourceAsStream(location)) {
assert fileStream != null;
return AudioSystem.getAudioInputStream(fileStream);
} catch (IOException | NullPointerException | UnsupportedAudioFileException ex) {
throw new RuntimeException(ex);
}
}
public static InputStream getFileStream(String location) {
try (InputStream fileStream = FileUtil.class.getResourceAsStream(location)) {
return fileStream;
} catch (IOException | NullPointerException ex) {
throw new RuntimeException(ex);
}
}
}

View File

@@ -0,0 +1,19 @@
package eu.midnightdust.yaytris.util;
import eu.midnightdust.yaytris.Tetris;
import java.util.TimerTask;
/**
* Defines our custom timer task that handles falling pieces.
*/
public class GravityTimerTask extends TimerTask {
@Override
public void run() {
if (Tetris.getSpace().getCurrentTetromino() != null) {
Tetris.updateTime();
Tetris.getSpace().getCurrentTetromino().fall();
Tetris.getUi().getGamePanel().repaint();
}
}
}

View File

@@ -0,0 +1,17 @@
package eu.midnightdust.yaytris.util;
public enum Language {
ENGLISH("en_gb"), DEUTSCH("de_de");
public final String locale;
private final String name;
Language(String locale) {
this.locale = locale;
this.name = this.name().charAt(0) + this.name().substring(1).toLowerCase();
}
@Override
public String toString() {
return this.name;
}
}

View File

@@ -1,113 +0,0 @@
package eu.midnightdust.yaytris.util;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
/*
NightJson v0.1 by Martin Prokoph
Extremely lightweight (and incomplete) JSON library
Concept inspired by GSON
*/
public class NightJson {
private static final String KEY_PATTERN = "\"(-?[0-9a-zA-Z]*)\":";
Class<?> jsonClass;
String fileLocation;
public NightJson(Class<?> jsonClass) {
this.jsonClass = jsonClass;
}
public NightJson(Class<?> jsonClass, String fileLocation) {
this(jsonClass);
this.fileLocation = fileLocation;
}
public void setFileLocation(String fileLocation) {
this.fileLocation = fileLocation;
}
public void writeJson() {
if (fileLocation == null) return;
try {
FileWriter jsonFile = new FileWriter(fileLocation);
jsonFile.write("{\n");
Iterator<Field> it = Arrays.stream(jsonClass.getFields()).iterator();
while (it.hasNext()) {
Field field = it.next();
jsonFile.write("\t");
if (field.getType() == Comment.class) {
jsonFile.write("// %s\n".formatted(((Comment) field.get(null)).commentString));
continue;
}
jsonFile.write((field.getType() == String.class || field.getType().isEnum() ? "\"%s\": \"%s\"" : "\"%s\": %s").formatted(field.getName(), field.get(null)));
jsonFile.write(it.hasNext() ? ",\n" : "\n");
}
jsonFile.write("}");
jsonFile.close();
} catch (IOException | IllegalAccessException e) {
System.out.println("Oh no! An Error occurred whilst writing the JSON file :(");
e.fillInStackTrace();
}
}
public void readJson() {
if (fileLocation == null) return;
try {
File file = new File(fileLocation);
if (!file.exists()) {
writeJson();
return;
}
Scanner jsonFile = new Scanner(file);
Map<String, String> jsonKeyValuePairs = new HashMap<>();
AtomicReference<String> lastKey = new AtomicReference<>();
jsonFile.forEachRemaining(s -> {
if (!s.matches("[{}]") && !s.matches("//+")) {
if (s.matches(KEY_PATTERN)) {
lastKey.set(s.replaceAll("([\":])", ""));
jsonKeyValuePairs.put(lastKey.get(), "");
}
else jsonKeyValuePairs.put(lastKey.get(), (jsonKeyValuePairs.get(
lastKey.get()).isEmpty() ? "" : jsonKeyValuePairs.get(lastKey.get()) + " "
) + s.replaceAll("([\",])", ""));
}
});
for (String key : jsonKeyValuePairs.keySet()) {
String currentString = jsonKeyValuePairs.get(key);
//System.out.printf("Key: %s Value: %s%n", key, currentString);
Field field;
try { field = jsonClass.getField(key);
} catch (NoSuchFieldException e) {continue;}
Object value = switch (field.getType().getName()) {
case "byte" -> Byte.parseByte(currentString);
case "int" -> Integer.parseInt(currentString);
case "long" -> Long.parseLong(currentString);
case "float" -> Float.parseFloat(currentString);
case "double" -> Double.parseDouble(currentString);
default -> currentString;
};
if (field.getType().isEnum()) value = Arrays.stream(field.getType().getEnumConstants())
.filter(enumConstant -> Objects.equals(enumConstant.toString(), currentString)).findFirst().orElseThrow();
field.set(field, value);
}
jsonFile.close();
} catch (IOException | IllegalAccessException | NoSuchElementException e) {
System.out.println("Oh no! An Error occurred whilst reading the JSON file :(");
e.fillInStackTrace();
}
}
public static class Comment {
final String commentString;
public Comment(String commentString) {
this.commentString = commentString;
}
}
}

View File

@@ -1,13 +1,19 @@
package eu.midnightdust.yaytris.util;
import eu.midnightdust.yaytris.util.sound.SoundUtil;
public enum SoundEffect {
BEEP("/sounds/beep.wav");
BOOP("/sounds/boop.wav"), LINE_COMPLETED("/sounds/line-completed.wav");
final String location;
SoundEffect(String location) {
this.location = location;
}
/**
* Play this sound effect aloud
* @see SoundUtil#playSoundClip(String)
*/
public void play() {
SoundUtil.playSoundClip(location);
}

View File

@@ -1,108 +0,0 @@
package eu.midnightdust.yaytris.util;
import eu.midnightdust.yaytris.Settings;
import javax.sound.sampled.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class SoundUtil {
private static final Map<String, MusicThread> musicThreads = new HashMap<>();
public static void playMusic(String fileLocation, boolean looped) {
if (musicThreads.containsKey(fileLocation)) stopMusic(fileLocation);
MusicThread musicThread = new MusicThread(fileLocation, looped);
musicThread.start();
musicThreads.put(fileLocation, musicThread);
}
public static void stopMusic(String fileLocation) {
if (musicThreads.containsKey(fileLocation)) musicThreads.get(fileLocation).stopMusic();
}
// Adapted from: https://www.baeldung.com/java-play-sound
public static void playSoundClip(String fileLocation) {
try (AudioInputStream stream = AudioSystem.getAudioInputStream(SoundUtil.class.getResource(fileLocation))) { // FIXME: Support audio files from JAR. File streams won't work here for some reason.
AudioFormat format = stream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip audioClip = (Clip) AudioSystem.getLine(info);
audioClip.addLineListener(new LineUpdateListener());
audioClip.open(stream);
audioClip.start();
setVolume(audioClip, Settings.soundVolume);
} catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) {
throw new RuntimeException(e);
}
}
// Adapted from: https://stackoverflow.com/a/40698149
private static void setVolume(Line line, int volume) {
if (volume < 0 || volume > 100)
throw new IllegalArgumentException("Volume not valid: " + volume);
FloatControl gainControl = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(20f * (float) Math.log10(volume/100f));
}
public static class MusicThread extends Thread {
private static final int BUFFER_SIZE = 8192;
private final boolean looped;
private final String fileLocation;
private boolean playing;
MusicThread(String fileLocation, boolean looped) {
this.fileLocation = fileLocation;
this.looped = looped;
this.playing = true;
}
public void stopMusic() {
this.playing = false;
}
@Override
public void run() {
do {playMusic(fileLocation);} while (looped && playing);
}
// Adapted from: https://www.baeldung.com/java-play-sound
private void playMusic(String fileLocation) {
try (AudioInputStream stream = AudioSystem.getAudioInputStream(SoundUtil.class.getResource(fileLocation))) {
AudioFormat format = stream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
sourceDataLine.open(format);
sourceDataLine.start();
setVolume(sourceDataLine, Settings.musicVolume);
float fadeOut = 1.0f;
byte[] bufferBytes = new byte[BUFFER_SIZE];
int readBytes;
while ((readBytes = stream.read(bufferBytes)) != -1) {
if (!playing) {
fadeOut = (float) Math.sin(fadeOut-0.01f); // Sinus fade-out
setVolume(sourceDataLine, (int) (fadeOut * Settings.musicVolume));
if (fadeOut <= 0) break;
}
sourceDataLine.write(bufferBytes, 0, readBytes);
}
sourceDataLine.drain();
sourceDataLine.close();
} catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) {
throw new RuntimeException(e);
}
}
}
public static class LineUpdateListener implements LineListener {
@Override
public void update(LineEvent event) {
if (LineEvent.Type.STOP == event.getType()) {
event.getLine().close();
}
}
}
}

View File

@@ -9,22 +9,36 @@ public class Vec2i {
this.y = y;
}
public static Vec2i of(int x) {
//noinspection SuspiciousNameCombination
return new Vec2i(x, x);
}
/**
* Creates a vector holding two signed ints.
*
* @param x the x value
* @param y the y value
*/
public static Vec2i of(int x, int y) {
return new Vec2i(x, y);
}
/**
* @return the saved x value
*/
public int getX() {
return x;
}
/**
* @return the saved y value
*/
public int getY() {
return y;
}
/**
* Offset each coordinate of this vector by the same coordinate of another vector
*
* @param other the vector to add
* @return the sum of both vectors
*/
public Vec2i offset(Vec2i other) {
return new Vec2i(x + other.getX(), y + other.getY());
}

View File

@@ -0,0 +1,19 @@
package eu.midnightdust.yaytris.util.json;
/**
* Add comments to your json files.
* If you decide to use this, it's best to save with the .json5 extension, as regular json does not officially support comments.
*/
public class Comment {
final String commentString;
/**
* Add a comment to spice-up the json file :)
*
* @param commentString the string you want to write as a comment
* @param args optional formatting arguments, calls {@link String#format(String, Object...)}
*/
public Comment(String commentString, Object... args) {
this.commentString = String.format(commentString, args);
}
}

View File

@@ -0,0 +1,267 @@
package eu.midnightdust.yaytris.util.json;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.nio.file.Files;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* NightJson v0.3 by Martin Prokoph
* Extremely lightweight JSON library
* Concept inspired by GSON
*/
public class NightJson {
private static final String KEY_PATTERN = "\"(.*)\":";
Class<?> jsonClass;
Field jsonMap;
String fileLocation;
/**
* Initialize the NightJSON json reader & writer.
*
* @param jsonClass the java class that should be linked to the json file
* @param fileLocation the location the json file is read from and written to
*/
public NightJson(Class<?> jsonClass, String fileLocation) {
this.jsonClass = jsonClass;
this.fileLocation = fileLocation;
getField("jsonMap").ifPresent(f -> {
if (f.getType() == Map.class && getTypeArgument(f, 0) == String.class) jsonMap = f;
});
}
/**
* Convert the current state of the java json class to actual json and save it to disk.
*/
public void writeJson() {
if (fileLocation == null) return;
try {
FileWriter jsonFile = new FileWriter(fileLocation);
writeJsonToFile(jsonFile);
} catch (IOException | IllegalAccessException e) {
System.out.println("Oh no! An Error occurred whilst writing the JSON file :(");
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private void writeJsonToFile(FileWriter jsonFile) throws IOException, IllegalAccessException {
jsonFile.write("{\n");
Iterator<Field> it = Arrays.stream(jsonClass.getFields()).iterator();
while (it.hasNext()) {
Field field = it.next();
if (field != jsonMap) writeElement(jsonFile, field.get(null), field.getType(), field.getName(), it.hasNext());
}
if (jsonMap != null) {
Iterator<String> mapIt = ((Map<String,?>)jsonMap.get(null)).keySet().iterator();
while (mapIt.hasNext()) {
String key = mapIt.next();
Object value = jsonMap.get(key);
writeElement(jsonFile, value, value.getClass(), key, mapIt.hasNext());
}
}
jsonFile.write("}");
jsonFile.close();
}
/**
* Write the desired element into the file.
*/
private void writeElement(FileWriter jsonFile, Object value, Class<?> type, String name, boolean hasNext) throws IOException {
jsonFile.write("\t");
if (type == Comment.class) {
jsonFile.write(String.format("// %s\n", ((Comment) value).commentString));
return;
}
jsonFile.write(String.format("\"%s\": ", name));
jsonFile.write(objToString(value, type));
jsonFile.write(hasNext ? ",\n" : "\n");
}
/**
* Converts the specified value object to its json representation.
*/
private String objToString(Object value, Class<?> type) {
if (type == Map.class) {
StringBuilder mapPairs = new StringBuilder();
Map<?, ?> map = (Map<?, ?>) value;
Iterator<?> it = map.keySet().iterator();
mapPairs.append(it.hasNext() ? "{" : "{}");
while (it.hasNext()) {
Object key = it.next();
Object val = map.get(key);
mapPairs.append("\n\t\t");
mapPairs.append(String.format("%s: %s", objToString(key, key.getClass()), objToString(val, val.getClass())));
mapPairs.append(it.hasNext() ? "," : "\n\t}");
}
return mapPairs.toString();
}
return String.format(type == String.class || type.isEnum() ? "\"%s\"" : "%s", value);
}
public void readJson() {
if (fileLocation == null) return;
try {
File file = new File(fileLocation);
if (!file.exists()) {
writeJson();
return;
}
readJsonFromString(Files.readString(file.toPath()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Read the json file from disk and overwrite the json class's field values.
*/
public void readJsonFromString(String jsonString) {
try {
readJsonString(jsonString);
} catch (IllegalAccessException | NoSuchElementException | ClassCastException e) {
System.out.println("Oh no! An Error occurred whilst reading the JSON file :(");
//noinspection CallToPrintStackTrace
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private void readJsonString(String jsonString) throws IllegalAccessException {
Map<String, Object> asMap = jsonToMap(
jsonString.replaceAll("(//)+.*\n", ""), // Replace comment lines (Json5)
(key) -> getField(key).isPresent() ? getField(key).get().getType() : String.class); // Determine data type
for (String key : asMap.keySet()) {
Object value = asMap.get(key);
Optional<Field> field = getField(key);
if (field.isPresent()) {
field.get().set(null, value);
}
else if (jsonMap != null) {
((Map<String, Object>)jsonMap.get(null)).put(key, value);
}
}
}
/**
* Read the json file as key-value pairs and save it as a map.
*/
private Map<String, Object> jsonToMap(String jsonString, Function<String, Class<?>> keyToType) {
Map<String, Object> map = new HashMap<>();
Iterator<String> pairIterator = Arrays.stream(jsonString.replaceAll("(//)+.*\n", "").replaceFirst("[{]", "").split(",")).iterator();
while (pairIterator.hasNext()) {
String s = pairIterator.next();
Matcher matcher = Pattern.compile(KEY_PATTERN).matcher(s);
if (matcher.find()) {
String key = matcher.group().replaceAll("([\":])", "");
map.put(key, getValue(s, key, keyToType, pairIterator));
}
}
return map;
}
/**
* Read the current key in the json file.
*/
private Object getValue(String s, String key, Function<String, Class<?>> keyToType, Iterator<String> pairIterator) {
String val = s.split(KEY_PATTERN, 2)[1];
if (s.contains("{")) {
return readJsonMap(key, pairIterator, val);
}
else {
while (val.startsWith(" ")) val = val.substring(1);
val = val.replaceAll("[\"}\n]", "");
while (val.endsWith(",") || val.endsWith("\n") || val.endsWith("\t")) val = val.substring(0, val.length() - 1);
return stringToObj(val, keyToType.apply(key));
}
}
/**
* Handle maps recursively
*/
private Map<String, Object> readJsonMap(String key, Iterator<String> pairIterator, String val) {
StringBuilder submapString = new StringBuilder();
String next = val;
int level = 0;
while (next != null) {
submapString.append(next);
level += charAmount(next, '{');
level -= charAmount(next, '}');
if (level <= 0) break;
if (!pairIterator.hasNext()) {
submapString.append(",");
next = pairIterator.next();
} else next = null;
}
Optional<Field> field = getField(key);
return jsonToMap(String.valueOf(submapString), k -> field.isPresent() ? getTypeArgument(field.get(), 1) : String.class);
}
/**
* Count the amount of appearances of a char in a string.
*
* @param input the string to search in
* @param c the char to count
*/
private int charAmount(String input, char c) {
return (int) input.chars().filter(ch -> ch == c).count();
}
/**
* Converts the value from a json string to the actual field type.
*/
private Object stringToObj(String value, Class<?> type) {
switch (type.getName()) {
case "byte": return Byte.parseByte(value);
case "int": return Integer.parseInt(value);
case "long": return Long.parseLong(value);
case "float": return Float.parseFloat(value);
case "double": return Double.parseDouble(value);
case "boolean": return Boolean.parseBoolean(value);
}
if (type.isEnum()) return Arrays.stream(type.getEnumConstants())
.filter(enumConstant -> Objects.equals(enumConstant.toString(), value)).findFirst().orElseThrow();
else return value;
}
/**
* Gets the type arguments of typed data structures, such as lists or maps.
* @param field the associated field
* @param index the type index (relevant for maps)
*/
private static Class<?> getTypeArgument(Field field, int index) {
return getPrimitiveType((Class<?>) ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[index]);
}
/**
* Tries to get primitive types from non-primitives (e.g. Boolean -> boolean)
*/
public static Class<?> getPrimitiveType(Class<?> rawType) {
try { return (Class<?>) rawType.getField("TYPE").get(null);
} catch (NoSuchFieldException | IllegalAccessException ignored) { return rawType; }
}
/**
* Get a field from a class by its name.
* @param name the field specifier
* @return an optional representation of the field
*/
private Optional<Field> getField(String name) {
try {
return Optional.of(jsonClass.getField(name));
} catch (NoSuchFieldException e) {
return Optional.empty();
}
}
}

View File

@@ -0,0 +1,13 @@
package eu.midnightdust.yaytris.util.sound;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
public class LineUpdateListener implements LineListener {
@Override
public void update(LineEvent event) {
if (LineEvent.Type.STOP == event.getType()) {
event.getLine().close();
}
}
}

View File

@@ -0,0 +1,72 @@
package eu.midnightdust.yaytris.util.sound;
import eu.midnightdust.yaytris.Settings;
import javax.sound.sampled.*;
import java.io.IOException;
/**
* Handle music in separate threads to not interrupt the main game
*/
public class MusicThread extends Thread {
private static final int BUFFER_SIZE = 8192;
private final boolean looped;
private final String fileLocation;
private boolean playing;
public MusicThread(String fileLocation, boolean looped) {
this.fileLocation = fileLocation;
this.looped = looped;
this.playing = true;
}
public void stopMusic() {
this.playing = false;
}
@Override
public void run() {
do {
playMusic(fileLocation);
} while (looped && playing);
}
/**
* INTERNAL!
* Play the long audio file found at the specified location.
* Fades out after calling {@link #stopMusic()}.
* Adapted from: <a href="https://www.baeldung.com/java-play-sound">Baeldung</a>
*
* @see SoundUtil#playMusic(String, boolean)
*/
private void playMusic(String fileLocation) {
try (AudioInputStream stream = AudioSystem.getAudioInputStream(SoundUtil.getResource(fileLocation))) {
AudioFormat format = stream.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
SourceDataLine sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
sourceDataLine.open(format);
sourceDataLine.start();
SoundUtil.setVolume(sourceDataLine, Settings.musicVolume);
float fadeOut = 1.0f;
byte[] bufferBytes = new byte[BUFFER_SIZE];
int readBytes;
while ((readBytes = stream.read(bufferBytes)) != -1) {
if (!playing) {
fadeOut = (float) Math.sin(fadeOut - 0.01f); // Sinus fade-out
SoundUtil.setVolume(sourceDataLine, (int) (fadeOut * Settings.musicVolume));
if (fadeOut <= 0) break;
}
sourceDataLine.write(bufferBytes, 0, readBytes);
}
sourceDataLine.drain();
sourceDataLine.close();
} catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException ignored) {
// Happens when no audio device is connected
}
}
}

View File

@@ -0,0 +1,77 @@
package eu.midnightdust.yaytris.util.sound;
import eu.midnightdust.yaytris.Settings;
import javax.sound.sampled.*;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class SoundUtil {
private static final Map<String, MusicThread> musicThreads = new HashMap<>();
/**
* Play the long audio file found at the specified location.
*
* @param fileLocation the URI of the desired audio file (should be a .wav file)
* @param looped whether to repeat the song indefinitely after it finishes
*/
public static void playMusic(String fileLocation, boolean looped) {
if (musicThreads.containsKey(fileLocation)) stopMusic(fileLocation);
MusicThread musicThread = new MusicThread(fileLocation, looped);
musicThread.start();
musicThreads.put(fileLocation, musicThread);
}
/**
* Stop the long audio file found at the specified location, if it is playing.
* Also has a nice smooth fade-out effect.
*
* @param fileLocation the URI of the desired audio file (should be a .wav file)
*/
public static void stopMusic(String fileLocation) {
if (musicThreads.containsKey(fileLocation)) musicThreads.get(fileLocation).stopMusic();
}
/**
* Play a short audio clip found at the specified location.
* Adapted from: <a href="https://www.baeldung.com/java-play-sound">Baeldung</a>
*
* @param fileLocation the URI of the desired audio file (should be a .wav file)
*/
public static void playSoundClip(String fileLocation) {
try (AudioInputStream stream = AudioSystem.getAudioInputStream(getResource(fileLocation))) {
AudioFormat format = stream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
Clip audioClip = (Clip) AudioSystem.getLine(info);
audioClip.addLineListener(new LineUpdateListener());
audioClip.open(stream);
audioClip.start();
setVolume(audioClip, Settings.soundVolume);
} catch (LineUnavailableException | IOException | UnsupportedAudioFileException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException ignored) {
// Happens when no audio device is connected
}
}
protected static URL getResource(String fileLocation) {
return SoundUtil.class.getResource(fileLocation);
}
/**
* Set the volume for the audio player.
* Adapted from: <a href="https://stackoverflow.com/a/40698149">Steve Eynon on StackOverflow</a>
*
* @param line the DataLine responsible for audio playback
* @param volume the requested volume in percent (0-100%)
*/
protected static void setVolume(Line line, int volume) {
if (volume < 0 || volume > 100)
throw new IllegalArgumentException("Volume not valid: " + volume);
FloatControl gainControl = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(20f * (float) Math.log10(volume/100f));
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,20 @@
{
"dialog.highscore.action": "Gib deinen Namen ein:",
"dialog.highscore.title": "Neuer Highscore!",
"game.level": "Level: %s",
"game.over": "Game over :(",
"game.score": "Score: %s",
"game.time": "Zeit: %s",
"highscores.title": "Highscores (%s):",
"menu.exit": "Spiel verlassen",
"menu.highscores": "Highscores",
"menu.settings": "Einstellungen",
"menu.start": "Start",
"settings.difficulty": "Schwierigkeit:",
"settings.language": "Sprache:",
"settings.scale_speed": "Geschwindigkeitszunahme:",
"settings.volume.music": "Musik-Lautstärke:",
"settings.volume.sound": "Effekt-Lautstärke:",
"settings.window_scaling": "Fenster-Skalierung:",
"ui.back": "Zurück"
}

View File

@@ -0,0 +1,20 @@
{
"dialog.highscore.action": "Enter your name:",
"dialog.highscore.title": "New Highscore!",
"game.level": "Level: %s",
"game.over": "Game over :(",
"game.score": "Score: %s",
"game.time": "Time: %s",
"highscores.title": "Highscores (%s):",
"menu.exit": "Exit Game",
"menu.highscores": "Highscores",
"menu.settings": "Settings",
"menu.start": "Start",
"settings.difficulty": "Difficulty:",
"settings.language": "Language:",
"settings.scale_speed": "Speed Increase:",
"settings.volume.music": "Music Volume:",
"settings.volume.sound": "Sound Volume:",
"settings.window_scaling": "Window Scaling:",
"ui.back": "Back"
}

11
tetris_scores.json5 Normal file
View File

@@ -0,0 +1,11 @@
{
// Highscores for each difficulty
"Noob": {},
"Easy": {},
"Normal": {
"Martin": 10593
},
"Hard": {},
"Extreme": {},
"WTF": {}
}

View File

@@ -1,6 +1,14 @@
{
// Volume of theme music (0-100)
"musicVolume": 100,
// Volume of sound effects (0-100)
"soundVolume": 100,
"guiScale": 5.0,
"difficulty": "NORMAL"
// Amount the user interface should be scaled
"guiScale": 2.00,
// Whether speed should scale with level (true/false)
"shouldScaleSpeed": true,
// One of [Noob, Easy, Normal, Hard, Extreme, WTF]
"difficulty": "Normal",
// One of [English, Deutsch]
"language": "Deutsch"
}