Compare commits

..

4 Commits

Author SHA1 Message Date
cb488f9853 feat: Show icons in stats 2026-01-20 12:36:18 +01:00
da45765413 feat: Dialog answering 2026-01-19 20:17:13 +01:00
eef269c853 feat: Implemented text rendering 2026-01-19 17:20:49 +01:00
6335ab7e5c chore: Started implementing dialog 2026-01-19 09:30:50 +01:00
347 changed files with 2795 additions and 10703 deletions

41
.gitignore vendored
View File

@@ -1 +1,42 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
.kotlin
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
.idea/FuzzierSettings.xml
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
logs

View File

@@ -1,14 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="com.mituuz.fuzzier.FuzzierSettings">
<option name="modules">
<map>
<entry key="common" value="$PROJECT_DIR$" />
<entry key="game" value="$PROJECT_DIR$" />
<entry key="game (1)" value="$PROJECT_DIR$" />
<entry key="server" value="$PROJECT_DIR$" />
</map>
</option>
<option name="recentlySearchedFiles" value="rO0ABXNyABxqYXZheC5zd2luZy5EZWZhdWx0TGlzdE1vZGVsBgfGCGLvV2ICAAFMAAhkZWxlZ2F0ZXQAEkxqYXZhL3V0aWwvVmVjdG9yO3hyAB1qYXZheC5zd2luZy5BYnN0cmFjdExpc3RNb2RlbFrW+oYSs63tAgABTAAMbGlzdGVuZXJMaXN0dAAlTGphdmF4L3N3aW5nL2V2ZW50L0V2ZW50TGlzdGVuZXJMaXN0O3hwc3IAI2phdmF4LnN3aW5nLmV2ZW50LkV2ZW50TGlzdGVuZXJMaXN0kUjMLXPfDt4DAAB4cHB4c3IAEGphdmEudXRpbC5WZWN0b3LZl31bgDuvAQMAA0kAEWNhcGFjaXR5SW5jcmVtZW50SQAMZWxlbWVudENvdW50WwALZWxlbWVudERhdGF0ABNbTGphdmEvbGFuZy9PYmplY3Q7eHAAAAAAAAAAB3VyABNbTGphdmEubGFuZy5PYmplY3Q7kM5YnxBzKWwCAAB4cAAAAApzcgBIY29tLm1pdHV1ei5mdXp6aWVyLmVudGl0aWVzLkZ1enp5TWF0Y2hDb250YWluZXIkU2VyaWFsaXplZE1hdGNoQ29udGFpbmVy2S8sP5uny74CAARMAAhmaWxlUGF0aHQAEkxqYXZhL2xhbmcvU3RyaW5nO0wACGZpbGVuYW1lcQB+AA1MAA5tb2R1bGVCYXNlUGF0aHEAfgANTAAFc2NvcmV0ADxMY29tL21pdHV1ei9mdXp6aWVyL2VudGl0aWVzL0Z1enp5TWF0Y2hDb250YWluZXIkRnV6enlTY29yZTt4cHQARC9nYW1lL3NyYy9tYWluL2phdmEvY3ovanppdG5pay9jbGllbnQvdXRpbHMvZXZlbnRzL0V2ZW50TWFuYWdlci5qYXZhdAARRXZlbnRNYW5hZ2VyLmphdmF0ABYvaG9tZS9rdWJhL0NvZGluZy9nYW1lc3IAOmNvbS5taXR1dXouZnV6emllci5lbnRpdGllcy5GdXp6eU1hdGNoQ29udGFpbmVyJEZ1enp5U2NvcmUvP9P07ROG2QIABUkADWZpbGVuYW1lU2NvcmVJAA9tdWx0aU1hdGNoU2NvcmVJABBwYXJ0aWFsUGF0aFNjb3JlSQALc3RyZWFrU2NvcmVMABNoaWdobGlnaHRDaGFyYWN0ZXJzdAAPTGphdmEvdXRpbC9TZXQ7eHAAAAAMAAAAAAAAAAoAAAAHc3IAEWphdmEudXRpbC5IYXNoU2V0ukSFlZa4tzQDAAB4cHcMAAAAED9AAAAAAAAMc3IAEWphdmEubGFuZy5JbnRlZ2VyEuKgpPeBhzgCAAFJAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cAAAAABzcQB+ABgAAAABc3EAfgAYAAAAAnNxAH4AGAAAAANzcQB+ABgAAAAEc3EAfgAYAAAABXNxAH4AGAAAAAZzcQB+ABgAAAAHc3EAfgAYAAAACHNxAH4AGAAAAAlzcQB+ABgAAAAKc3EAfgAYAAAAC3hzcQB+AAx0AEQvZ2FtZS9zcmMvbWFpbi9qYXZhL2N6L2p6aXRuaWsvY2xpZW50L3NvY2tldC9Tb2NrZXRFdmVudE1hbmFnZXIuamF2YXQAF1NvY2tldEV2ZW50TWFuYWdlci5qYXZhdAAWL2hvbWUva3ViYS9Db2RpbmcvZ2FtZXNxAH4AEwAAABEAAAAAAAAAAAAAAApzcQB+ABZ3DAAAACA/QAAAAAAAEXEAfgAacQB+ABtxAH4AHHEAfgAdcQB+AB5xAH4AH3EAfgAgcQB+ACFxAH4AInEAfgAjcQB+ACRxAH4AJXNxAH4AGAAAAAxzcQB+ABgAAAANc3EAfgAYAAAADnNxAH4AGAAAAA9zcQB+ABgAAAAQeHNxAH4ADHQADS9nYW1lL3BvbS54bWx0AAdwb20ueG1sdAAWL2hvbWUva3ViYS9Db2RpbmcvZ2FtZXNxAH4AEwAAAAAAAAAAAAAAAAAAAAxzcQB+ABZ3DAAAAAE/QAAAAAAAAHhzcQB+AAx0AEkvZ2FtZS9zcmMvbWFpbi9qYXZhL2N6L2p6aXRuaWsvY2xpZW50L2Fubm90YXRpb25zL1NvY2tldEV2ZW50SGFuZGxlci5qYXZhdAAXU29ja2V0RXZlbnRIYW5kbGVyLmphdmF0ABYvaG9tZS9rdWJhL0NvZGluZy9nYW1lc3EAfgATAAAAEgAAAAAAAAAKAAAAEHNxAH4AFncMAAAAID9AAAAAAAAScQB+ABpxAH4AG3EAfgAccQB+AB1xAH4AHnEAfgAfcQB+ACBxAH4AIXEAfgAicQB+ACNxAH4AJHEAfgAlcQB+ACxxAH4ALXEAfgAucQB+AC9xAH4AMHNxAH4AGAAAABF4c3EAfgAMdAA/L2dhbWUvc3JjL21haW4vamF2YS9jei9qeml0bmlrL2NsaWVudC9nYW1lL3NldHVwL0dhbWVTZXR1cC5qYXZhdAAOR2FtZVNldHVwLmphdmF0ABYvaG9tZS9rdWJhL0NvZGluZy9nYW1lc3EAfgATAAAADAAAAAAAAAAAAAAABHNxAH4AFncMAAAAED9AAAAAAAAMc3EAfgAYAAAAAHNxAH4AGAAAAAFzcQB+ABgAAAACc3EAfgAYAAAAA3NxAH4AGAAAAARzcQB+ABgAAAAFc3EAfgAYAAAABnNxAH4AGAAAAAdzcQB+ABgAAAAIc3EAfgAYAAAACXNxAH4AGAAAAApzcQB+ABgAAAALeHNxAH4ADHQASS9nYW1lL3NyYy9tYWluL2phdmEvY3ovanppdG5pay9jbGllbnQvZ2FtZS9tb2JzL3Rhc2tzL3V0aWxzL0FTdGFyQWxnLmphdmF0AA1BU3RhckFsZy5qYXZhdAAWL2hvbWUva3ViYS9Db2RpbmcvZ2FtZXNxAH4AEwAAAAgAAAAAAAAACgAAAARzcQB+ABZ3DAAAABA/QAAAAAAACHEAfgBEcQB+AEVxAH4ARnEAfgBHcQB+AEhxAH4ASXEAfgBKcQB+AEt4c3EAfgAMdAA4L2dhbWUvc3JjL21haW4vamF2YS9jei9qeml0bmlrL2NsaWVudC91aS91dGlscy9HcmlkLmphdmF0AAlHcmlkLmphdmF0ABYvaG9tZS9rdWJhL0NvZGluZy9nYW1lc3EAfgATAAAACQAAAAAAAAAAAAAABnNxAH4AFncMAAAAED9AAAAAAAAJcQB+AERxAH4ARXEAfgBGcQB+AEdxAH4ASHEAfgBJcQB+AEpxAH4AS3EAfgBMeHBwcHg=" />
</component>
</project>

41
.idea/compiler.xml generated
View File

@@ -1,41 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
</profile>
<profile name="Annotation profile for common" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<processorPath useClasspath="false">
<entry name="$MAVEN_REPOSITORY$/org/projectlombok/lombok/1.18.42/lombok-1.18.42.jar" />
</processorPath>
<module name="common" />
</profile>
<profile name="Annotation profile for server" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<processorPath useClasspath="false">
<entry name="$MAVEN_REPOSITORY$/org/projectlombok/lombok/1.18.42/lombok-1.18.42.jar" />
</processorPath>
<module name="server" />
</profile>
<profile name="Annotation profile for game-parent" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<processorPath useClasspath="false">
<entry name="$MAVEN_REPOSITORY$/org/projectlombok/lombok/1.18.38/lombok-1.18.38.jar" />
</processorPath>
<module name="game (1)" />
<module name="game" />
</profile>
</annotationProcessing>
</component>
</project>

View File

@@ -1,6 +0,0 @@
<component name="CopyrightManager">
<copyright>
<option name="notice" value="Copyright (C) &amp;#36;today.year Jakub Žitník&#10;&#10;This program is free software: you can redistribute it and/or modify&#10;it under the terms of the GNU General Public License as published by&#10;the Free Software Foundation, either version 3 of the License, or&#10;(at your option) any later version&#10;&#10;This program is distributed in the hope that it will be useful,&#10;but WITHOUT ANY WARRANTY; without even the implied warranty of&#10;MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the&#10;GNU General Public License for more details.&#10;&#10;You should have received a copy of the GNU General Public License&#10;along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;." />
<option name="myName" value="GPL 3.0" />
</copyright>
</component>

View File

@@ -1,3 +0,0 @@
<component name="CopyrightManager">
<settings default="GPL 3.0" />
</component>

6
.idea/encodings.xml generated
View File

@@ -1,12 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/common/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/common/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/game/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/game/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/server/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/server/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>

View File

@@ -1,25 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="be.0110.repo-releases" />
<option name="name" value="0110.be repository" />
<option name="url" value="https://mvn.0110.be/releases" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>

16
.idea/misc.xml generated
View File

@@ -1,5 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<list size="3">
<item index="0" class="java.lang.String" itemvalue="cz.jzitnik.annotations.EventHandler" />
<item index="1" class="java.lang.String" itemvalue="cz.jzitnik.annotations.ui.KeyboardPressHandler" />
<item index="2" class="java.lang.String" itemvalue="cz.jzitnik.annotations.ui.MouseHandler" />
</list>
<writeAnnotations>
<writeAnnotation name="cz.jzitnik.annotations.injectors.InjectConfig" />
<writeAnnotation name="cz.jzitnik.annotations.injectors.InjectDependency" />
<writeAnnotation name="cz.jzitnik.annotations.injectors.InjectState" />
</writeAnnotations>
</component>
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
@@ -8,5 +20,7 @@
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="openjdk-25" project-jdk-type="JavaSDK" />
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="openjdk-25" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

674
COPYING
View File

@@ -1,674 +0,0 @@
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>.

View File

@@ -1,37 +0,0 @@
# Lost in a cave
A multiplayer terminal-based game built with Java, utilizing WebSockets for communication and Lanterna for the text-based user interface.
## Project Structure
* **game**: Client application (TUI).
* **server**: WebSocket server.
* **common**: Shared libraries and logic.
## Requirements
* Java 25
* Maven
## How to Run
1. Build the project:
```bash
mvn clean install
```
2. Start the server:
```bash
mvn compile exec:java -pl server -am
```
3. Start the client (in a new terminal):
```bash
mvn compile exec:java -pl game -am
```
## Controls
* **Left Click**: Interact with objects and fight.
* **WASD**: Move the character.
* **CTRL**: Hold to run (sprint).

39
common/.gitignore vendored
View File

@@ -1,39 +0,0 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
.kotlin
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

3
common/.idea/.gitignore generated vendored
View File

@@ -1,3 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>

14
common/.idea/misc.xml generated
View File

@@ -1,14 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" default="true" project-jdk-name="openjdk-25" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
common/.idea/vcs.xml generated
View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View File

@@ -1,69 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cz.jzitnik</groupId>
<artifactId>game-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>common</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.42</version>
</path>
</annotationProcessorPaths>
<source>25</source>
<target>25</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>tools.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.42</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.17</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -1,10 +0,0 @@
package cz.jzitnik.common;
/**
* Configuration constants for the common module.
*
* @author Jakub Žitník (jzitnik)
*/
public class Config {
public static final int WORLD_PASSWORD_LENGTH = 5;
}

View File

@@ -1,118 +0,0 @@
package cz.jzitnik.common.models.coordinates;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import java.util.List;
/**
* Represents coordinates in a room.
*
* @author Jakub Žitník (jzitnik)
*/
@Slf4j
@ToString
@Getter
public class RoomCords implements Cloneable, Serializable {
private int x;
private int y;
/**
* Calculates the center coordinate based on a texture's dimensions.
*
* @param texture The texture to calculate the center for
* @return A new RoomCords instance representing the center
*/
public RoomCords calculateCenter(BufferedImage texture) {
return new RoomCords(
x + texture.getWidth() / 2,
y + texture.getHeight() / 2
);
}
/**
* Constructs RoomCords with specified x and y values.
*
* @param x The x coordinate
* @param y The y coordinate
*/
@JsonCreator
public RoomCords(
@JsonProperty("x") int x,
@JsonProperty("y") int y
) {
updateCords(x, y);
}
/**
* Updates the coordinates with new x and y values.
*
* @param x The new x coordinate
* @param y The new y coordinate
*/
public void updateCords(int x, int y) {
this.x = x;
this.y = y;
}
/**
* Updates the coordinates using another RoomCords instance.
*
* @param roomCords The RoomCords instance to copy values from
*/
public void updateCords(RoomCords roomCords) {
updateCords(roomCords.getX(), roomCords.getY());
}
/**
* Updates the coordinates only if the new position does not collide with specified colliders.
*
* @param colliders The list of colliders in the room
* @param x The target x coordinate
* @param y The target y coordinate
* @param playerCollider The collider of the player
*/
public void updateCordsWithColliders(List<RoomPart> colliders, int x, int y, RoomPart playerCollider) {
var normalizedPlayerCollider = new RoomPart(
new RoomCords(playerCollider.getStart().getX() + x, playerCollider.getStart().getY() + y),
new RoomCords(playerCollider.getEnd().getX() + x, playerCollider.getEnd().getY() + y)
);
if (colliders.stream().anyMatch(collider -> collider.isOverlapping(normalizedPlayerCollider))) {
return;
}
updateCords(x, y);
}
/**
* Creates and returns a copy of this object.
*
* @return A clone of this instance
*/
@Override
public RoomCords clone() {
try {
return (RoomCords) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError();
}
}
/**
* Calculates the Euclidean distance between this coordinate and another.
*
* @param other The other RoomCords instance
* @return The distance as a double
*/
public double calculateDistance(RoomCords other) {
if (other == null) {
throw new IllegalArgumentException("Cannot calculate distance to null");
}
return Math.hypot(this.x - other.x, this.y - other.y);
}
}

View File

@@ -1,61 +0,0 @@
package cz.jzitnik.common.models.coordinates;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* Represents a rectangular part of a room, defined by start and end coordinates.
*
* @author Jakub Žitník (jzitnik)
*/
@Data
@ToString
public class RoomPart implements Serializable {
private RoomCords start;
private RoomCords end;
/**
* Constructs a RoomPart with specified start and end coordinates.
*
* @param start The start coordinates (top-left)
* @param end The end coordinates (bottom-right)
*/
@JsonCreator
public RoomPart(
@JsonProperty("start") RoomCords start,
@JsonProperty("end") RoomCords end
) {
this.start = start;
this.end = end;
}
/**
* Checks if the given coordinates are within this room part.
*
* @param cords The coordinates to check
* @return true if the coordinates are within this part, false otherwise
*/
public boolean isWithin(RoomCords cords) {
return cords.getX() >= start.getX() &&
cords.getX() <= end.getX() &&
cords.getY() >= start.getY() &&
cords.getY() <= end.getY();
}
/**
* Checks if this RoomPart overlaps with another.
*
* @param other The other RoomPart to check for overlap
* @return true if it overlaps, false otherwise
*/
public boolean isOverlapping(RoomPart other) {
return start.getX() <= other.getEnd().getX() &&
end.getX() >= other.getStart().getX() &&
start.getY() <= other.getEnd().getY() &&
end.getY() >= other.getStart().getY();
}
}

View File

@@ -1,38 +0,0 @@
package cz.jzitnik.common.models.player;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import cz.jzitnik.common.models.coordinates.RoomCords;
import cz.jzitnik.common.models.coordinates.RoomPart;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
* Data required for player creation.
*
* @author Jakub Žitník (jzitnik)
*/
@Getter
public final class PlayerCreation implements Serializable {
@Setter
private int id;
private final RoomCords playerCords;
private final RoomPart collider;
/**
* Constructs a PlayerCreation instance.
*
* @param playerCords The player's initial coordinates
* @param collider The player's collider
*/
@JsonCreator
public PlayerCreation(
@JsonProperty("playerCords") RoomCords playerCords,
@JsonProperty("collider") RoomPart collider
) {
this.playerCords = playerCords;
this.collider = collider;
}
}

View File

@@ -1,11 +0,0 @@
package cz.jzitnik.common.socket;
import java.io.Serializable;
/**
* Base interface for all messages sent over the socket.
*
* @author Jakub Žitník (jzitnik)
*/
public interface SocketMessage extends Serializable {
}

View File

@@ -1,11 +0,0 @@
package cz.jzitnik.common.socket.messages.game;
import cz.jzitnik.common.socket.SocketMessage;
/**
* Message indicating that the game has been won.
*
* @author Jakub Žitník (jzitnik)
*/
public record GameWin() implements SocketMessage {
}

View File

@@ -1,12 +0,0 @@
package cz.jzitnik.common.socket.messages.game;
import cz.jzitnik.common.socket.SocketMessage;
/**
* Message indicating that a player has died.
*
* @param playerId The ID of the player who died.
* @author Jakub Žitník (jzitnik)
*/
public record PlayerDeath(int playerId) implements SocketMessage {
}

View File

@@ -1,12 +0,0 @@
package cz.jzitnik.common.socket.messages.game.connection;
import cz.jzitnik.common.socket.SocketMessage;
/**
* Message sent to request connection to a game.
*
* @param gamePass The password of the game to connect to.
* @author Jakub Žitník (jzitnik)
*/
public record ConnectToAGame(String gamePass) implements SocketMessage {
}

View File

@@ -1,50 +0,0 @@
package cz.jzitnik.common.socket.messages.game.connection;
import cz.jzitnik.common.models.player.PlayerCreation;
import cz.jzitnik.common.socket.SocketMessage;
import java.util.List;
/**
* Response message sent after a connection request to a game.
*
* @param responseType The type of response (SUCCESS or GAME_DOES_NOT_EXIST).
* @param playerCreation Information about the player being created.
* @param existingPlayers List of existing players in the game.
* @author Jakub Žitník (jzitnik)
*/
public record ConnectToAGameResponse(ResponseType responseType, PlayerCreation playerCreation, List<PlayerCreation> existingPlayers) implements SocketMessage {
/**
* Enum representing the possible response types for game connection.
*/
private enum ResponseType {
GAME_DOES_NOT_EXIST,
SUCCESS
}
/**
* Default constructor representing a failed connection (game does not exist).
*/
public ConnectToAGameResponse() {
this(ResponseType.GAME_DOES_NOT_EXIST, null, null);
}
/**
* Constructor for a successful connection.
*
* @param playerCreation Information about the player being created.
* @param existingPlayers List of existing players in the game.
*/
public ConnectToAGameResponse(PlayerCreation playerCreation, List<PlayerCreation> existingPlayers) {
this(ResponseType.SUCCESS, playerCreation, existingPlayers);
}
/**
* Checks if the connection was successful.
*
* @return true if successful, false otherwise.
*/
public boolean success() {
return responseType == ResponseType.SUCCESS;
}
}

View File

@@ -1,11 +0,0 @@
package cz.jzitnik.common.socket.messages.game.creation;
import cz.jzitnik.common.socket.SocketMessage;
/**
* Message sent to request game creation.
*
* @author Jakub Žitník (jzitnik)
*/
public class CreateGame implements SocketMessage {
}

View File

@@ -1,18 +0,0 @@
package cz.jzitnik.common.socket.messages.game.creation;
import cz.jzitnik.common.models.player.PlayerCreation;
import cz.jzitnik.common.socket.SocketMessage;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Response message sent after a game is created.
*
* @author Jakub Žitník (jzitnik)
*/
@Getter
@AllArgsConstructor
public class CreateGameResponse implements SocketMessage {
private final String gamePassword;
private final PlayerCreation ownerPlayer;
}

View File

@@ -1,16 +0,0 @@
package cz.jzitnik.common.socket.messages.items;
import cz.jzitnik.common.socket.SocketMessage;
/**
* Message indicating that an item was taken from a chest.
*
* @param roomId The ID of the room where the chest is located.
* @param id The ID of the item taken.
* @author Jakub Žitník (jzitnik)
*/
public record ItemTookFromChest(
String roomId, // For faster lookup i guess
int id
) implements SocketMessage {
}

View File

@@ -1,18 +0,0 @@
package cz.jzitnik.common.socket.messages.player;
import cz.jzitnik.common.models.coordinates.RoomCords;
import cz.jzitnik.common.socket.SocketMessage;
/**
* Message sent when a player's arrival status in a room changes.
*
* @param id The ID of the player.
* @param playerCords The current coordinates of the player.
* @param playerRotation The current rotation of the player.
* @param arrived Whether the player has arrived or departed.
* @param rerender Whether a rerender is requested.
* @author Jakub Žitník (jzitnik)
*/
public record PlayerArrivalChange(int id, RoomCords playerCords, PlayerRotation playerRotation,
boolean arrived, boolean rerender) implements SocketMessage {
}

View File

@@ -1,12 +0,0 @@
package cz.jzitnik.common.socket.messages.player;
import cz.jzitnik.common.socket.SocketMessage;
/**
* Message indicating that a player has disconnected.
*
* @param playerId The ID of the player who disconnected.
* @author Jakub Žitník (jzitnik)
*/
public record PlayerDisconnected(int playerId) implements SocketMessage {
}

View File

@@ -1,13 +0,0 @@
package cz.jzitnik.common.socket.messages.player;
import cz.jzitnik.common.models.player.PlayerCreation;
import cz.jzitnik.common.socket.SocketMessage;
/**
* Message indicating that a new player has joined the game.
*
* @param playerCreation Information about the player who joined.
* @author Jakub Žitník (jzitnik)
*/
public record PlayerJoined(PlayerCreation playerCreation) implements SocketMessage {
}

View File

@@ -1,14 +0,0 @@
package cz.jzitnik.common.socket.messages.player;
import cz.jzitnik.common.models.coordinates.RoomCords;
import cz.jzitnik.common.socket.SocketMessage;
/**
* Message sent when a player moves.
*
* @param newCords The new coordinates of the player.
* @param playerRotation The rotation of the player.
* @author Jakub Žitník (jzitnik)
*/
public record PlayerMove(RoomCords newCords, PlayerRotation playerRotation) implements SocketMessage {
}

View File

@@ -1,19 +0,0 @@
package cz.jzitnik.common.socket.messages.player;
import cz.jzitnik.common.models.coordinates.RoomCords;
import cz.jzitnik.common.socket.SocketMessage;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* Message sent when another player moves within the same room.
*
* @author Jakub Žitník (jzitnik)
*/
@Getter
@AllArgsConstructor
public class PlayerMovedInUrRoom implements SocketMessage {
private int playerId;
private RoomCords cords;
private PlayerRotation playerRotation;
}

View File

@@ -1,10 +0,0 @@
package cz.jzitnik.common.socket.messages.player;
/**
* Enum representing the possible rotations of a player.
*
* @author Jakub Žitník (jzitnik)
*/
public enum PlayerRotation {
FRONT, BACK, LEFT, RIGHT
}

View File

@@ -1,16 +0,0 @@
package cz.jzitnik.common.socket.messages.room;
import cz.jzitnik.common.models.coordinates.RoomCords;
import cz.jzitnik.common.socket.SocketMessage;
/**
* Message sent to request moving a player to a new room.
*
* @param newRoomId The ID of the room to move to.
* @param oldCords The coordinates in the old room.
* @param newCords The initial coordinates in the new room.
* @author Jakub Žitník (jzitnik)
*/
public record MovePlayerRoom(String newRoomId, RoomCords oldCords, RoomCords newCords) implements SocketMessage {
}

View File

@@ -1,46 +0,0 @@
package cz.jzitnik.common.socket.messages.room;
import cz.jzitnik.common.models.coordinates.RoomCords;
import cz.jzitnik.common.socket.SocketMessage;
import cz.jzitnik.common.socket.messages.player.PlayerRotation;
import java.io.Serializable;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Response message sent after a player moves to a different room.
*
* @param players Set of players currently in the new room.
* @author Jakub Žitník (jzitnik)
*/
public record MovePlayerRoomResponse(Set<Registry> players) implements SocketMessage {
/**
* Represents a registry of a player in a room.
*
* @param id The ID of the player.
* @param cords The coordinates of the player.
* @param playerRotation The rotation of the player.
*/
public record Registry(int id, RoomCords cords, PlayerRotation playerRotation) implements Serializable {}
/**
* Gets a player's registry by their ID.
*
* @param id The ID of the player to find.
* @return An Optional containing the registry if found, otherwise empty.
*/
public Optional<Registry> getById(int id) {
return players.stream().filter(registry -> registry.id == id).findFirst();
}
/**
* Gets the set of IDs of all players in the response.
*
* @return A Set of player IDs.
*/
public Set<Integer> getIds() {
return players.stream().map(Registry::id).collect(Collectors.toSet());
}
}

View File

@@ -1,76 +0,0 @@
package cz.jzitnik.common.models.coordinates;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.*;
class RoomCordsTest {
@Test
void testConstructor() {
RoomCords cords = new RoomCords(10, 20);
assertEquals(10, cords.getX());
assertEquals(20, cords.getY());
}
@Test
void testUpdateCordsWithInts() {
RoomCords cords = new RoomCords(0, 0);
cords.updateCords(5, 10);
assertEquals(5, cords.getX());
assertEquals(10, cords.getY());
}
@Test
void testUpdateCordsWithRoomCords() {
RoomCords cords = new RoomCords(0, 0);
RoomCords newCords = new RoomCords(15, 25);
cords.updateCords(newCords);
assertEquals(15, cords.getX());
assertEquals(25, cords.getY());
}
@Test
void testCalculateDistance() {
RoomCords cords1 = new RoomCords(0, 0);
RoomCords cords2 = new RoomCords(3, 4);
double distance = cords1.calculateDistance(cords2);
assertEquals(5.0, distance, 0.0001);
}
@Test
void testCalculateDistanceToSelf() {
RoomCords cords = new RoomCords(5, 5);
double distance = cords.calculateDistance(cords);
assertEquals(0.0, distance, 0.0001);
}
@Test
void testCalculateDistanceThrowsOnNull() {
RoomCords cords = new RoomCords(0, 0);
assertThrows(IllegalArgumentException.class, () -> cords.calculateDistance(null));
}
@Test
void testClone() {
RoomCords original = new RoomCords(7, 8);
RoomCords cloned = original.clone();
assertEquals(original.getX(), cloned.getX());
assertEquals(original.getY(), cloned.getY());
assertNotSame(original, cloned);
}
@ParameterizedTest
@CsvSource({
"0, 0, 10, 10",
"5, 5, 15, 15",
"-5, -5, 0, 0"
})
void testUpdateCordsWithValues(int x, int y, int expectedX, int expectedY) {
RoomCords cords = new RoomCords(x, y);
assertEquals(x, cords.getX());
assertEquals(y, cords.getY());
}
}

View File

@@ -1,73 +0,0 @@
package cz.jzitnik.common.models.coordinates;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class RoomPartTest {
@Test
void testConstructor() {
RoomCords start = new RoomCords(0, 0);
RoomCords end = new RoomCords(10, 10);
RoomPart roomPart = new RoomPart(start, end);
assertEquals(start, roomPart.getStart());
assertEquals(end, roomPart.getEnd());
}
@Test
void testIsWithinReturnsTrueForPointInside() {
RoomPart roomPart = new RoomPart(new RoomCords(0, 0), new RoomCords(10, 10));
assertTrue(roomPart.isWithin(new RoomCords(5, 5)));
}
@Test
void testIsWithinReturnsTrueForPointOnEdge() {
RoomPart roomPart = new RoomPart(new RoomCords(0, 0), new RoomCords(10, 10));
assertTrue(roomPart.isWithin(new RoomCords(0, 0)));
assertTrue(roomPart.isWithin(new RoomCords(10, 10)));
}
@Test
void testIsWithinReturnsFalseForPointOutside() {
RoomPart roomPart = new RoomPart(new RoomCords(0, 0), new RoomCords(10, 10));
assertFalse(roomPart.isWithin(new RoomCords(15, 5)));
assertFalse(roomPart.isWithin(new RoomCords(5, 15)));
assertFalse(roomPart.isWithin(new RoomCords(-1, 5)));
}
@Test
void testIsOverlappingReturnsTrueForOverlappingParts() {
RoomPart part1 = new RoomPart(new RoomCords(0, 0), new RoomCords(10, 10));
RoomPart part2 = new RoomPart(new RoomCords(5, 5), new RoomCords(15, 15));
assertTrue(part1.isOverlapping(part2));
}
@Test
void testIsOverlappingReturnsTrueForIdenticalParts() {
RoomPart part1 = new RoomPart(new RoomCords(0, 0), new RoomCords(10, 10));
RoomPart part2 = new RoomPart(new RoomCords(0, 0), new RoomCords(10, 10));
assertTrue(part1.isOverlapping(part2));
}
@Test
void testIsOverlappingReturnsFalseForNonOverlappingParts() {
RoomPart part1 = new RoomPart(new RoomCords(0, 0), new RoomCords(10, 10));
RoomPart part2 = new RoomPart(new RoomCords(20, 20), new RoomCords(30, 30));
assertFalse(part1.isOverlapping(part2));
}
@Test
void testIsOverlappingReturnsTrueForAdjacentParts() {
RoomPart part1 = new RoomPart(new RoomCords(0, 0), new RoomCords(10, 10));
RoomPart part2 = new RoomPart(new RoomCords(10, 0), new RoomCords(20, 10));
assertTrue(part1.isOverlapping(part2));
}
@Test
void testIsOverlappingWithOnePartInsideAnother() {
RoomPart part1 = new RoomPart(new RoomCords(0, 0), new RoomCords(20, 20));
RoomPart part2 = new RoomPart(new RoomCords(5, 5), new RoomCords(15, 15));
assertTrue(part1.isOverlapping(part2));
}
}

42
game/.gitignore vendored
View File

@@ -1,42 +0,0 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
.kotlin
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
.idea/FuzzierSettings.xml
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
logs

3
game/.idea/.gitignore generated vendored
View File

@@ -1,3 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/common/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/common/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/game/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/game/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/server/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/server/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>

12
game/.idea/misc.xml generated
View File

@@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_X" default="true" project-jdk-name="openjdk-25" project-jdk-type="JavaSDK" />
</project>

6
game/.idea/vcs.xml generated
View File

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View File

@@ -1,183 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cz.jzitnik</groupId>
<artifactId>game-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>game</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.38</version>
</path>
</annotationProcessorPaths>
<source>25</source>
<target>25</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>cz.jzitnik.client.Main</mainClass>
</transformer>
</transformers>
<shadedArtifactAttached>false</shadedArtifactAttached>
<createDependencyReducedPom>false</createDependencyReducedPom>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>cz.jzitnik.client.Main</mainClass>
<classpathScope>compile</classpathScope>
<skip>false</skip>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>be.0110.repo-releases</id>
<name>0110.be repository</name>
<url>https://mvn.0110.be/releases</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>cz.jzitnik</groupId>
<artifactId>common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.42</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.10.2</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>33.5.0-jre</version>
</dependency>
<dependency>
<groupId>tools.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>tools.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.17</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.5.25</version>
</dependency>
<dependency>
<groupId>com.github.trilarion</groupId>
<artifactId>java-vorbis-support</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>com.googlecode.lanterna</groupId>
<artifactId>lanterna</artifactId>
<version>3.1.3</version>
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>javacv-platform</artifactId>
<version>1.5.12</version>
</dependency>
<dependency>
<groupId>org.bytedeco</groupId>
<artifactId>ffmpeg-platform</artifactId>
<version>7.1.1-1.5.12</version>
</dependency>
<dependency>
<groupId>be.tarsos.dsp</groupId>
<artifactId>core</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>be.tarsos.dsp</groupId>
<artifactId>jvm</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus.bundles</groupId>
<artifactId>tyrus-standalone-client</artifactId>
<version>2.2.2</version>
</dependency>
</dependencies>
</project>

View File

@@ -1,56 +0,0 @@
package cz.jzitnik.client;
import cz.jzitnik.client.annotations.injectors.InjectDependency;
import cz.jzitnik.client.game.setup.GameSetup;
import cz.jzitnik.client.socket.Client;
import cz.jzitnik.client.socket.SocketEventManager;
import cz.jzitnik.client.utils.DependencyManager;
import cz.jzitnik.client.utils.GlobalIOHandlerRepository;
import cz.jzitnik.client.utils.ScheduledTaskManager;
import cz.jzitnik.client.utils.ThreadManager;
import cz.jzitnik.client.utils.events.EventManager;
import jakarta.websocket.DeploymentException;
import org.reflections.Reflections;
import java.io.IOException;
/**
* Main game class responsible for initialization and starting the game loop.
*
* @author Jakub Žitník (jzitnik)
*/
public class Game {
private final DependencyManager dependencyManager = new DependencyManager(new Reflections("cz.jzitnik.client"));
@InjectDependency
private GameSetup gameSetup;
@InjectDependency
private EventManager eventManager;
@InjectDependency
private SocketEventManager socketEventManager;
@InjectDependency
private Cli cli;
@InjectDependency
private ThreadManager threadManager;
@InjectDependency
private GlobalIOHandlerRepository globalIOHandlerRepository;
/**
* Starts the game by injecting dependencies and initializing managers.
*
* @throws IOException If an I/O error occurs
*/
public void start() throws IOException {
dependencyManager.inject(this);
eventManager.start();
socketEventManager.start();
threadManager.startAll();
globalIOHandlerRepository.setup();
gameSetup.setup();
cli.run();
}
}

View File

@@ -1,22 +0,0 @@
package cz.jzitnik.client;
// events/handlers/MouseMoveEventHandler.java
import java.io.IOException;
/**
* Main entry point for the client application.
*
* @author Jakub Žitník (jzitnik)
*/
public class Main {
/**
* Main method that starts the game.
*
* @param args Command line arguments
* @throws IOException If an I/O error occurs
*/
public static void main(String[] args) throws IOException {
new Game().start();
}
}

View File

@@ -1,22 +0,0 @@
package cz.jzitnik.client.annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
/**
* Annotation to mark a class as a configuration component loaded from a YAML file.
*
* @author Jakub Žitník (jzitnik)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Config {
/**
* The YAML file name.
*
* @return file name
*/
String value();
}

View File

@@ -1,24 +0,0 @@
package cz.jzitnik.client.annotations;
import cz.jzitnik.client.utils.events.Event;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
/**
* Annotation to mark a class as an event handler for a specific Event type.
*
* @author Jakub Žitník (jzitnik)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface EventHandler {
/**
* The type of Event this handler handles.
*
* @return Event class
*/
Class<? extends Event> value();
}

View File

@@ -1,24 +0,0 @@
package cz.jzitnik.client.annotations;
import cz.jzitnik.common.socket.SocketMessage;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation to mark a class as a socket event handler for a specific SocketMessage type.
*
* @author Jakub Žitník (jzitnik)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SocketEventHandler {
/**
* The type of SocketMessage this handler handles.
*
* @return SocketMessage class
*/
Class<? extends SocketMessage> value();
}

View File

@@ -1,28 +0,0 @@
package cz.jzitnik.client.annotations.ui;
import com.googlecode.lanterna.input.KeyType;
import java.lang.annotation.*;
/**
* Annotation to mark a method as a keyboard press handler.
*
* @author Jakub Žitník (jzitnik)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Repeatable(KeyboardPressHandlers.class)
public @interface KeyboardPressHandler {
/**
* The key type to handle.
*
* @return key type
*/
KeyType keyType() default KeyType.Character;
/**
* The specific character to handle (if keyType is Character).
*
* @return character
*/
char character() default '\0';
}

View File

@@ -1,12 +0,0 @@
package cz.jzitnik.client.annotations.ui;
/**
* Enum representing types of mouse handlers.
*
* @author Jakub Žitník (jzitnik)
*/
public enum MouseHandlerType {
CLICK,
MOVE,
ELSE,
}

View File

@@ -1,26 +0,0 @@
package cz.jzitnik.client.config;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import cz.jzitnik.client.annotations.Config;
/**
* Configuration for core game logic.
*
* @param itemDropDisappearMinutes Minutes before a dropped item disappears
* @author Jakub Žitník (jzitnik)
*/
@Config("core_logic.yaml")
public record CoreLogic(int itemDropDisappearMinutes) {
/**
* Constructs a CoreLogic configuration instance.
*
* @param itemDropDisappearMinutes Disappear timeout in minutes
*/
@JsonCreator
public CoreLogic(
@JsonProperty("itemDropDisappearMinutes") int itemDropDisappearMinutes
) {
this.itemDropDisappearMinutes = itemDropDisappearMinutes;
}
}

View File

@@ -1,34 +0,0 @@
package cz.jzitnik.client.config;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import cz.jzitnik.client.annotations.Config;
/**
* Configuration for debugging features.
*
* @param renderColliders Whether to render colliders
* @param renderPlayerCollider Whether to render the player's collider
* @param showPlayerCordsLogs Whether to show player coordinate logs
* @author Jakub Žitník (jzitnik)
*/
@Config("debugging.yaml")
public record Debugging(boolean renderColliders, boolean renderPlayerCollider, boolean showPlayerCordsLogs) {
/**
* Constructs a Debugging configuration instance.
*
* @param renderColliders Whether to render colliders
* @param renderPlayerCollider Whether to render the player's collider
* @param showPlayerCordsLogs Whether to show player coordinate logs
*/
@JsonCreator
public Debugging(
@JsonProperty("renderColliders") boolean renderColliders,
@JsonProperty("renderPlayerCollider") boolean renderPlayerCollider,
@JsonProperty("showPlayerCordsLogs") boolean showPlayerCordsLogs
) {
this.renderColliders = renderColliders;
this.renderPlayerCollider = renderPlayerCollider;
this.showPlayerCordsLogs = showPlayerCordsLogs;
}
}

View File

@@ -1,26 +0,0 @@
package cz.jzitnik.client.config;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import cz.jzitnik.client.annotations.Config;
/**
* Configuration for microphone input.
*
* @param volumeThreshold The volume threshold for activation
* @author Jakub Žitník (jzitnik)
*/
@Config("microphone.yaml")
public record MicrophoneConfig(float volumeThreshold) {
/**
* Constructs a MicrophoneConfig instance.
*
* @param volumeThreshold The volume threshold
*/
@JsonCreator
public MicrophoneConfig(
@JsonProperty("volumeThreshold") float volumeThreshold
) {
this.volumeThreshold = volumeThreshold;
}
}

View File

@@ -1,59 +0,0 @@
package cz.jzitnik.client.config;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import cz.jzitnik.client.annotations.Config;
import cz.jzitnik.client.events.handlers.PlayerMoveEventHandler;
/**
* Configuration for player-related settings.
*
* @param playerReach The distance a player can reach
* @param playerMoveDistance The distance a player moves normally
* @param playerMoveDistanceSprinting The distance a player moves while sprinting
* @param sprintKey The key used for sprinting
* @param swingTimeMs Time in milliseconds for a weapon swing
* @param staminaIncreaseRateMs Rate at which stamina increases
* @param staminaDelayMs Delay before stamina starts increasing
* @author Jakub Žitník (jzitnik)
*/
@Config("player.yaml")
public record PlayerConfig(
double playerReach,
int playerMoveDistance,
int playerMoveDistanceSprinting,
PlayerMoveEventHandler.SprintKey sprintKey,
int swingTimeMs,
int staminaIncreaseRateMs,
int staminaDelayMs
) {
/**
* Constructs a PlayerConfig instance.
*
* @param playerReach Player reach
* @param playerMoveDistance Move distance
* @param playerMoveDistanceSprinting Sprint move distance
* @param sprintKey Sprint key
* @param swingTimeMs Swing time
* @param staminaIncreaseRateMs Stamina increase rate
* @param staminaDelayMs Stamina delay
*/
@JsonCreator
public PlayerConfig(
@JsonProperty("playerReach") double playerReach,
@JsonProperty("playerMoveDistance") int playerMoveDistance,
@JsonProperty("playerMoveDistanceSprinting") int playerMoveDistanceSprinting,
@JsonProperty("sprintKey") PlayerMoveEventHandler.SprintKey sprintKey,
@JsonProperty("swingTimeMs") int swingTimeMs,
@JsonProperty("staminaIncreaseRateMs") int staminaIncreaseRateMs,
@JsonProperty("staminaDelayMs") int staminaDelayMs
) {
this.playerReach = playerReach;
this.playerMoveDistance = playerMoveDistance;
this.playerMoveDistanceSprinting = playerMoveDistanceSprinting;
this.sprintKey = sprintKey;
this.swingTimeMs = swingTimeMs;
this.staminaIncreaseRateMs = staminaIncreaseRateMs;
this.staminaDelayMs = staminaDelayMs;
}
}

View File

@@ -1,30 +0,0 @@
package cz.jzitnik.client.config;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import cz.jzitnik.client.annotations.Config;
/**
* Configuration for thread pool sizes.
*
* @param eventThreadCount Number of threads for events
* @param taskThreadCount Number of threads for tasks
* @author Jakub Žitník (jzitnik)
*/
@Config("threads.yaml")
public record ThreadPoolConfig(int eventThreadCount, int taskThreadCount) {
/**
* Constructs a ThreadPoolConfig instance.
*
* @param eventThreadCount Event thread count
* @param taskThreadCount Task thread count
*/
@JsonCreator
public ThreadPoolConfig(
@JsonProperty("eventThreadCount") int eventThreadCount,
@JsonProperty("taskThreadCount") int taskThreadCount
) {
this.eventThreadCount = eventThreadCount;
this.taskThreadCount = taskThreadCount;
}
}

View File

@@ -1,12 +0,0 @@
package cz.jzitnik.client.events;
import cz.jzitnik.client.game.objects.DroppedItem;
import cz.jzitnik.client.utils.events.Event;
/**
* Event triggered when a dropped item in the game world needs to be rerendered.
*
* @param droppedItem the dropped item to rerender
*/
public record DroppedItemRerender(DroppedItem droppedItem) implements Event {
}

View File

@@ -1,11 +0,0 @@
package cz.jzitnik.client.events;
import cz.jzitnik.client.utils.events.Event;
/**
* Event indicating that the application should exit.
*
* @author Jakub Žitník (jzitnik)
*/
public class ExitEvent implements Event {
}

View File

@@ -1,9 +0,0 @@
package cz.jzitnik.client.events;
import cz.jzitnik.client.utils.events.Event;
/**
* Event triggered when the entire screen needs to be fully redrawn.
*/
public class FullRedrawEvent implements Event {
}

View File

@@ -1,9 +0,0 @@
package cz.jzitnik.client.events;
import cz.jzitnik.client.utils.events.Event;
/**
* Event triggered when the player's inventory display needs to be rerendered.
*/
public class InventoryRerender implements Event {
}

View File

@@ -1,9 +0,0 @@
package cz.jzitnik.client.events;
import cz.jzitnik.client.utils.events.Event;
/**
* Event triggered when the player stats display needs to be rerendered.
*/
public class RenderStats implements Event {
}

View File

@@ -1,12 +0,0 @@
package cz.jzitnik.client.events;
import cz.jzitnik.client.events.handlers.FullRoomDrawHandler;
import cz.jzitnik.client.utils.events.Event;
/**
* Event triggered when the player changes to a different room.
*
* @param door the door position from which the player entered the new room
*/
public record RoomChangeEvent(FullRoomDrawHandler.DoorPosition door) implements Event {
}

View File

@@ -1,12 +0,0 @@
package cz.jzitnik.client.events;
import cz.jzitnik.client.utils.events.Event;
import cz.jzitnik.common.socket.SocketMessage;
/**
* Event triggered when a socket message needs to be sent to the server.
*
* @param message the socket message to send
*/
public record SendSocketMessageEvent(SocketMessage message) implements Event {
}

View File

@@ -1,11 +0,0 @@
package cz.jzitnik.client.events;
import cz.jzitnik.client.utils.events.Event;
/**
* Event triggered when the terminal window is too small to render the game.
*
* @author Jakub Žitník (jzitnik)
*/
public class TerminalTooSmallEvent implements Event {
}

View File

@@ -1,325 +0,0 @@
package cz.jzitnik.client.events.handlers;
import com.googlecode.lanterna.TerminalPosition;
import com.googlecode.lanterna.TerminalSize;
import com.googlecode.lanterna.TextColor;
import cz.jzitnik.client.annotations.EventHandler;
import cz.jzitnik.client.annotations.injectors.InjectDependency;
import cz.jzitnik.client.annotations.injectors.InjectState;
import cz.jzitnik.client.events.RerenderScreen;
import cz.jzitnik.client.game.GameState;
import cz.jzitnik.client.game.dialog.Dialog;
import cz.jzitnik.client.game.dialog.OnEnd;
import cz.jzitnik.client.states.DialogState;
import cz.jzitnik.client.states.ScreenBuffer;
import cz.jzitnik.client.states.TerminalState;
import cz.jzitnik.client.ui.pixels.AlphaPixel;
import cz.jzitnik.client.ui.pixels.ColoredPixel;
import cz.jzitnik.client.ui.pixels.Empty;
import cz.jzitnik.client.utils.DependencyManager;
import cz.jzitnik.client.utils.TextRenderer;
import cz.jzitnik.client.utils.events.AbstractEventHandler;
import cz.jzitnik.client.utils.events.EventManager;
import lombok.extern.slf4j.Slf4j;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
/**
* Handler for the Dialog event.
*
* @author Jakub Žitník (jzitnik)
*/
@Slf4j
@EventHandler(Dialog.class)
public class DialogEventHandler extends AbstractEventHandler<Dialog> {
@InjectState
private DialogState dialogState;
@InjectState
private TerminalState terminalState;
@InjectState
private ScreenBuffer screenBuffer;
@InjectState
private GameState gameState;
@InjectDependency
private EventManager eventManager;
@InjectDependency
private TextRenderer textRenderer;
@InjectDependency
private DependencyManager dependencyManager;
private static final int WIDTH = 350;
private static final int MARGIN_BOTTOM = 15;
/** Padding for the dialog box. */
public static final int PADDING = 7;
private static final int BUTTON_TEXT_PADDING = 4;
private static final int QUESTION_ACTIONS_GAP = 10;
/** Height of a button in the dialog. */
public static final int BUTTON_HEIGHT = 15;
/** Padding for buttons in the dialog. */
public static final int BUTTON_PADDING = 5;
private static final float FONT_SIZE = 15f;
/**
* Calculates the total height required for buttons in a dialog.
*
* @param dialog The dialog
* @param gameState Current game state
* @return Calculated height
*/
public static int calculateButtonHeight(Dialog dialog, GameState gameState) {
if (dialog.getOnEnd() instanceof OnEnd.AskQuestion askQuestion) {
int count = askQuestion.answers(gameState).length;
return count * BUTTON_HEIGHT + Math.max(0, count - 1) * BUTTON_PADDING;
}
return 0;
}
/**
* Calculates the starting Y coordinate for buttons.
*
* @param textRenderer The text renderer
* @param dialog The dialog
* @return Starting Y coordinate
*/
public static int getYStartButtons(TextRenderer textRenderer, Dialog dialog) {
var textSize = textRenderer.measureText(
dialog.getText(),
WIDTH - PADDING * 2,
FONT_SIZE
);
return PADDING + textSize.height + BUTTON_PADDING;
}
/**
* Calculates the overall size of the dialog box.
*
* @param textRenderer The text renderer
* @param dialog The dialog
* @param gameState Current game state
* @return The terminal size
*/
public static TerminalSize getSize(TextRenderer textRenderer, Dialog dialog, GameState gameState) {
var textSize = textRenderer.measureText(
dialog.getText(),
WIDTH - PADDING * 2,
FONT_SIZE
);
int buttonsHeight = 0;
if (dialog.getOnEnd() instanceof OnEnd.AskQuestion) {
buttonsHeight = BUTTON_PADDING + calculateButtonHeight(dialog, gameState);
}
return new TerminalSize(
300,
PADDING + textSize.height + buttonsHeight + PADDING
);
}
/**
* Calculates the starting terminal position for the dialog box.
*
* @param terminalSize Current terminal size
* @param size Size of the dialog box
* @return Starting position
*/
public static TerminalPosition getStart(TerminalSize terminalSize, TerminalSize size) {
int startY = terminalSize.getRows() * 2 - MARGIN_BOTTOM - size.getRows();
int startX = (terminalSize.getColumns() / 2) - (size.getColumns() / 2);
return new TerminalPosition(startX, startY);
}
/**
* Handles the Dialog event by rendering it with typing animation.
*
* @param event The Dialog event
*/
@Override
public void handle(Dialog event) {
boolean onlyLast = dialogState.getCurrentDialog() == event;
dialogState.setCurrentDialog(event);
TerminalSize terminalSize = terminalState.getTerminalScreen().getTerminalSize();
var overrideBuffer = screenBuffer.getGlobalOverrideBuffer();
var size = getSize(textRenderer, event, gameState);
var start = getStart(terminalSize, size);
var animation = textRenderer.renderTypingAnimation(
event.getText(),
size.getColumns() - PADDING * 2,
size.getRows() - PADDING * 2,
Color.WHITE,
FONT_SIZE
);
var textSize = textRenderer.measureText(
event.getText(),
size.getColumns() - PADDING * 2,
FONT_SIZE
);
OnEnd onEnd = event.getOnEnd();
List<AlphaPixel[][]> answersBuf = new ArrayList<>();
OnEnd.AskQuestion askQuestion = null;
if (onEnd instanceof OnEnd.AskQuestion aq) {
askQuestion = aq;
for (OnEnd.AskQuestion.Answer answer : aq.answers(gameState)) {
answersBuf.add(
textRenderer.renderText(
answer.answer(),
size.getColumns() - PADDING * 2,
BUTTON_HEIGHT,
Color.BLACK,
FONT_SIZE,
false
)
);
}
}
dialogState.setRenderInProgress(true);
try {
for (int i = onlyLast ? animation.length : 0; i <= animation.length; i++) {
var buf = animation[Math.min(i, animation.length - 1)];
for (int y = 0; y < size.getRows(); y++) {
for (int x = 0; x < size.getColumns(); x++) {
var textPixel = buf[
Math.min(Math.max(0, y - PADDING), buf.length - 1)
][
Math.min(Math.max(0, x - PADDING), buf[0].length - 1)
];
if (textPixel instanceof Empty
|| y < PADDING
|| x < PADDING
|| x >= size.getColumns() - PADDING
|| y >= size.getRows() - PADDING) {
if (i == animation.length
&& askQuestion != null
&& y - 2 > textSize.height + QUESTION_ACTIONS_GAP) {
var answers = askQuestion.answers(gameState);
int buttonsY = y - textSize.height - QUESTION_ACTIONS_GAP - 2;
int buttonIndex = buttonsY / (BUTTON_HEIGHT + BUTTON_PADDING);
int rest = buttonsY % (BUTTON_HEIGHT + BUTTON_PADDING);
if (buttonIndex < answers.length
&& rest < BUTTON_HEIGHT
&& x >= PADDING
&& x < size.getColumns() - PADDING) {
int localY = rest - BUTTON_TEXT_PADDING;
int localX = x - PADDING - BUTTON_TEXT_PADDING;
var buttonBuf = answersBuf.get(buttonIndex);
var buttonTextPixel = buttonBuf[
Math.min(Math.max(0, localY), buttonBuf.length - 1)
][
Math.min(Math.max(0, localX), buttonBuf[0].length - 1)
];
if (buttonTextPixel instanceof Empty
|| localY < 0
|| localX < 0
|| localY >= buttonBuf.length
|| localX >= buttonBuf[0].length) {
overrideBuffer[start.getRow() + y][start.getColumn() + x] =
new ColoredPixel(
new TextColor.RGB(255, 255, 255),
dialogState.getHoveredButtonIndex() == buttonIndex ? 0.8f : 0.6f
);
} else {
overrideBuffer[start.getRow() + y][start.getColumn() + x] =
buttonTextPixel;
}
continue;
}
}
overrideBuffer[start.getRow() + y][start.getColumn() + x] =
new ColoredPixel(new TextColor.RGB(0, 0, 0), 0.6f);
continue;
}
overrideBuffer[start.getRow() + y][start.getColumn() + x] = textPixel;
}
}
eventManager.emitEvent(
new RerenderScreen(
new RerenderScreen.ScreenPart(
start,
new TerminalPosition(
start.getColumn() + size.getColumns(),
start.getRow() + size.getRows()
)
)
)
);
Thread.sleep(1000 / event.getTypingSpeed());
}
dialogState.setRenderInProgress(false);
next(onEnd, start, size);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private void next(OnEnd onEnd, TerminalPosition start, TerminalSize size) throws InterruptedException {
Thread.sleep(1000);
if (onEnd instanceof OnEnd.Continue(Dialog nextDialog)) {
clear(start, size);
eventManager.emitEvent(nextDialog);
} else if (onEnd instanceof OnEnd.RunCode runCode) {
Runnable runnable = runCode.getRunnable();
dependencyManager.inject(runnable);
runnable.run();
next(runCode.getOnEnd(), start, size);
} else if (onEnd instanceof OnEnd.End) {
clear(start, size);
dialogState.setCurrentDialog(null);
eventManager.emitEvent(
new RerenderScreen(
new RerenderScreen.ScreenPart(
start,
new TerminalPosition(
start.getColumn() + size.getColumns(),
start.getRow() + size.getRows()
)
)
)
);
}
}
private void clear(TerminalPosition start, TerminalSize size) {
for (int y = start.getRow(); y < start.getRow() + size.getRows(); y++) {
for (int x = start.getColumn(); x < start.getColumn() + size.getColumns(); x++) {
screenBuffer.getGlobalOverrideBuffer()[y][x] = new Empty();
}
}
}
}

View File

@@ -1,45 +0,0 @@
package cz.jzitnik.client.events.handlers;
import cz.jzitnik.client.annotations.EventHandler;
import cz.jzitnik.client.annotations.injectors.InjectDependency;
import cz.jzitnik.client.annotations.injectors.InjectState;
import cz.jzitnik.client.events.ExitEvent;
import cz.jzitnik.client.states.RunningState;
import cz.jzitnik.client.utils.ScheduledTaskManager;
import cz.jzitnik.client.utils.ThreadManager;
import cz.jzitnik.client.utils.events.AbstractEventHandler;
import cz.jzitnik.client.utils.roomtasks.RoomTaskScheduler;
/**
* Handler for the ExitEvent.
*
* @author Jakub Žitník (jzitnik)
*/
@EventHandler(ExitEvent.class)
public class ExitEventHandler extends AbstractEventHandler<ExitEvent> {
@InjectDependency
private ThreadManager threadManager;
@InjectState
private RunningState runningState;
@InjectDependency
private RoomTaskScheduler roomTaskScheduler;
@InjectDependency
private ScheduledTaskManager scheduledTaskManager;
/**
* Handles the ExitEvent by shutting down all managers and setting the running state to false.
*
* @param event The ExitEvent
*/
@Override
public void handle(ExitEvent event) {
threadManager.shutdownAll();
scheduledTaskManager.shutdown();
roomTaskScheduler.finalShutdown();
runningState.setRunning(false);
//System.exit(0); // Pls don't blame me
}
}

View File

@@ -1,42 +0,0 @@
package cz.jzitnik.client.events.handlers;
import com.googlecode.lanterna.screen.Screen;
import cz.jzitnik.client.annotations.EventHandler;
import cz.jzitnik.client.annotations.injectors.InjectDependency;
import cz.jzitnik.client.annotations.injectors.InjectState;
import cz.jzitnik.client.events.FullRedrawEvent;
import cz.jzitnik.client.events.FullRoomDraw;
import cz.jzitnik.client.states.TerminalState;
import cz.jzitnik.client.utils.events.AbstractEventHandler;
import cz.jzitnik.client.utils.events.EventManager;
import java.io.IOException;
/**
* Handler for the FullRedrawEvent.
*
* @author Jakub Žitník (jzitnik)
*/
@EventHandler(FullRedrawEvent.class)
public class FullRedrawEventHandler extends AbstractEventHandler<FullRedrawEvent> {
@InjectDependency
private EventManager eventManager;
@InjectState
private TerminalState terminalState;
/**
* Handles the FullRedrawEvent by clearing the terminal and emitting a FullRoomDraw event.
*
* @param event The FullRedrawEvent
*/
@Override
public void handle(FullRedrawEvent event) {
terminalState.getTerminalScreen().clear();
try {
terminalState.getTerminalScreen().refresh(Screen.RefreshType.COMPLETE);
} catch (IOException _) {
}
eventManager.emitEvent(new FullRoomDraw(true));
}
}

View File

@@ -1,38 +0,0 @@
package cz.jzitnik.client.events.handlers;
import cz.jzitnik.client.annotations.EventHandler;
import cz.jzitnik.client.annotations.injectors.InjectDependency;
import cz.jzitnik.client.annotations.injectors.InjectState;
import cz.jzitnik.client.events.KeyboardPressEvent;
import cz.jzitnik.client.game.GameState;
import cz.jzitnik.client.utils.GlobalIOHandlerRepository;
import cz.jzitnik.client.utils.events.AbstractEventHandler;
/**
* Handler for the KeyboardPressEvent.
*
* @author Jakub Žitník (jzitnik)
*/
@EventHandler(KeyboardPressEvent.class)
public class KeyboardPressEventHandler extends AbstractEventHandler<KeyboardPressEvent> {
@InjectState
private GameState gameState;
@InjectDependency
private GlobalIOHandlerRepository globalIOHandlerRepository;
/**
* Handles the KeyboardPressEvent by delegating to the current screen or the global repository.
*
* @param event The KeyboardPressEvent
*/
@Override
public void handle(KeyboardPressEvent event) {
if (gameState.getScreen() != null) {
gameState.getScreen().handleKeyboardAction(event);
return;
}
globalIOHandlerRepository.keyboard(event);
}
}

View File

@@ -1,91 +0,0 @@
package cz.jzitnik.client.events.handlers;
import cz.jzitnik.client.annotations.EventHandler;
import cz.jzitnik.client.annotations.injectors.InjectDependency;
import cz.jzitnik.client.annotations.injectors.InjectState;
import cz.jzitnik.client.events.RoomChangeEvent;
import cz.jzitnik.client.events.SendSocketMessageEvent;
import cz.jzitnik.client.game.GameRoom;
import cz.jzitnik.client.game.GameState;
import cz.jzitnik.client.game.Requirement;
import cz.jzitnik.common.models.coordinates.RoomCords;
import cz.jzitnik.client.utils.events.AbstractEventHandler;
import cz.jzitnik.client.utils.events.EventManager;
import cz.jzitnik.client.utils.roomtasks.RoomTaskScheduler;
import cz.jzitnik.common.socket.messages.game.GameWin;
import cz.jzitnik.common.socket.messages.room.MovePlayerRoom;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Handler for the RoomChangeEvent.
*
* @author Jakub Žitník (jzitnik)
*/
@Slf4j
@EventHandler(RoomChangeEvent.class)
public class RoomChangeEventHandler extends AbstractEventHandler<RoomChangeEvent> {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
@InjectState
private GameState gameState;
@InjectDependency
private EventManager eventManager;
@InjectDependency
private RoomTaskScheduler roomTaskScheduler;
/**
* Handles the RoomChangeEvent by changing the current room and moving the player.
*
* @param event The RoomChangeEvent
*/
@Override
public void handle(RoomChangeEvent event) {
RoomCords playerCords = gameState.getPlayer().getPlayerCords();
RoomCords oldCords = playerCords.clone();
GameRoom currentRoom = gameState.getCurrentRoom();
GameRoom newRoom = switch (event.door()) {
case LEFT -> currentRoom.getLeft();
case RIGHT -> currentRoom.getRight();
case TOP -> currentRoom.getUp();
case BOTTOM -> currentRoom.getDown();
};
if (newRoom == null) {
return;
}
if (newRoom.getRequirement() != null) {
Requirement requirement = newRoom.getRequirement();
String itemType = requirement.itemType();
if (Arrays.stream(gameState.getPlayer().getInventory()).noneMatch(item -> {
if (item == null) {
return false;
}
return item.getType().getItemType().getSimpleName().equals(itemType);
})) {
return;
}
}
switch (event.door()) {
case LEFT -> playerCords.updateCords(155, playerCords.getY());
case RIGHT -> playerCords.updateCords(30, playerCords.getY());
case TOP -> playerCords.updateCords(playerCords.getX(), 110);
case BOTTOM -> playerCords.updateCords(playerCords.getX(), 10);
}
eventManager.emitEvent(new SendSocketMessageEvent(new MovePlayerRoom(newRoom.getId(), oldCords, playerCords)));
gameState.setCurrentRoom(newRoom);
if (newRoom.isEnd()) {
eventManager.emitEvent(new SendSocketMessageEvent(new GameWin()));
} else {
scheduler.schedule(() -> roomTaskScheduler.setupNewSchedulers(newRoom), 200, TimeUnit.MILLISECONDS);
}
}
}

View File

@@ -1,34 +0,0 @@
package cz.jzitnik.client.events.handlers;
import cz.jzitnik.client.annotations.EventHandler;
import cz.jzitnik.client.annotations.injectors.InjectDependency;
import cz.jzitnik.client.events.SendSocketMessageEvent;
import cz.jzitnik.client.socket.Client;
import cz.jzitnik.client.utils.events.AbstractEventHandler;
import java.io.IOException;
/**
* Handler for the SendSocketMessageEvent.
*
* @author Jakub Žitník (jzitnik)
*/
@EventHandler(SendSocketMessageEvent.class)
public class SendSocketMessageEventHandler extends AbstractEventHandler<SendSocketMessageEvent> {
@InjectDependency
private Client client;
/**
* Handles the SendSocketMessageEvent by sending the message through the client.
*
* @param event The SendSocketMessageEvent
*/
@Override
public void handle(SendSocketMessageEvent event) {
try {
client.send(event.message());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -1,13 +0,0 @@
package cz.jzitnik.client.game;
import com.googlecode.lanterna.TextColor;
/**
* Global game constants.
*
* @author Jakub Žitník (jzitnik)
*/
public class Constants {
/** The default background color for the game. */
public static final TextColor BACKGROUND_COLOR = new TextColor.RGB(4, 4, 16);
}

View File

@@ -1,27 +0,0 @@
package cz.jzitnik.client.game;
import cz.jzitnik.common.models.coordinates.RoomCords;
import java.awt.image.BufferedImage;
/**
* Interface representing a player-like entity in the game.
*
* @author Jakub Žitník (jzitnik)
*/
public interface GamePlayer {
/**
* Gets the player's coordinates.
*
* @return RoomCords instance
*/
RoomCords getPlayerCords();
/**
* Gets the player's current texture.
*
* @param resourceManager The resource manager to load texture
* @return BufferedImage texture
*/
BufferedImage getTexture(ResourceManager resourceManager);
}

View File

@@ -1,128 +0,0 @@
package cz.jzitnik.client.game;
import com.fasterxml.jackson.annotation.*;
import cz.jzitnik.client.game.mobs.Mob;
import cz.jzitnik.client.game.objects.DroppedItem;
import cz.jzitnik.client.game.objects.GameObject;
import cz.jzitnik.client.ui.pixels.Empty;
import cz.jzitnik.client.ui.pixels.Pixel;
import cz.jzitnik.common.models.coordinates.RoomPart;
import lombok.Getter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Represents a room in the game.
*
* @author Jakub Žitník (jzitnik)
*/
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id"
)
@Getter
public class GameRoom {
private final String id;
@JsonIgnore
private final Pixel[][] overrideBuffer;
@JsonIgnore
private final ResourceManager.Resource texture;
@JsonIgnore
private final List<GameObject> objects = new ArrayList<>();
@JsonIgnore
private final List<Mob> mobs = new ArrayList<>();
@JsonIgnore
private final Set<DroppedItem> droppedItems = new HashSet<>();
@JsonIgnore
private final List<RoomPart> colliders = new ArrayList<>();
@JsonProperty("requirement")
private Requirement requirement;
@JsonProperty("end")
private boolean end;
private GameRoom left;
private GameRoom right;
private GameRoom up;
private GameRoom down;
/**
* Constructs a GameRoom.
*
* @param id Room ID
* @param objects List of objects in the room
* @param colliders List of colliders
* @param mobs List of mobs
* @param texture Texture resource
*/
@JsonCreator
public GameRoom(
@JsonProperty("id") String id,
@JsonProperty("objects") List<GameObject> objects,
@JsonProperty("colliders") List<RoomPart> colliders,
@JsonProperty("mobs") List<Mob> mobs,
@JsonProperty("texture") ResourceManager.Resource texture
) {
this.id = id;
this.texture = texture;
if (objects != null) this.objects.addAll(objects);
if (colliders != null) this.colliders.addAll(colliders);
if (mobs != null) this.mobs.addAll(mobs);
int height = 225;
int width = 225 * 2;
Pixel[][] overrideBuffer = new Pixel[height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
overrideBuffer[y][x] = new Empty();
}
}
this.overrideBuffer = overrideBuffer;
}
/**
* Sets the room to the west (left).
*
* @param west West room
*/
@JsonSetter("west")
public void setWest(GameRoom west) {
if (west != null) this.left = west;
}
/**
* Sets the room to the east (right).
*
* @param east East room
*/
@JsonSetter("east")
public void setEast(GameRoom east) {
if (east != null) this.right = east;
}
/**
* Sets the room to the north (up).
*
* @param north North room
*/
@JsonSetter("north")
public void setNorth(GameRoom north) {
if (north != null) this.up = north;
}
/**
* Sets the room to the south (down).
*
* @param south South room
*/
@JsonSetter("south")
public void setSouth(GameRoom south) {
if (south != null) this.down = south;
}
}

View File

@@ -1,74 +0,0 @@
package cz.jzitnik.client.game;
import cz.jzitnik.client.annotations.State;
import cz.jzitnik.client.game.objects.Interactable;
import cz.jzitnik.client.screens.Screen;
import cz.jzitnik.client.utils.DependencyManager;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
/**
* Holds the current state of the game.
*
* @author Jakub Žitník (jzitnik)
*/
@RequiredArgsConstructor
@State
public class GameState {
private final DependencyManager dependencyManager; // Maybe transient in the future
@Getter
@Setter
private GameRoom currentRoom;
@Getter
@Setter
private List<GameRoom> allRooms;
@Getter
@Setter
private Player player;
private final List<OtherPlayer> otherPlayers = new ArrayList<>();
/**
* Gets a list of visible other players.
*
* @return List of visible other players
*/
public List<OtherPlayer> getOtherPlayers() {
return otherPlayers.stream().filter(OtherPlayer::isVisible).toList();
}
/**
* Gets a list of all other players.
*
* @return List of all other players
*/
public List<OtherPlayer> getAllOtherPlayers() {
return otherPlayers;
}
@Getter
@Setter
private Interactable interacting;
@Getter
private Screen screen;
/**
* Sets the current screen and injects its dependencies.
*
* @param screen The screen to set
*/
public void setScreen(Screen screen) {
if (screen != null) {
dependencyManager.inject(screen);
}
this.screen = screen;
}
}

View File

@@ -1,55 +0,0 @@
package cz.jzitnik.client.game;
import cz.jzitnik.client.game.mobs.HittableMob;
import cz.jzitnik.common.models.coordinates.RoomCords;
import cz.jzitnik.common.models.player.PlayerCreation;
import cz.jzitnik.common.socket.messages.player.PlayerRotation;
import lombok.Getter;
import lombok.Setter;
import java.awt.image.BufferedImage;
/**
* Represents another player connected to the same game.
*
* @author Jakub Žitník (jzitnik)
*/
@Getter
public class OtherPlayer implements GamePlayer {
private final int id;
private boolean hitAnimationOn = false;
private final RoomCords playerCords;
@Setter
private PlayerRotation playerRotation = PlayerRotation.FRONT;
@Setter
private boolean visible;
/**
* Constructs an OtherPlayer.
*
* @param playerCreation Player creation data
*/
public OtherPlayer(PlayerCreation playerCreation) {
this.id = playerCreation.getId();
this.playerCords = playerCreation.getPlayerCords();
}
/**
* {@inheritDoc}
*/
@Override
public BufferedImage getTexture(ResourceManager resourceManager) {
BufferedImage resource = resourceManager.getResource(switch (playerRotation) {
case FRONT -> ResourceManager.Resource.PLAYER_FRONT;
case BACK -> ResourceManager.Resource.PLAYER_BACK;
case LEFT -> ResourceManager.Resource.PLAYER_LEFT;
case RIGHT -> ResourceManager.Resource.PLAYER_RIGHT;
});
if (hitAnimationOn) {
return HittableMob.applyRedFactor(resource);
}
return resource;
}
}

View File

@@ -1,24 +0,0 @@
package cz.jzitnik.client.game;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Represents a requirement (e.g. an item) needed to enter a room.
*
* @param itemType The type of item required
* @author Jakub Žitník (jzitnik)
*/
public record Requirement(String itemType) {
/**
* Constructs a Requirement.
*
* @param itemType The type of item required
*/
@JsonCreator
public Requirement(
@JsonProperty("item") String itemType
) {
this.itemType = itemType;
}
}

View File

@@ -1,36 +0,0 @@
package cz.jzitnik.client.game.dialog;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import cz.jzitnik.client.utils.events.Event;
import lombok.Getter;
/**
* Represents a dialog sequence in the game.
*
* @author Jakub Žitník (jzitnik)
*/
@Getter
public class Dialog implements Event {
/**
* Characters per second
*/
private final int typingSpeed = 10;
private final String text;
private final OnEnd onEnd;
/**
* Constructs a Dialog.
*
* @param text The dialog text
* @param onEnd Action to perform when dialog ends
*/
@JsonCreator
public Dialog(
@JsonProperty("text") String text,
@JsonProperty("onEnd") OnEnd onEnd
) {
this.text = text;
this.onEnd = onEnd;
}
}

View File

@@ -1,182 +0,0 @@
package cz.jzitnik.client.game.dialog;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import cz.jzitnik.client.annotations.injectors.InjectDependency;
import cz.jzitnik.client.annotations.injectors.InjectState;
import cz.jzitnik.client.events.InventoryRerender;
import cz.jzitnik.client.game.GameState;
import cz.jzitnik.client.game.Player;
import cz.jzitnik.client.game.Requirement;
import cz.jzitnik.client.game.ResourceManager;
import cz.jzitnik.client.game.items.GameItem;
import cz.jzitnik.client.game.mobs.HittableMobDrops;
import cz.jzitnik.client.utils.events.EventManager;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import java.util.Arrays;
import java.util.Optional;
/**
* Interface for actions to perform at the end of a dialog.
*
* @author Jakub Žitník (jzitnik)
*/
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type"
)
@JsonSubTypes({
@JsonSubTypes.Type(value = OnEnd.Continue.class, name = "continue"),
@JsonSubTypes.Type(value = OnEnd.AskQuestion.class, name = "ask_question"),
@JsonSubTypes.Type(value = OnEnd.End.class, name = "end"),
@JsonSubTypes.Type(value = OnEnd.GiveItem.class, name = "give_item")
})
public interface OnEnd {
/** Terminal dialog action. */
record End() implements OnEnd {
}
/** Action that gives an item to the player. */
class GiveItem extends RunCode {
/**
* Constructs a GiveItem action.
*
* @param item Item to give
* @param onEnd Next action
*/
@JsonCreator
public GiveItem(
@JsonProperty("item") GameItem item,
@JsonProperty("then") OnEnd onEnd
) {
super(new Run(item), onEnd);
}
/** Internal runnable to give the item. */
@RequiredArgsConstructor
private static class Run implements Runnable {
private final GameItem item;
@InjectState
private GameState gameState;
@InjectDependency
private EventManager eventManager;
@InjectDependency
private ResourceManager resourceManager;
/**
* {@inheritDoc}
*/
@Override
public void run() {
Player player = gameState.getPlayer();
var playerCords = player.getPlayerCords().calculateCenter(player.getTexture(resourceManager));
boolean addedIntoInventory = player.addItem(item);
if (!addedIntoInventory) {
eventManager.emitEvent(HittableMobDrops.dropItem(playerCords.getX(), playerCords.getY(), gameState.getCurrentRoom(), item));
} else {
eventManager.emitEvent(new InventoryRerender());
}
}
}
}
/** Action that runs arbitrary code. */
@Getter
@RequiredArgsConstructor
class RunCode implements OnEnd {
private final Runnable runnable;
private final OnEnd onEnd;
}
/** Action that continues to another dialog. */
record Continue(Dialog nextDialog) implements OnEnd {
/**
* Constructs a Continue action.
*
* @param nextDialog The next dialog
*/
@JsonCreator
public Continue(@JsonProperty("nextDialog") Dialog nextDialog) {
this.nextDialog = nextDialog;
}
}
/** Action that asks the player a question with multiple answers. */
record AskQuestion(Answer[] answers) implements OnEnd {
/**
* Constructs an AskQuestion action.
*
* @param answers Possible answers
*/
@JsonCreator
public AskQuestion(@JsonProperty("answers") Answer[] answers) {
this.answers = answers;
}
/** Represents a single answer to a question. */
public record Answer(
String answer,
Dialog dialog,
Optional<Requirement> requirement
) {
/**
* Constructs an Answer.
*
* @param answer Answer text
* @param dialog Resulting dialog
* @param requirement Requirement to see this answer
*/
@JsonCreator
public Answer(
@JsonProperty("answer") String answer,
@JsonProperty("dialog") Dialog dialog,
@JsonProperty("requirement") Requirement requirement
) {
this(answer, dialog, Optional.ofNullable(requirement));
}
/**
* Checks if the answer is valid for the current state.
*/
private boolean isValid(GameState gameState) {
if (requirement.isPresent()) {
Requirement requirement = requirement().get();
if (requirement.itemType() != null) {
return Arrays.stream(gameState.getPlayer().getInventory()).anyMatch(item -> {
if (item == null) {
return false;
}
return item.getType().getItemType().getSimpleName().equals(requirement.itemType());
});
}
return true;
}
return true;
}
}
/**
* Gets valid answers for the current game state.
*
* @param gameState Current game state
* @return Array of valid answers
*/
public Answer[] answers(GameState gameState) {
return Arrays.stream(answers)
.filter(answer -> answer.isValid(gameState))
.toArray(Answer[]::new);
}
}
}

View File

@@ -1,24 +0,0 @@
package cz.jzitnik.client.game.exceptions;
/**
* Exception thrown when coordinates are invalid.
*
* @author Jakub Žitník (jzitnik)
*/
public class InvalidCoordinatesException extends RuntimeException {
/**
* Constructs an InvalidCoordinatesException with message.
*
* @param message The error message
*/
public InvalidCoordinatesException(String message) {
super(message);
}
/**
* Constructs an InvalidCoordinatesException.
*/
public InvalidCoordinatesException() {
super();
}
}

View File

@@ -1,46 +0,0 @@
package cz.jzitnik.client.game.items;
import com.fasterxml.jackson.annotation.*;
import cz.jzitnik.client.game.ResourceManager;
import cz.jzitnik.client.game.items.types.ItemType;
import cz.jzitnik.client.game.utils.Renderable;
import lombok.Getter;
import java.awt.image.BufferedImage;
/**
* Represents an item in the game.
*
* @author Jakub Žitník (jzitnik)
*/
@Getter
public class GameItem implements Renderable {
private final ItemType<?> type;
@JsonIgnore
private final BufferedImage texture;
private final String name;
private final int id;
/**
* Constructs a GameItem.
*
* @param id Item ID
* @param name Item name
* @param type Item type
* @param resource Texture resource
* @param resourceManager Resource manager
*/
@JsonCreator
public GameItem(
@JsonProperty("id") int id,
@JsonProperty("name") String name,
@JsonProperty("type") ItemType<?> type,
@JsonProperty("texture") ResourceManager.Resource resource,
@JacksonInject ResourceManager resourceManager
) {
this.id = id;
this.name = name;
this.type = type;
this.texture = resourceManager.getResource(resource);
}
}

View File

@@ -1,16 +0,0 @@
package cz.jzitnik.client.game.items.types;
/**
* Represents a beast skin item type.
*
* @author Jakub Žitník (jzitnik)
*/
public class BeastSkin implements ItemType<BeastSkin> {
/**
* {@inheritDoc}
*/
@Override
public Class<BeastSkin> getItemType() {
return BeastSkin.class;
}
}

View File

@@ -1,28 +0,0 @@
package cz.jzitnik.client.game.items.types;
import cz.jzitnik.client.utils.DependencyManager;
import cz.jzitnik.client.utils.StateManager;
/**
* Interface for items that can be interacted with.
*
* @author Jakub Žitník (jzitnik)
*/
public interface InteractableItem {
/**
* Performs interaction with the item.
*
* @param dependencyManager The dependency manager
* @param stateManager The state manager
* @return Result of the interaction
*/
InteractableItemResponse interact(DependencyManager dependencyManager, StateManager stateManager);
/**
* Response types for item interaction.
*/
enum InteractableItemResponse {
/** Clear the item from inventory. */
CLEAR_ITEM,
}
}

View File

@@ -1,32 +0,0 @@
package cz.jzitnik.client.game.items.types;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import cz.jzitnik.client.game.items.types.food.Food;
import cz.jzitnik.client.game.items.types.weapons.Sword;
/**
* Interface representing a type of game item.
*
* @param <T> The class type of the item
* @author Jakub Žitník (jzitnik)
*/
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "name"
)
@JsonSubTypes({
@JsonSubTypes.Type(value = Food.class, name = "food"),
@JsonSubTypes.Type(value = Sword.class, name = "weapon_sword"),
@JsonSubTypes.Type(value = Junk.class, name = "junk"),
@JsonSubTypes.Type(value = Key.class, name = "key"),
@JsonSubTypes.Type(value = BeastSkin.class, name = "beast_skin"),
})
public interface ItemType<T> {
/**
* Gets the class representing this item type.
*
* @return The item type class
*/
Class<T> getItemType();
}

View File

@@ -1,16 +0,0 @@
package cz.jzitnik.client.game.items.types;
/**
* Represents a junk item type.
*
* @author Jakub Žitník (jzitnik)
*/
public class Junk implements ItemType<Junk> {
/**
* {@inheritDoc}
*/
@Override
public Class<Junk> getItemType() {
return Junk.class;
}
}

View File

@@ -1,16 +0,0 @@
package cz.jzitnik.client.game.items.types;
/**
* Represents a key item type.
*
* @author Jakub Žitník (jzitnik)
*/
public class Key implements ItemType<Key> {
/**
* {@inheritDoc}
*/
@Override
public Class<Key> getItemType() {
return Key.class;
}
}

View File

@@ -1,58 +0,0 @@
package cz.jzitnik.client.game.items.types.food;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import cz.jzitnik.client.events.RenderStats;
import cz.jzitnik.client.game.GameState;
import cz.jzitnik.client.game.items.types.InteractableItem;
import cz.jzitnik.client.game.items.types.ItemType;
import cz.jzitnik.client.utils.DependencyManager;
import cz.jzitnik.client.utils.StateManager;
import cz.jzitnik.client.utils.events.EventManager;
/**
* Represents a food item that can be consumed to restore health.
*
* @author Jakub Žitník (jzitnik)
*/
public class Food implements InteractableItem, ItemType<Food> {
private final int addHealth;
/**
* Constructs a Food item with specified health restoration value.
*
* @param addHealth Health to add when consumed
*/
@JsonCreator
public Food(
@JsonProperty("addHealth") int addHealth
) {
this.addHealth = addHealth;
}
/**
* Interacts with the food item (consumes it).
*
* @param dependencyManager The dependency manager
* @param stateManager The state manager
* @return Response indicating the item should be cleared
*/
@Override
public InteractableItemResponse interact(DependencyManager dependencyManager, StateManager stateManager) {
GameState gameState = stateManager.getOrThrow(GameState.class);
EventManager eventManager = dependencyManager.getDependencyOrThrow(EventManager.class);
gameState.getPlayer().addHealth(addHealth);
eventManager.emitEvent(new RenderStats());
return InteractableItemResponse.CLEAR_ITEM;
}
/**
* {@inheritDoc}
*/
@Override
public Class<Food> getItemType() {
return Food.class;
}
}

View File

@@ -1,15 +0,0 @@
package cz.jzitnik.client.game.items.types.interfaces;
/**
* Interface for game items that can deal damage.
*
* @author Jakub Žitník (jzitnik)
*/
public interface WeaponInterface {
/**
* Gets the damage dealt by the weapon.
*
* @return Damage value
*/
int getDamageDeal();
}

View File

@@ -1,23 +0,0 @@
package cz.jzitnik.client.game.items.types.weapons;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Represents a sword weapon.
*
* @author Jakub Žitník (jzitnik)
*/
public class Sword extends Weapon {
/**
* Constructs a Sword with specified damage.
*
* @param dealDamage Damage dealt by the sword
*/
@JsonCreator
public Sword(
@JsonProperty("dealDamage") int dealDamage
) {
super(dealDamage);
}
}

View File

@@ -1,33 +0,0 @@
package cz.jzitnik.client.game.items.types.weapons;
import cz.jzitnik.client.game.items.types.ItemType;
import cz.jzitnik.client.game.items.types.interfaces.WeaponInterface;
import lombok.AllArgsConstructor;
/**
* Base class for all weapon items.
*
* @author Jakub Žitník (jzitnik)
*/
@AllArgsConstructor
public abstract class Weapon implements ItemType<Weapon>, WeaponInterface {
private final int dealDamage;
/**
* {@inheritDoc}
*/
@Override
public final Class<Weapon> getItemType() {
return Weapon.class;
}
/**
* Gets the damage dealt by this weapon.
*
* @return Damage value
*/
@Override
public int getDamageDeal() {
return dealDamage;
}
}

View File

@@ -1,65 +0,0 @@
package cz.jzitnik.client.game.mobs;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import cz.jzitnik.client.annotations.injectors.InjectDependency;
import cz.jzitnik.client.annotations.injectors.InjectState;
import cz.jzitnik.client.game.ResourceManager;
import cz.jzitnik.common.models.coordinates.RoomPart;
import cz.jzitnik.client.game.dialog.Dialog;
import cz.jzitnik.client.game.mobs.tasks.MobRoomTask;
import cz.jzitnik.common.models.coordinates.RoomCords;
import cz.jzitnik.client.states.DialogState;
import cz.jzitnik.client.utils.events.EventManager;
import lombok.extern.slf4j.Slf4j;
/**
* A mob that triggers a dialog when interacted with.
*
* @author Jakub Žitník (jzitnik)
*/
@Slf4j
public class DialogMob extends Mob {
protected Dialog dialog;
/**
* Constructs a DialogMob.
*
* @param texture Texture resource
* @param tasks Tasks
* @param cords Coordinates
* @param collider Collider
* @param dialog Dialog to trigger
* @param resourceManager Resource manager
*/
@JsonCreator
public DialogMob(
@JsonProperty("texture") ResourceManager.Resource texture,
@JsonProperty("tasks") MobRoomTask[] tasks,
@JsonProperty("cords") RoomCords cords,
@JsonProperty("collider") RoomPart collider,
@JsonProperty("dialog") Dialog dialog,
@JacksonInject ResourceManager resourceManager
) {
super(resourceManager.getResource(texture), tasks, cords, collider);
this.dialog = dialog;
}
@InjectDependency
private EventManager eventManager;
@InjectState
private DialogState dialogState;
/**
* {@inheritDoc}
*/
@Override
public void interact() {
log.debug("Interacting with dialog mob!");
if (dialogState.getCurrentDialog() == null) {
eventManager.emitEvent(dialog);
}
}
}

View File

@@ -1,118 +0,0 @@
package cz.jzitnik.client.game.mobs;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import cz.jzitnik.client.annotations.injectors.InjectDependency;
import cz.jzitnik.client.annotations.injectors.InjectState;
import cz.jzitnik.client.events.DroppedItemRerender;
import cz.jzitnik.client.events.InventoryRerender;
import cz.jzitnik.client.game.*;
import cz.jzitnik.client.game.items.GameItem;
import cz.jzitnik.client.game.mobs.tasks.MobRoomTask;
import cz.jzitnik.client.game.objects.DroppedItem;
import cz.jzitnik.common.models.coordinates.RoomPart;
import cz.jzitnik.common.models.coordinates.RoomCords;
import cz.jzitnik.client.utils.events.Event;
import cz.jzitnik.client.utils.events.EventManager;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* A hittable mob that drops items when killed.
*
* @author Jakub Žitník (jzitnik)
*/
public class HittableMobDrops extends HittableMob {
private static final int DROP_ITEM_ON_GROUND_RADIUS = 30;
private final GameItem[] itemsDrops;
@InjectState
private GameState gameState;
@InjectDependency
private EventManager eventManager;
/**
* Constructs a HittableMobDrops instance.
*
* @param texture Texture resource
* @param tasks Tasks
* @param cords Coordinates
* @param collider Collider
* @param health Initial health
* @param itemsDrops Items to drop on death
* @param resourceManager Resource manager
*/
@JsonCreator
public HittableMobDrops(
@JsonProperty("texture") ResourceManager.Resource texture,
@JsonProperty("tasks") MobRoomTask[] tasks,
@JsonProperty("cords") RoomCords cords,
@JsonProperty("collider") RoomPart collider,
@JsonProperty("health") int health,
@JsonProperty("itemsDrops") GameItem[] itemsDrops,
@JacksonInject ResourceManager resourceManager
) {
super(resourceManager.getResource(texture), tasks, cords, collider, health);
this.itemsDrops = itemsDrops == null ? new GameItem[]{} : itemsDrops;
}
/**
* Can be overwritten by an extending class
**/
public void afterKill() {
}
/**
* {@inheritDoc}
*/
@Override
public final void onKilled() {
boolean addedIntoInventory = false;
Player player = gameState.getPlayer();
RoomCords enemyCords = getCords();
BufferedImage enemyTexture = getTexture();
int roomX = enemyCords.getX() + enemyTexture.getWidth() / 2;
int roomY = enemyCords.getY() + enemyTexture.getHeight() / 2;
GameRoom currentRoom = gameState.getCurrentRoom();
List<Event> events = new ArrayList<>();
for (GameItem item : itemsDrops) {
boolean added = player.addItem(item);
if (added) {
if (!addedIntoInventory) {
addedIntoInventory = true;
events.add(new InventoryRerender());
}
} else {
events.add(dropItem(roomX, roomY, currentRoom, item));
}
}
eventManager.emitEvent(events, this::afterKill);
}
/**
* Drops an item at a random position near specified coordinates.
*
* @param x Center X
* @param y Center Y
* @param currentRoom The current room
* @param item The item to drop
* @return A DroppedItemRerender event
*/
public static Event dropItem(int x, int y, GameRoom currentRoom, GameItem item) {
double angle = ThreadLocalRandom.current().nextDouble(0, Math.PI * 2);
double radius = ThreadLocalRandom.current().nextDouble(0, DROP_ITEM_ON_GROUND_RADIUS);
int randomX = x + (int) (Math.cos(angle) * radius);
int randomY = y + (int) (Math.sin(angle) * radius);
RoomCords itemCords = new RoomCords(randomX, randomY);
DroppedItem droppedItem = new DroppedItem(currentRoom, itemCords, item);
currentRoom.getDroppedItems().add(droppedItem);
return new DroppedItemRerender(droppedItem);
}
}

View File

@@ -1,46 +0,0 @@
package cz.jzitnik.client.game.mobs;
import com.fasterxml.jackson.annotation.JacksonInject;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import cz.jzitnik.common.models.coordinates.RoomPart;
import cz.jzitnik.client.game.ResourceManager;
import cz.jzitnik.client.game.mobs.tasks.MobRoomTask;
import cz.jzitnik.common.models.coordinates.RoomCords;
/**
* A hittable mob that does not drop any items when killed.
*
* @author Jakub Žitník (jzitnik)
*/
public class HittableMobNoDrops extends HittableMob {
/**
* Constructs a HittableMobNoDrops instance.
*
* @param texture Texture resource
* @param tasks Tasks
* @param cords Coordinates
* @param collider Collider
* @param health Initial health
* @param resourceManager Resource manager
*/
@JsonCreator
public HittableMobNoDrops(
@JsonProperty("texture") ResourceManager.Resource texture,
@JsonProperty("tasks") MobRoomTask[] tasks,
@JsonProperty("cords") RoomCords cords,
@JsonProperty("collider") RoomPart collider,
@JsonProperty("health") int health,
@JacksonInject ResourceManager resourceManager
) {
super(resourceManager.getResource(texture), tasks, cords, collider, health);
}
/**
* {@inheritDoc}
*/
@Override
public void onKilled() {
}
}

View File

@@ -1,82 +0,0 @@
package cz.jzitnik.client.game.mobs;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import cz.jzitnik.client.annotations.injectors.InjectDependency;
import cz.jzitnik.common.models.coordinates.RoomPart;
import cz.jzitnik.client.game.mobs.tasks.MobRoomTask;
import cz.jzitnik.client.game.utils.Renderable;
import cz.jzitnik.common.models.coordinates.RoomCords;
import cz.jzitnik.client.game.utils.Selectable;
import cz.jzitnik.client.utils.roomtasks.RoomTaskScheduler;
import lombok.Getter;
import lombok.Setter;
import java.awt.image.BufferedImage;
/**
* Abstract base class for all mobs in the game.
*
* @author Jakub Žitník (jzitnik)
*/
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type"
)
@JsonSubTypes({
@JsonSubTypes.Type(value = DialogMob.class, name = "dialog"),
@JsonSubTypes.Type(value = HittableMobDrops.class, name = "hittable_drops"),
@JsonSubTypes.Type(value = HittableMobNoDrops.class, name = "hittable_no_drops")
})
@Getter
public abstract class Mob implements Renderable, Selectable {
@JsonIgnore
protected final BufferedImage texture;
@JsonIgnore
protected MobRoomTask[] tasks;
@JsonIgnore
protected final RoomCords cords;
@JsonIgnore
protected final RoomPart collider;
@InjectDependency
private RoomTaskScheduler roomTaskScheduler;
/**
* Updates the tasks associated with this mob and registers them.
*
* @param tasks The new tasks
*/
protected void updateTasks(MobRoomTask[] tasks) {
var oldTasks = this.tasks;
this.tasks = tasks;
roomTaskScheduler.registerNewMob(this, oldTasks);
}
/**
* Constructs a Mob.
*
* @param texture The mob's texture
* @param tasks Tasks associated with the mob
* @param cords Initial coordinates
* @param collider The mob's collider
*/
public Mob(BufferedImage texture, MobRoomTask[] tasks, RoomCords cords, RoomPart collider) {
this.texture = texture;
this.tasks = tasks == null ? new MobRoomTask[] {} : tasks;
this.cords = cords;
this.collider = collider;
if (tasks != null) {
for (MobRoomTask task : tasks) {
task.setOwner(this);
}
}
}
@Setter
private boolean selected = false;
}

View File

@@ -1,100 +0,0 @@
package cz.jzitnik.client.game.mobs.tasks;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import cz.jzitnik.client.annotations.injectors.InjectConfig;
import cz.jzitnik.client.annotations.injectors.InjectDependency;
import cz.jzitnik.client.annotations.injectors.InjectState;
import cz.jzitnik.client.config.Debugging;
import cz.jzitnik.client.config.MicrophoneConfig;
import cz.jzitnik.client.game.GameState;
import cz.jzitnik.client.game.ResourceManager;
import cz.jzitnik.client.game.mobs.Mob;
import cz.jzitnik.common.models.coordinates.RoomCords;
import cz.jzitnik.client.states.MicrophoneState;
import cz.jzitnik.client.states.ScreenBuffer;
import cz.jzitnik.client.states.TerminalState;
import cz.jzitnik.client.utils.events.EventManager;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import java.util.concurrent.TimeUnit;
/**
* Task that makes a mob follow the player only when they make noise.
*
* @author Jakub Žitník (jzitnik)
*/
public class BlindMobFollowingPlayerTask extends MobRoomTask {
private final Task task;
/**
* Constructs a BlindMobFollowingPlayerTask.
*
* @param speed Mob movement speed
* @param updateRateMs Execution rate in milliseconds
*/
@JsonCreator
public BlindMobFollowingPlayerTask(
@JsonProperty("speed") int speed,
@JsonProperty("updateRateMs") int updateRateMs
) {
Task task = new Task(speed);
super(task, updateRateMs, TimeUnit.MILLISECONDS);
this.task = task;
}
/**
* {@inheritDoc}
*/
@Override
public void setOwner(Mob mob) {
task.setMob(mob);
}
/**
* Internal task runnable logic.
*/
@RequiredArgsConstructor
private static class Task implements Runnable {
@Setter
private Mob mob;
private final int speed;
private RoomCords playerCords;
@InjectState
private GameState gameState;
@InjectDependency
private EventManager eventManager;
@InjectDependency
private ResourceManager resourceManager;
@InjectState
private TerminalState terminalState;
@InjectState
private ScreenBuffer screenBuffer;
@InjectConfig
private Debugging debugging;
@InjectState
private MicrophoneState microphoneState;
@InjectConfig
private MicrophoneConfig microphoneConfig;
/**
* {@inheritDoc}
*/
@Override
public void run() {
if (playerCords == null || (microphoneState.isMicrophoneSetup() && microphoneState.getMicrophoneVolume() > microphoneConfig.volumeThreshold())) {
playerCords = gameState.getPlayer().getPlayerCords().clone();
}
MobFollowingPlayerTask.Task.moveMob(playerCords, mob, gameState, speed, resourceManager, terminalState, screenBuffer, debugging, eventManager);
}
}
}

View File

@@ -1,93 +0,0 @@
package cz.jzitnik.client.game.mobs.tasks;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import cz.jzitnik.client.annotations.injectors.InjectDependency;
import cz.jzitnik.client.annotations.injectors.InjectState;
import cz.jzitnik.client.events.RenderStats;
import cz.jzitnik.client.game.GameState;
import cz.jzitnik.client.game.mobs.Mob;
import cz.jzitnik.common.models.coordinates.RoomCords;
import cz.jzitnik.client.utils.DependencyManager;
import cz.jzitnik.client.utils.events.EventManager;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
/**
* Task that makes a mob attack the player if within reach.
*
* @author Jakub Žitník (jzitnik)
*/
@Slf4j
public class EnemyPlayerAttackingTask extends MobRoomTask {
private final Task task;
/**
* Constructs an EnemyPlayerAttackingTask.
*
* @param updateRateMs Execution rate in milliseconds
* @param reach Attack reach
* @param damage Attack damage
*/
@JsonCreator
public EnemyPlayerAttackingTask(
@JsonProperty("updateRateMs") long updateRateMs,
@JsonProperty("reach") double reach,
@JsonProperty("damage") int damage
) {
Task task = new Task(reach, damage);
super(task, updateRateMs, TimeUnit.MILLISECONDS);
this.task = task;
}
/**
* {@inheritDoc}
*/
@Override
public void setOwner(Mob mob) {
task.setMob(mob);
}
/**
* Internal task runnable logic.
*/
@RequiredArgsConstructor
private static class Task implements Runnable {
private final double reach;
private final int damage;
@Setter
private Mob mob;
@InjectState
private GameState gameState;
@InjectDependency
private EventManager eventManager;
@InjectDependency
private DependencyManager dependencyManager;
/**
* {@inheritDoc}
*/
@Override
public void run() {
RoomCords playerCords = gameState.getPlayer().getPlayerCords();
RoomCords mobCords = mob.getCords();
double distance = playerCords.calculateDistance(mobCords);
if (distance > reach) {
return;
}
boolean isDead = gameState.getPlayer().dealDamage(damage, dependencyManager);
eventManager.emitEvent(new RenderStats());
log.debug("Is dead: {}", isDead);
// TODO: Death screen
}
}
}

View File

@@ -1,43 +0,0 @@
package cz.jzitnik.client.game.mobs.tasks;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import cz.jzitnik.client.game.mobs.Mob;
import cz.jzitnik.client.utils.roomtasks.RoomTask;
import java.util.concurrent.TimeUnit;
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "type"
)
@JsonSubTypes({
@JsonSubTypes.Type(value = BlindMobFollowingPlayerTask.class, name = "blind_following_player"),
@JsonSubTypes.Type(value = MobFollowingPlayerTask.class, name = "following_player"),
@JsonSubTypes.Type(value = EnemyPlayerAttackingTask.class, name = "attacking_player")
})
/**
* Base class for tasks associated with a mob in a room.
*
* @author Jakub Žitník (jzitnik)
*/
public abstract class MobRoomTask extends RoomTask {
/**
* Constructs a MobRoomTask.
*
* @param task Runnable task
* @param rate Execution rate
* @param rateUnit Time unit for rate
*/
public MobRoomTask(Runnable task, long rate, TimeUnit rateUnit) {
super(task, rate, rateUnit);
}
/**
* Sets the owner mob of this task.
*
* @param mob The owner mob
*/
public abstract void setOwner(Mob mob);
}

View File

@@ -1,40 +0,0 @@
package cz.jzitnik.client.game.objects;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import cz.jzitnik.client.game.utils.Renderable;
import cz.jzitnik.common.models.coordinates.RoomCords;
import cz.jzitnik.client.game.utils.Selectable;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import java.awt.image.BufferedImage;
/**
* Abstract base class for all static or interactable objects in a room.
*
* @author Jakub Žitník (jzitnik)
*/
@Getter
@RequiredArgsConstructor
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
property = "objectType"
)
@JsonSubTypes({
@JsonSubTypes.Type(value = Chest.class, name = "chest")
})
public sealed abstract class GameObject implements Renderable, Selectable permits Chest {
@JsonIgnore
private final BufferedImage texture;
@JsonIgnore
private final RoomCords cords;
@JsonIgnore
private final boolean selectable;
@JsonIgnore
@Setter
private boolean selected = false;
}

View File

@@ -1,13 +0,0 @@
package cz.jzitnik.client.game.objects;
/**
* Interface for objects that can be interacted with.
*
* @author Jakub Žitník (jzitnik)
*/
public interface Interactable {
/**
* Performs the interaction logic.
*/
void interact();
}

View File

@@ -1,38 +0,0 @@
package cz.jzitnik.client.game.objects;
import cz.jzitnik.client.events.MouseAction;
/**
* Interface for components that handle UI mouse actions.
*
* @author Jakub Žitník (jzitnik)
*/
public interface UIClickHandler {
/**
* Handles a mouse click action.
*
* @param mouseAction The mouse action
* @return true if the event was handled
*/
boolean handleClick(MouseAction mouseAction);
/**
* Handles a mouse move action.
*
* @param ignoredMouseAction The mouse action
* @return true if the event was handled
*/
default boolean handleMove(MouseAction ignoredMouseAction) {
return false;
}
/**
* Handles other mouse actions.
*
* @param ignoredMouseAction The mouse action
* @return true if the event was handled
*/
default boolean handleElse(MouseAction ignoredMouseAction) {
return false;
}
}

View File

@@ -1,62 +0,0 @@
package cz.jzitnik.client.game.setup;
import cz.jzitnik.client.annotations.Dependency;
import cz.jzitnik.client.annotations.injectors.InjectDependency;
import cz.jzitnik.client.annotations.injectors.InjectState;
import cz.jzitnik.client.events.SendSocketMessageEvent;
import cz.jzitnik.client.game.GameRoom;
import cz.jzitnik.client.game.GameState;
import cz.jzitnik.client.game.Player;
import cz.jzitnik.client.game.ResourceManager;
import cz.jzitnik.client.game.setup.scenes.connect.ServerChoose;
import cz.jzitnik.client.utils.DependencyManager;
import cz.jzitnik.client.utils.events.EventManager;
import cz.jzitnik.common.socket.messages.game.creation.CreateGame;
import lombok.extern.slf4j.Slf4j;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.ObjectReader;
import java.io.IOException;
import java.util.List;
/**
* Manages the initial setup of the game, including rooms and initial screen.
*
* @author Jakub Žitník (jzitnik)
*/
@Slf4j
@Dependency
public class GameSetup {
@InjectState
private GameState gameState;
@InjectDependency
private ResourceManager resourceManager;
@InjectDependency
private ObjectMapper objectMapper;
@InjectDependency
private DependencyManager dependencyManager;
/**
* Sets up the game state.
*
* @throws IOException If an I/O error occurs
*/
public void setup() throws IOException {
gameState.setScreen(new ServerChoose(dependencyManager));
ObjectReader roomsReader = objectMapper.readerFor(
new TypeReference<List<GameRoom>>() {
}
).with(dependencyManager);
List<GameRoom> rooms = roomsReader.readValue(
resourceManager.getResourceAsStream("setup/rooms.yaml")
);
gameState.setCurrentRoom(rooms.getFirst());
gameState.setAllRooms(rooms);
}
}

Some files were not shown because too many files have changed in this diff Show More