diff --git a/common/src/main/java/cz/jzitnik/common/Config.java b/common/src/main/java/cz/jzitnik/common/Config.java index de224e3..94438d1 100644 --- a/common/src/main/java/cz/jzitnik/common/Config.java +++ b/common/src/main/java/cz/jzitnik/common/Config.java @@ -1,5 +1,10 @@ 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; } diff --git a/common/src/main/java/cz/jzitnik/common/models/coordinates/RoomCords.java b/common/src/main/java/cz/jzitnik/common/models/coordinates/RoomCords.java index d55c18d..358c018 100644 --- a/common/src/main/java/cz/jzitnik/common/models/coordinates/RoomCords.java +++ b/common/src/main/java/cz/jzitnik/common/models/coordinates/RoomCords.java @@ -10,6 +10,11 @@ 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 @@ -17,6 +22,12 @@ 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, @@ -24,6 +35,12 @@ public class RoomCords implements Cloneable, Serializable { ); } + /** + * 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, @@ -32,15 +49,34 @@ public class RoomCords implements Cloneable, Serializable { 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 colliders, int x, int y, RoomPart playerCollider) { var normalizedPlayerCollider = new RoomPart( new RoomCords(playerCollider.getStart().getX() + x, playerCollider.getStart().getY() + y), @@ -53,6 +89,11 @@ public class RoomCords implements Cloneable, Serializable { updateCords(x, y); } + /** + * Creates and returns a copy of this object. + * + * @return A clone of this instance + */ @Override public RoomCords clone() { try { diff --git a/common/src/main/java/cz/jzitnik/common/models/coordinates/RoomPart.java b/common/src/main/java/cz/jzitnik/common/models/coordinates/RoomPart.java index 3de05c6..fc45515 100644 --- a/common/src/main/java/cz/jzitnik/common/models/coordinates/RoomPart.java +++ b/common/src/main/java/cz/jzitnik/common/models/coordinates/RoomPart.java @@ -7,12 +7,23 @@ 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, @@ -22,6 +33,12 @@ public class RoomPart implements Serializable { 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() && @@ -30,7 +47,10 @@ public class RoomPart implements Serializable { } /** - * Checks if this GameRoomPart overlaps with another. + * 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() && diff --git a/common/src/main/java/cz/jzitnik/common/models/player/PlayerCreation.java b/common/src/main/java/cz/jzitnik/common/models/player/PlayerCreation.java index a8587ac..20bd2a7 100644 --- a/common/src/main/java/cz/jzitnik/common/models/player/PlayerCreation.java +++ b/common/src/main/java/cz/jzitnik/common/models/player/PlayerCreation.java @@ -9,6 +9,11 @@ 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 @@ -16,6 +21,12 @@ public final class PlayerCreation implements Serializable { 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, diff --git a/common/src/main/java/cz/jzitnik/common/socket/SocketMessage.java b/common/src/main/java/cz/jzitnik/common/socket/SocketMessage.java index 3134c92..8d3a144 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/SocketMessage.java +++ b/common/src/main/java/cz/jzitnik/common/socket/SocketMessage.java @@ -2,5 +2,10 @@ 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 { } diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/Test.java b/common/src/main/java/cz/jzitnik/common/socket/messages/Test.java index 00d3703..c009969 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/Test.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/Test.java @@ -2,5 +2,10 @@ package cz.jzitnik.common.socket.messages; import cz.jzitnik.common.socket.SocketMessage; +/** + * Test message for socket communication. + * + * @author Jakub Žitník (jzitnik) + */ public class Test implements SocketMessage { } diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/game/GameWin.java b/common/src/main/java/cz/jzitnik/common/socket/messages/game/GameWin.java index 5fc55e5..e80f531 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/game/GameWin.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/game/GameWin.java @@ -2,5 +2,10 @@ 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 { } diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/game/PlayerDeath.java b/common/src/main/java/cz/jzitnik/common/socket/messages/game/PlayerDeath.java index eee62c6..d51ef07 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/game/PlayerDeath.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/game/PlayerDeath.java @@ -2,5 +2,11 @@ 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 { } diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/game/connection/ConnectToAGame.java b/common/src/main/java/cz/jzitnik/common/socket/messages/game/connection/ConnectToAGame.java index 72fc1a2..77def16 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/game/connection/ConnectToAGame.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/game/connection/ConnectToAGame.java @@ -2,5 +2,11 @@ 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 { } diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/game/connection/ConnectToAGameResponse.java b/common/src/main/java/cz/jzitnik/common/socket/messages/game/connection/ConnectToAGameResponse.java index da7d74a..19699c5 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/game/connection/ConnectToAGameResponse.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/game/connection/ConnectToAGameResponse.java @@ -5,20 +5,45 @@ 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 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 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; } diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/game/creation/CreateGame.java b/common/src/main/java/cz/jzitnik/common/socket/messages/game/creation/CreateGame.java index ad4a593..bcf73e5 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/game/creation/CreateGame.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/game/creation/CreateGame.java @@ -2,5 +2,10 @@ 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 { } diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/game/creation/CreateGameResponse.java b/common/src/main/java/cz/jzitnik/common/socket/messages/game/creation/CreateGameResponse.java index 732c852..ef1a32e 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/game/creation/CreateGameResponse.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/game/creation/CreateGameResponse.java @@ -5,6 +5,11 @@ 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 { diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/items/ItemTookFromChest.java b/common/src/main/java/cz/jzitnik/common/socket/messages/items/ItemTookFromChest.java index f1b3897..56c1595 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/items/ItemTookFromChest.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/items/ItemTookFromChest.java @@ -2,6 +2,13 @@ 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 diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerArrivalChange.java b/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerArrivalChange.java index d661795..7dd82b6 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerArrivalChange.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerArrivalChange.java @@ -3,6 +3,16 @@ 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 { } diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerDisconnected.java b/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerDisconnected.java index 85fad63..af90d39 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerDisconnected.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerDisconnected.java @@ -2,5 +2,11 @@ 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 { } diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerJoined.java b/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerJoined.java index c60aa5b..9a59060 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerJoined.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerJoined.java @@ -3,5 +3,11 @@ 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 { } diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerMove.java b/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerMove.java index fdd52d9..4eca8ae 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerMove.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerMove.java @@ -3,5 +3,12 @@ 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 { } diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerMovedInUrRoom.java b/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerMovedInUrRoom.java index 0870792..1f60595 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerMovedInUrRoom.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerMovedInUrRoom.java @@ -5,6 +5,11 @@ 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 { diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerRotation.java b/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerRotation.java index 968721b..1b71330 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerRotation.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/player/PlayerRotation.java @@ -1,5 +1,10 @@ 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 } diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/room/MovePlayerRoom.java b/common/src/main/java/cz/jzitnik/common/socket/messages/room/MovePlayerRoom.java index 631fd6c..bc50a1b 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/room/MovePlayerRoom.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/room/MovePlayerRoom.java @@ -3,6 +3,14 @@ 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 { } diff --git a/common/src/main/java/cz/jzitnik/common/socket/messages/room/MovePlayerRoomResponse.java b/common/src/main/java/cz/jzitnik/common/socket/messages/room/MovePlayerRoomResponse.java index 1d283d2..1e06ecc 100644 --- a/common/src/main/java/cz/jzitnik/common/socket/messages/room/MovePlayerRoomResponse.java +++ b/common/src/main/java/cz/jzitnik/common/socket/messages/room/MovePlayerRoomResponse.java @@ -9,13 +9,37 @@ 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 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 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 getIds() { return players.stream().map(Registry::id).collect(Collectors.toSet()); } diff --git a/game/src/main/java/cz/jzitnik/client/Cli.java b/game/src/main/java/cz/jzitnik/client/Cli.java index 5f32d35..d914573 100644 --- a/game/src/main/java/cz/jzitnik/client/Cli.java +++ b/game/src/main/java/cz/jzitnik/client/Cli.java @@ -17,6 +17,11 @@ import lombok.extern.slf4j.Slf4j; import java.io.IOException; +/** + * Command line interface handler using Lanterna. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @Dependency public class Cli implements Runnable { @@ -29,6 +34,9 @@ public class Cli implements Runnable { @InjectState private RunningState runningState; + /** + * Runs the CLI thread, handling terminal input and events. + */ @Override public void run() { // Start event manager thread diff --git a/game/src/main/java/cz/jzitnik/client/Game.java b/game/src/main/java/cz/jzitnik/client/Game.java index 71f774e..0fd15d9 100644 --- a/game/src/main/java/cz/jzitnik/client/Game.java +++ b/game/src/main/java/cz/jzitnik/client/Game.java @@ -14,6 +14,11 @@ 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")); @@ -32,6 +37,11 @@ public class Game { @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); diff --git a/game/src/main/java/cz/jzitnik/client/Main.java b/game/src/main/java/cz/jzitnik/client/Main.java index 41515de..6a54955 100644 --- a/game/src/main/java/cz/jzitnik/client/Main.java +++ b/game/src/main/java/cz/jzitnik/client/Main.java @@ -4,7 +4,18 @@ package cz.jzitnik.client; 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(); } diff --git a/game/src/main/java/cz/jzitnik/client/annotations/Config.java b/game/src/main/java/cz/jzitnik/client/annotations/Config.java index 882f382..60ef747 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/Config.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/Config.java @@ -5,8 +5,18 @@ 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(); } diff --git a/game/src/main/java/cz/jzitnik/client/annotations/Dependency.java b/game/src/main/java/cz/jzitnik/client/annotations/Dependency.java index 288c601..f43f282 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/Dependency.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/Dependency.java @@ -5,9 +5,18 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.annotation.ElementType; +/** + * Annotation to mark a class as a dependency for the DependencyManager. + * + * @author Jakub Žitník (jzitnik) + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Dependency { - /** Custom alias **/ + /** + * Custom alias for the dependency. + * + * @return Alias class + */ Class value() default Object.class; } \ No newline at end of file diff --git a/game/src/main/java/cz/jzitnik/client/annotations/EventHandler.java b/game/src/main/java/cz/jzitnik/client/annotations/EventHandler.java index 79bdc30..e69e6b4 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/EventHandler.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/EventHandler.java @@ -7,8 +7,18 @@ 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 value(); } diff --git a/game/src/main/java/cz/jzitnik/client/annotations/PostInit.java b/game/src/main/java/cz/jzitnik/client/annotations/PostInit.java index 2998554..8f2ac44 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/PostInit.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/PostInit.java @@ -5,6 +5,11 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.annotation.ElementType; +/** + * Annotation to mark a method to be called after dependency injection. + * + * @author Jakub Žitník (jzitnik) + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface PostInit { diff --git a/game/src/main/java/cz/jzitnik/client/annotations/ScheduledTask.java b/game/src/main/java/cz/jzitnik/client/annotations/ScheduledTask.java index 9856180..4e46a32 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/ScheduledTask.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/ScheduledTask.java @@ -6,9 +6,24 @@ import java.lang.annotation.Target; import java.lang.annotation.ElementType; import java.util.concurrent.TimeUnit; +/** + * Annotation to mark a task for periodic execution. + * + * @author Jakub Žitník (jzitnik) + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ScheduledTask { + /** + * Execution rate. + * + * @return rate + */ long rate(); + /** + * Time unit for the rate. + * + * @return rate unit + */ TimeUnit rateUnit(); } diff --git a/game/src/main/java/cz/jzitnik/client/annotations/SocketEventHandler.java b/game/src/main/java/cz/jzitnik/client/annotations/SocketEventHandler.java index bf6fdd9..665cc19 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/SocketEventHandler.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/SocketEventHandler.java @@ -7,8 +7,18 @@ 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 value(); } diff --git a/game/src/main/java/cz/jzitnik/client/annotations/State.java b/game/src/main/java/cz/jzitnik/client/annotations/State.java index 0d9646b..d88a7ab 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/State.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/State.java @@ -5,6 +5,11 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.annotation.ElementType; +/** + * Annotation to mark a class as a state component. + * + * @author Jakub Žitník (jzitnik) + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface State { diff --git a/game/src/main/java/cz/jzitnik/client/annotations/ThreadRegistry.java b/game/src/main/java/cz/jzitnik/client/annotations/ThreadRegistry.java index ff3ec98..03166fe 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/ThreadRegistry.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/ThreadRegistry.java @@ -5,6 +5,11 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.annotation.ElementType; +/** + * Annotation to mark a class for automatic thread registration. + * + * @author Jakub Žitník (jzitnik) + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ThreadRegistry { diff --git a/game/src/main/java/cz/jzitnik/client/annotations/injectors/InjectConfig.java b/game/src/main/java/cz/jzitnik/client/annotations/injectors/InjectConfig.java index 3371552..dc68959 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/injectors/InjectConfig.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/injectors/InjectConfig.java @@ -5,6 +5,11 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +/** + * Annotation to inject a configuration component into a field. + * + * @author Jakub Žitník (jzitnik) + */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface InjectConfig { diff --git a/game/src/main/java/cz/jzitnik/client/annotations/injectors/InjectDependency.java b/game/src/main/java/cz/jzitnik/client/annotations/injectors/InjectDependency.java index 2b8d0d6..ae56898 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/injectors/InjectDependency.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/injectors/InjectDependency.java @@ -5,6 +5,11 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +/** + * Annotation to inject a dependency into a field. + * + * @author Jakub Žitník (jzitnik) + */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface InjectDependency { diff --git a/game/src/main/java/cz/jzitnik/client/annotations/injectors/InjectState.java b/game/src/main/java/cz/jzitnik/client/annotations/injectors/InjectState.java index 0c6ae48..281678c 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/injectors/InjectState.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/injectors/InjectState.java @@ -5,6 +5,11 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +/** + * Annotation to inject a state component into a field. + * + * @author Jakub Žitník (jzitnik) + */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface InjectState { diff --git a/game/src/main/java/cz/jzitnik/client/annotations/ui/KeyboardPressHandler.java b/game/src/main/java/cz/jzitnik/client/annotations/ui/KeyboardPressHandler.java index b8c172a..37b59b2 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/ui/KeyboardPressHandler.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/ui/KeyboardPressHandler.java @@ -4,10 +4,25 @@ 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'; } diff --git a/game/src/main/java/cz/jzitnik/client/annotations/ui/KeyboardPressHandlers.java b/game/src/main/java/cz/jzitnik/client/annotations/ui/KeyboardPressHandlers.java index 32d1abf..3398bf1 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/ui/KeyboardPressHandlers.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/ui/KeyboardPressHandlers.java @@ -5,8 +5,18 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +/** + * Container annotation for repeatable KeyboardPressHandler. + * + * @author Jakub Žitník (jzitnik) + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface KeyboardPressHandlers { + /** + * Array of KeyboardPressHandler annotations. + * + * @return handlers + */ KeyboardPressHandler[] value(); } diff --git a/game/src/main/java/cz/jzitnik/client/annotations/ui/MouseHandler.java b/game/src/main/java/cz/jzitnik/client/annotations/ui/MouseHandler.java index 5ea0f70..ad11ce8 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/ui/MouseHandler.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/ui/MouseHandler.java @@ -5,8 +5,18 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.annotation.ElementType; +/** + * Annotation to mark a method as a mouse handler. + * + * @author Jakub Žitník (jzitnik) + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MouseHandler { + /** + * The type of mouse action to handle. + * + * @return handler type + */ MouseHandlerType value(); } diff --git a/game/src/main/java/cz/jzitnik/client/annotations/ui/MouseHandlerType.java b/game/src/main/java/cz/jzitnik/client/annotations/ui/MouseHandlerType.java index 158904b..3c49a4d 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/ui/MouseHandlerType.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/ui/MouseHandlerType.java @@ -1,5 +1,10 @@ package cz.jzitnik.client.annotations.ui; +/** + * Enum representing types of mouse handlers. + * + * @author Jakub Žitník (jzitnik) + */ public enum MouseHandlerType { CLICK, MOVE, diff --git a/game/src/main/java/cz/jzitnik/client/annotations/ui/Render.java b/game/src/main/java/cz/jzitnik/client/annotations/ui/Render.java index 0f60582..442dc75 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/ui/Render.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/ui/Render.java @@ -5,6 +5,11 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.annotation.ElementType; +/** + * Annotation to mark a method as a rendering method. + * + * @author Jakub Žitník (jzitnik) + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Render { diff --git a/game/src/main/java/cz/jzitnik/client/annotations/ui/UI.java b/game/src/main/java/cz/jzitnik/client/annotations/ui/UI.java index c74f7e2..96bc343 100644 --- a/game/src/main/java/cz/jzitnik/client/annotations/ui/UI.java +++ b/game/src/main/java/cz/jzitnik/client/annotations/ui/UI.java @@ -5,6 +5,11 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.annotation.ElementType; +/** + * Annotation to mark a class as a UI component. + * + * @author Jakub Žitník (jzitnik) + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface UI { diff --git a/game/src/main/java/cz/jzitnik/client/config/CoreLogic.java b/game/src/main/java/cz/jzitnik/client/config/CoreLogic.java index 545b613..cece3db 100644 --- a/game/src/main/java/cz/jzitnik/client/config/CoreLogic.java +++ b/game/src/main/java/cz/jzitnik/client/config/CoreLogic.java @@ -4,8 +4,19 @@ 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 diff --git a/game/src/main/java/cz/jzitnik/client/config/Debugging.java b/game/src/main/java/cz/jzitnik/client/config/Debugging.java index 287cdff..f8cd5f8 100644 --- a/game/src/main/java/cz/jzitnik/client/config/Debugging.java +++ b/game/src/main/java/cz/jzitnik/client/config/Debugging.java @@ -4,8 +4,23 @@ 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, diff --git a/game/src/main/java/cz/jzitnik/client/config/MicrophoneConfig.java b/game/src/main/java/cz/jzitnik/client/config/MicrophoneConfig.java index b07ba83..bc9d084 100644 --- a/game/src/main/java/cz/jzitnik/client/config/MicrophoneConfig.java +++ b/game/src/main/java/cz/jzitnik/client/config/MicrophoneConfig.java @@ -4,8 +4,19 @@ 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 diff --git a/game/src/main/java/cz/jzitnik/client/config/PlayerConfig.java b/game/src/main/java/cz/jzitnik/client/config/PlayerConfig.java index 78079ce..ba190c7 100644 --- a/game/src/main/java/cz/jzitnik/client/config/PlayerConfig.java +++ b/game/src/main/java/cz/jzitnik/client/config/PlayerConfig.java @@ -5,6 +5,18 @@ 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, @@ -15,6 +27,17 @@ public record PlayerConfig( 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, diff --git a/game/src/main/java/cz/jzitnik/client/config/ThreadPoolConfig.java b/game/src/main/java/cz/jzitnik/client/config/ThreadPoolConfig.java index b1c2dfc..8cdb0f6 100644 --- a/game/src/main/java/cz/jzitnik/client/config/ThreadPoolConfig.java +++ b/game/src/main/java/cz/jzitnik/client/config/ThreadPoolConfig.java @@ -4,8 +4,21 @@ 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, diff --git a/game/src/main/java/cz/jzitnik/client/events/ExitEvent.java b/game/src/main/java/cz/jzitnik/client/events/ExitEvent.java index 0a5761d..51f6dcf 100644 --- a/game/src/main/java/cz/jzitnik/client/events/ExitEvent.java +++ b/game/src/main/java/cz/jzitnik/client/events/ExitEvent.java @@ -2,6 +2,10 @@ package cz.jzitnik.client.events; import cz.jzitnik.client.utils.events.Event; -/** Custom event without any handler **/ +/** + * Event indicating that the application should exit. + * + * @author Jakub Žitník (jzitnik) + */ public class ExitEvent implements Event { } diff --git a/game/src/main/java/cz/jzitnik/client/events/KeyboardPressEvent.java b/game/src/main/java/cz/jzitnik/client/events/KeyboardPressEvent.java index 19b2e2b..0cf9bbc 100644 --- a/game/src/main/java/cz/jzitnik/client/events/KeyboardPressEvent.java +++ b/game/src/main/java/cz/jzitnik/client/events/KeyboardPressEvent.java @@ -5,6 +5,11 @@ import cz.jzitnik.client.utils.events.Event; import lombok.AllArgsConstructor; import lombok.Getter; +/** + * Event triggered when a key is pressed. + * + * @author Jakub Žitník (jzitnik) + */ @Getter @AllArgsConstructor public class KeyboardPressEvent implements Event { diff --git a/game/src/main/java/cz/jzitnik/client/events/MouseAction.java b/game/src/main/java/cz/jzitnik/client/events/MouseAction.java index 605e5db..8291be8 100644 --- a/game/src/main/java/cz/jzitnik/client/events/MouseAction.java +++ b/game/src/main/java/cz/jzitnik/client/events/MouseAction.java @@ -4,11 +4,28 @@ import com.googlecode.lanterna.TerminalPosition; import com.googlecode.lanterna.input.MouseActionType; import cz.jzitnik.client.utils.events.Event; +/** + * Event triggered by a mouse action. + * + * @author Jakub Žitník (jzitnik) + */ public class MouseAction extends com.googlecode.lanterna.input.MouseAction implements Event { + /** + * Constructs a MouseAction. + * + * @param actionType The type of action + * @param button The button involved + * @param position The terminal position + */ public MouseAction(MouseActionType actionType, int button, TerminalPosition position) { super(actionType, button, position); } + /** + * Constructs a MouseAction from an existing Lanterna MouseAction. + * + * @param mouseAction The Lanterna mouse action + */ public MouseAction(com.googlecode.lanterna.input.MouseAction mouseAction) { this(mouseAction.getActionType(), mouseAction.getButton(), mouseAction.getPosition()); } diff --git a/game/src/main/java/cz/jzitnik/client/events/MouseMoveEvent.java b/game/src/main/java/cz/jzitnik/client/events/MouseMoveEvent.java index e4c4e82..041406a 100644 --- a/game/src/main/java/cz/jzitnik/client/events/MouseMoveEvent.java +++ b/game/src/main/java/cz/jzitnik/client/events/MouseMoveEvent.java @@ -4,6 +4,11 @@ import cz.jzitnik.client.utils.events.Event; import lombok.AllArgsConstructor; import lombok.Getter; +/** + * Event triggered by a mouse movement. + * + * @author Jakub Žitník (jzitnik) + */ @AllArgsConstructor @Getter public class MouseMoveEvent implements Event { diff --git a/game/src/main/java/cz/jzitnik/client/events/PlayerMoveEvent.java b/game/src/main/java/cz/jzitnik/client/events/PlayerMoveEvent.java index 34ed568..2231e19 100644 --- a/game/src/main/java/cz/jzitnik/client/events/PlayerMoveEvent.java +++ b/game/src/main/java/cz/jzitnik/client/events/PlayerMoveEvent.java @@ -5,6 +5,11 @@ import cz.jzitnik.client.utils.events.Event; import lombok.AllArgsConstructor; import lombok.Getter; +/** + * Event triggered when a player attempts to move. + * + * @author Jakub Žitník (jzitnik) + */ @AllArgsConstructor @Getter public class PlayerMoveEvent implements Event { diff --git a/game/src/main/java/cz/jzitnik/client/events/RerenderPart.java b/game/src/main/java/cz/jzitnik/client/events/RerenderPart.java index bd79e2d..5f3767a 100644 --- a/game/src/main/java/cz/jzitnik/client/events/RerenderPart.java +++ b/game/src/main/java/cz/jzitnik/client/events/RerenderPart.java @@ -4,6 +4,11 @@ import cz.jzitnik.client.utils.events.Event; import lombok.AllArgsConstructor; import lombok.Getter; +/** + * Event requesting a rerender of a specific part of the screen. + * + * @author Jakub Žitník (jzitnik) + */ @Getter @AllArgsConstructor public class RerenderPart implements Event { diff --git a/game/src/main/java/cz/jzitnik/client/events/TerminalResizeEvent.java b/game/src/main/java/cz/jzitnik/client/events/TerminalResizeEvent.java index 7f3af38..be4c59a 100644 --- a/game/src/main/java/cz/jzitnik/client/events/TerminalResizeEvent.java +++ b/game/src/main/java/cz/jzitnik/client/events/TerminalResizeEvent.java @@ -5,6 +5,11 @@ import cz.jzitnik.client.utils.events.Event; import lombok.AllArgsConstructor; import lombok.Getter; +/** + * Event triggered when the terminal is resized. + * + * @author Jakub Žitník (jzitnik) + */ @AllArgsConstructor @Getter public class TerminalResizeEvent implements Event { diff --git a/game/src/main/java/cz/jzitnik/client/events/TerminalTooSmallEvent.java b/game/src/main/java/cz/jzitnik/client/events/TerminalTooSmallEvent.java index a2795b5..02bd327 100644 --- a/game/src/main/java/cz/jzitnik/client/events/TerminalTooSmallEvent.java +++ b/game/src/main/java/cz/jzitnik/client/events/TerminalTooSmallEvent.java @@ -2,5 +2,10 @@ 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 { } diff --git a/game/src/main/java/cz/jzitnik/client/events/handlers/CliHandler.java b/game/src/main/java/cz/jzitnik/client/events/handlers/CliHandler.java index 989838a..759bae7 100644 --- a/game/src/main/java/cz/jzitnik/client/events/handlers/CliHandler.java +++ b/game/src/main/java/cz/jzitnik/client/events/handlers/CliHandler.java @@ -18,6 +18,11 @@ import lombok.extern.slf4j.Slf4j; import java.io.IOException; +/** + * Handler for the RerenderScreen event in the CLI. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @EventHandler(RerenderScreen.class) public class CliHandler extends AbstractEventHandler { @@ -30,6 +35,11 @@ public class CliHandler extends AbstractEventHandler { @InjectState private RenderState renderState; + /** + * Handles the RerenderScreen event by drawing requested parts of the screen buffer to the terminal. + * + * @param event The RerenderScreen event + */ @Override public void handle(RerenderScreen event) { if (renderState.isTerminalTooSmall()) { @@ -79,6 +89,13 @@ public class CliHandler extends AbstractEventHandler { } } + /** + * Resolves the final pixel color by blending with the global override buffer. + * + * @param buffer The base pixel from the rendered buffer + * @param globalOverride The pixel from the global override buffer + * @return The final pixel to draw + */ private Pixel getPixel(Pixel buffer, AlphaPixel globalOverride) { if (globalOverride instanceof Empty) { return buffer; @@ -97,6 +114,14 @@ public class CliHandler extends AbstractEventHandler { return new ColoredPixel(blended); } + /** + * Blends two colors using an alpha value. + * + * @param base The base color + * @param overlay The overlay color + * @param alpha The alpha transparency of the overlay + * @return The blended color + */ private TextColor blendColors(TextColor base, TextColor overlay, float alpha) { int r = blend(base.getRed(), overlay.getRed(), alpha); int g = blend(base.getGreen(), overlay.getGreen(), alpha); @@ -105,10 +130,27 @@ public class CliHandler extends AbstractEventHandler { return new TextColor.RGB(r, g, b); } + /** + * Internal helper to blend a single color channel. + * + * @param base Base channel value + * @param overlay Overlay channel value + * @param alpha Alpha transparency + * @return Blended channel value + */ private int blend(int base, int overlay, float alpha) { return Math.round(base * (1 - alpha) + overlay * alpha); } + /** + * Draws a "half-pixel" using Unicode character '▄' to achieve higher vertical resolution. + * + * @param tg The TextGraphics context + * @param x X terminal position + * @param y Y terminal position + * @param topColor Color for the top half + * @param bottomColor Color for the bottom half + */ private void drawHalfPixel(TextGraphics tg, int x, int y, TextColor topColor, TextColor bottomColor) { diff --git a/game/src/main/java/cz/jzitnik/client/events/handlers/DialogEventHandler.java b/game/src/main/java/cz/jzitnik/client/events/handlers/DialogEventHandler.java index dcd111d..f6e56dc 100644 --- a/game/src/main/java/cz/jzitnik/client/events/handlers/DialogEventHandler.java +++ b/game/src/main/java/cz/jzitnik/client/events/handlers/DialogEventHandler.java @@ -26,6 +26,11 @@ 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 { @@ -53,13 +58,23 @@ public class DialogEventHandler extends AbstractEventHandler { 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; @@ -68,6 +83,13 @@ public class DialogEventHandler extends AbstractEventHandler { 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(), @@ -78,6 +100,14 @@ public class DialogEventHandler extends AbstractEventHandler { 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(), @@ -96,12 +126,24 @@ public class DialogEventHandler extends AbstractEventHandler { ); } + /** + * 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; diff --git a/game/src/main/java/cz/jzitnik/client/events/handlers/DroppedItemRerenderHandler.java b/game/src/main/java/cz/jzitnik/client/events/handlers/DroppedItemRerenderHandler.java index 7898f51..be88176 100644 --- a/game/src/main/java/cz/jzitnik/client/events/handlers/DroppedItemRerenderHandler.java +++ b/game/src/main/java/cz/jzitnik/client/events/handlers/DroppedItemRerenderHandler.java @@ -10,11 +10,21 @@ import cz.jzitnik.client.utils.events.EventManager; import java.awt.image.BufferedImage; +/** + * Handler for the DroppedItemRerender event. + * + * @author Jakub Žitník (jzitnik) + */ @EventHandler(DroppedItemRerender.class) public class DroppedItemRerenderHandler extends AbstractEventHandler { @InjectDependency private EventManager eventManager; + /** + * Handles the DroppedItemRerender event by emitting a RerenderPart event. + * + * @param event The DroppedItemRerender event + */ @Override public void handle(DroppedItemRerender event) { RoomCords droppedItemCords = event.droppedItem().getCords(); diff --git a/game/src/main/java/cz/jzitnik/client/events/handlers/ExitEventHandler.java b/game/src/main/java/cz/jzitnik/client/events/handlers/ExitEventHandler.java index 1c9cec5..f991554 100644 --- a/game/src/main/java/cz/jzitnik/client/events/handlers/ExitEventHandler.java +++ b/game/src/main/java/cz/jzitnik/client/events/handlers/ExitEventHandler.java @@ -10,6 +10,11 @@ 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 { @InjectDependency @@ -24,6 +29,11 @@ public class ExitEventHandler extends AbstractEventHandler { @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(); diff --git a/game/src/main/java/cz/jzitnik/client/events/handlers/FullRedrawEventHandler.java b/game/src/main/java/cz/jzitnik/client/events/handlers/FullRedrawEventHandler.java index dfa6e95..6631671 100644 --- a/game/src/main/java/cz/jzitnik/client/events/handlers/FullRedrawEventHandler.java +++ b/game/src/main/java/cz/jzitnik/client/events/handlers/FullRedrawEventHandler.java @@ -12,6 +12,11 @@ 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 { @InjectDependency @@ -20,6 +25,11 @@ public class FullRedrawEventHandler extends AbstractEventHandler { @@ -55,6 +60,11 @@ public class FullRoomDrawHandler extends AbstractEventHandler { @InjectDependency private GlobalIOHandlerRepository globalIOHandlerRepository; + /** + * Handles the FullRoomDraw event by rendering the entire room and players. + * + * @param event The FullRoomDraw event + */ @Override public void handle(FullRoomDraw event) { try { @@ -103,6 +113,9 @@ public class FullRoomDrawHandler extends AbstractEventHandler { } } + /** + * Enum representing door positions in a room. + */ public enum DoorPosition { TOP, LEFT, diff --git a/game/src/main/java/cz/jzitnik/client/events/handlers/InventoryRerenderHandler.java b/game/src/main/java/cz/jzitnik/client/events/handlers/InventoryRerenderHandler.java index 2511276..435e96b 100644 --- a/game/src/main/java/cz/jzitnik/client/events/handlers/InventoryRerenderHandler.java +++ b/game/src/main/java/cz/jzitnik/client/events/handlers/InventoryRerenderHandler.java @@ -9,6 +9,11 @@ import cz.jzitnik.client.ui.Inventory; import cz.jzitnik.client.utils.events.AbstractEventHandler; import cz.jzitnik.client.utils.events.EventManager; +/** + * Handler for the InventoryRerender event. + * + * @author Jakub Žitník (jzitnik) + */ @EventHandler(InventoryRerender.class) public class InventoryRerenderHandler extends AbstractEventHandler { @InjectDependency @@ -17,6 +22,11 @@ public class InventoryRerenderHandler extends AbstractEventHandler { @InjectState @@ -16,6 +21,11 @@ public class KeyboardPressEventHandler extends AbstractEventHandler { @InjectDependency @@ -38,6 +43,11 @@ public class MouseActionEventHandler extends AbstractEventHandler { @InjectDependency private DependencyManager dependencyManager; + /** + * Handles the MouseAction event by delegating to screens, repositories, or performing interactions. + * + * @param event The MouseAction event + */ @Override public void handle(MouseAction event) { if (gameState.getScreen() != null) { diff --git a/game/src/main/java/cz/jzitnik/client/events/handlers/MouseMoveEventHandler.java b/game/src/main/java/cz/jzitnik/client/events/handlers/MouseMoveEventHandler.java index dd4b13f..2467b5a 100644 --- a/game/src/main/java/cz/jzitnik/client/events/handlers/MouseMoveEventHandler.java +++ b/game/src/main/java/cz/jzitnik/client/events/handlers/MouseMoveEventHandler.java @@ -32,6 +32,11 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; +/** + * Handler for the MouseMoveEvent. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @EventHandler(MouseMoveEvent.class) public class MouseMoveEventHandler extends AbstractEventHandler { @@ -58,6 +63,17 @@ public class MouseMoveEventHandler extends AbstractEventHandler @InjectConfig private PlayerConfig playerConfig; + /** + * Calculates the distance from a point to a rectangle. + * + * @param px Point X + * @param py Point Y + * @param rectTopLeftX Rectangle top-left X + * @param rectTopLeftY Rectangle top-left Y + * @param rectBottomRightX Rectangle bottom-right X + * @param rectBottomRightY Rectangle bottom-right Y + * @return Distance as double + */ private double distancePointToRect( double px, double py, double rectTopLeftX, double rectTopLeftY, @@ -81,6 +97,11 @@ public class MouseMoveEventHandler extends AbstractEventHandler } } + /** + * Handles the MouseMoveEvent by updating selectable object states based on hover and distance. + * + * @param event The MouseMoveEvent + */ @Override public void handle(MouseMoveEvent event) { if (event.getMouseAction() != null) { diff --git a/game/src/main/java/cz/jzitnik/client/events/handlers/PlayerMoveEventHandler.java b/game/src/main/java/cz/jzitnik/client/events/handlers/PlayerMoveEventHandler.java index 7127b86..8ad7385 100644 --- a/game/src/main/java/cz/jzitnik/client/events/handlers/PlayerMoveEventHandler.java +++ b/game/src/main/java/cz/jzitnik/client/events/handlers/PlayerMoveEventHandler.java @@ -26,6 +26,11 @@ import lombok.extern.slf4j.Slf4j; import java.awt.image.BufferedImage; +/** + * Handler for the PlayerMoveEvent. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @EventHandler(PlayerMoveEvent.class) public class PlayerMoveEventHandler extends AbstractEventHandler { @@ -50,6 +55,11 @@ public class PlayerMoveEventHandler extends AbstractEventHandler { @InjectDependency @@ -17,6 +22,11 @@ public class RenderStatsHandler extends AbstractEventHandler { @InjectDependency private Stats stats; + /** + * Handles the RenderStats event by rerendering the stats UI component. + * + * @param event The RenderStats event + */ @Override public void handle(RenderStats event) { stats.rerender(); diff --git a/game/src/main/java/cz/jzitnik/client/events/handlers/RerenderPartHandler.java b/game/src/main/java/cz/jzitnik/client/events/handlers/RerenderPartHandler.java index 9bf1d76..5c0aadd 100644 --- a/game/src/main/java/cz/jzitnik/client/events/handlers/RerenderPartHandler.java +++ b/game/src/main/java/cz/jzitnik/client/events/handlers/RerenderPartHandler.java @@ -20,6 +20,11 @@ import cz.jzitnik.client.utils.events.EventManager; import java.awt.image.BufferedImage; +/** + * Handler for the RerenderPart event. + * + * @author Jakub Žitník (jzitnik) + */ @EventHandler(RerenderPart.class) public class RerenderPartHandler extends AbstractEventHandler { @InjectState @@ -40,6 +45,11 @@ public class RerenderPartHandler extends AbstractEventHandler { @InjectDependency private EventManager eventManager; + /** + * Handles the RerenderPart event by rerendering a portion of the screen. + * + * @param event The RerenderPart event + */ @Override public void handle(RerenderPart event) { int forStartX = event.getForStartX(); diff --git a/game/src/main/java/cz/jzitnik/client/events/handlers/RoomChangeEventHandler.java b/game/src/main/java/cz/jzitnik/client/events/handlers/RoomChangeEventHandler.java index 2cee842..3ace9b8 100644 --- a/game/src/main/java/cz/jzitnik/client/events/handlers/RoomChangeEventHandler.java +++ b/game/src/main/java/cz/jzitnik/client/events/handlers/RoomChangeEventHandler.java @@ -21,6 +21,11 @@ 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 { @@ -32,6 +37,11 @@ public class RoomChangeEventHandler extends AbstractEventHandler { @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 { diff --git a/game/src/main/java/cz/jzitnik/client/events/handlers/TerminalResizeEventHandler.java b/game/src/main/java/cz/jzitnik/client/events/handlers/TerminalResizeEventHandler.java index c9ca2e2..1d18e91 100644 --- a/game/src/main/java/cz/jzitnik/client/events/handlers/TerminalResizeEventHandler.java +++ b/game/src/main/java/cz/jzitnik/client/events/handlers/TerminalResizeEventHandler.java @@ -15,6 +15,11 @@ import cz.jzitnik.client.utils.events.AbstractEventHandler; import cz.jzitnik.client.utils.events.EventManager; import lombok.extern.slf4j.Slf4j; +/** + * Handler for the TerminalResizeEvent. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @EventHandler(TerminalResizeEvent.class) public class TerminalResizeEventHandler extends AbstractEventHandler { @@ -29,6 +34,11 @@ public class TerminalResizeEventHandler extends AbstractEventHandler { @InjectState private TerminalState terminalState; + /** + * Handles the TerminalTooSmallEvent by rendering a warning message directly to the terminal. + * + * @param event The TerminalTooSmallEvent + */ @Override public void handle(TerminalTooSmallEvent event) { // Directly render the message for the user diff --git a/game/src/main/java/cz/jzitnik/client/game/Constants.java b/game/src/main/java/cz/jzitnik/client/game/Constants.java index 607479c..38b1b4d 100644 --- a/game/src/main/java/cz/jzitnik/client/game/Constants.java +++ b/game/src/main/java/cz/jzitnik/client/game/Constants.java @@ -2,6 +2,12 @@ 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); } diff --git a/game/src/main/java/cz/jzitnik/client/game/GamePlayer.java b/game/src/main/java/cz/jzitnik/client/game/GamePlayer.java index 4e27c0a..fbdc74f 100644 --- a/game/src/main/java/cz/jzitnik/client/game/GamePlayer.java +++ b/game/src/main/java/cz/jzitnik/client/game/GamePlayer.java @@ -4,7 +4,24 @@ 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); } diff --git a/game/src/main/java/cz/jzitnik/client/game/GameRoom.java b/game/src/main/java/cz/jzitnik/client/game/GameRoom.java index cdb46f7..b7bdd5a 100644 --- a/game/src/main/java/cz/jzitnik/client/game/GameRoom.java +++ b/game/src/main/java/cz/jzitnik/client/game/GameRoom.java @@ -14,6 +14,11 @@ 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" @@ -45,6 +50,15 @@ public class GameRoom { 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, @@ -72,21 +86,41 @@ public class GameRoom { 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; diff --git a/game/src/main/java/cz/jzitnik/client/game/GameState.java b/game/src/main/java/cz/jzitnik/client/game/GameState.java index 67027ad..0b5e5b7 100644 --- a/game/src/main/java/cz/jzitnik/client/game/GameState.java +++ b/game/src/main/java/cz/jzitnik/client/game/GameState.java @@ -11,6 +11,11 @@ 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 { @@ -30,10 +35,20 @@ public class GameState { private final List otherPlayers = new ArrayList<>(); + /** + * Gets a list of visible other players. + * + * @return List of visible other players + */ public List getOtherPlayers() { return otherPlayers.stream().filter(OtherPlayer::isVisible).toList(); } + /** + * Gets a list of all other players. + * + * @return List of all other players + */ public List getAllOtherPlayers() { return otherPlayers; } @@ -45,6 +60,11 @@ public class GameState { @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); diff --git a/game/src/main/java/cz/jzitnik/client/game/OtherPlayer.java b/game/src/main/java/cz/jzitnik/client/game/OtherPlayer.java index d90b855..d776c4c 100644 --- a/game/src/main/java/cz/jzitnik/client/game/OtherPlayer.java +++ b/game/src/main/java/cz/jzitnik/client/game/OtherPlayer.java @@ -9,6 +9,11 @@ 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; @@ -19,11 +24,20 @@ public class OtherPlayer implements GamePlayer { @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; diff --git a/game/src/main/java/cz/jzitnik/client/game/Player.java b/game/src/main/java/cz/jzitnik/client/game/Player.java index e524a97..cbd6c72 100644 --- a/game/src/main/java/cz/jzitnik/client/game/Player.java +++ b/game/src/main/java/cz/jzitnik/client/game/Player.java @@ -22,11 +22,18 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +/** + * Represents the local player. + * + * @author Jakub Žitník (jzitnik) + */ @Getter @Slf4j public class Player implements GamePlayer { private final int id; + /** Maximum stamina value. */ public static final int MAX_STAMINA = 20; + /** Maximum health value. */ public static final int MAX_HEALTH = 30; private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); @@ -43,24 +50,47 @@ public class Player implements GamePlayer { private boolean hitAnimationOn = false; private ScheduledFuture currentTimeoutHitAnimation = null; + /** + * Constructs a Player. + * + * @param playerCreation Player creation data + */ public Player(PlayerCreation playerCreation) { this.playerCords = playerCreation.getPlayerCords(); this.collider = playerCreation.getCollider(); this.id = playerCreation.getId(); } + /** + * Increases player stamina. + */ public void increaseStamina() { stamina++; } + /** + * Decreases player stamina. + */ public void decreaseStamina() { stamina--; } + /** + * Restores player health. + * + * @param amount Amount to restore + */ public void addHealth(int amount) { health = Math.min(MAX_HEALTH, health + amount); } + /** + * Deals damage to the player. + * + * @param amount Damage amount + * @param dependencyManager Dependency manager + * @return true if player died + */ public boolean dealDamage(int amount, DependencyManager dependencyManager) { if (health - amount <= 0) { health = 0; @@ -88,6 +118,11 @@ public class Player implements GamePlayer { return false; } + /** + * Triggers a rerender of the player. + * + * @param dependencyManager Dependency manager + */ private void rerender(DependencyManager dependencyManager) { ResourceManager resourceManager = dependencyManager.getDependencyOrThrow(ResourceManager.class); EventManager eventManager = dependencyManager.getDependencyOrThrow(EventManager.class); @@ -104,6 +139,10 @@ public class Player implements GamePlayer { }); } + /** + * {@inheritDoc} + */ + @Override public BufferedImage getTexture(ResourceManager resourceManager) { BufferedImage resource = resourceManager.getResource(switch (playerRotation) { case FRONT -> ResourceManager.Resource.PLAYER_FRONT; @@ -119,6 +158,11 @@ public class Player implements GamePlayer { return resource; } + /** + * Gets the damage dealt by the player with their current weapon. + * + * @return Damage value + */ public int getDamageDeal() { int damage = 1; @@ -131,6 +175,12 @@ public class Player implements GamePlayer { return damage; } + /** + * Adds an item to the player's inventory. + * + * @param item Item to add + * @return true if item was added, false if inventory is full + */ public boolean addItem(GameItem item) { boolean added = false; for (int i = 0; i < inventory.length; i++) { @@ -144,6 +194,11 @@ public class Player implements GamePlayer { return added; } + /** + * Triggers a weapon swing animation. + * + * @param delayMs Duration of the swing + */ public void swing(int delayMs) { if (swinging) { return; diff --git a/game/src/main/java/cz/jzitnik/client/game/Requirement.java b/game/src/main/java/cz/jzitnik/client/game/Requirement.java index 3f41071..bea51cd 100644 --- a/game/src/main/java/cz/jzitnik/client/game/Requirement.java +++ b/game/src/main/java/cz/jzitnik/client/game/Requirement.java @@ -3,7 +3,18 @@ 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 diff --git a/game/src/main/java/cz/jzitnik/client/game/ResourceManager.java b/game/src/main/java/cz/jzitnik/client/game/ResourceManager.java index 85c06ba..038fdb2 100644 --- a/game/src/main/java/cz/jzitnik/client/game/ResourceManager.java +++ b/game/src/main/java/cz/jzitnik/client/game/ResourceManager.java @@ -11,11 +11,19 @@ import java.io.IOException; import java.io.InputStream; import java.util.HashMap; +/** + * Manages loading and caching of game resources (textures, audio). + * + * @author Jakub Žitník (jzitnik) + */ @Dependency public class ResourceManager { @InjectDependency private ClassLoader classLoader; + /** + * Enum representing available game resources. + */ @AllArgsConstructor @Getter public enum Resource { @@ -69,6 +77,12 @@ public class ResourceManager { private final HashMap resourceCache = new HashMap<>(); + /** + * Retrieves a texture resource by its enum key. + * + * @param resource The resource key + * @return The loaded BufferedImage + */ public BufferedImage getResource(Resource resource) { if (resourceCache.containsKey(resource)) { return resourceCache.get(resource); @@ -88,6 +102,12 @@ public class ResourceManager { } } + /** + * Retrieves a texture resource by its path. + * + * @param path The resource path + * @return The loaded BufferedImage + */ public BufferedImage getResource(String path) { InputStream is = classLoader.getResourceAsStream(path); if (is == null) { @@ -101,6 +121,12 @@ public class ResourceManager { } } + /** + * Gets a resource input stream by path. + * + * @param path The resource path + * @return InputStream for the resource + */ public InputStream getResourceAsStream(String path) { return classLoader.getResourceAsStream(path); } diff --git a/game/src/main/java/cz/jzitnik/client/game/dialog/Dialog.java b/game/src/main/java/cz/jzitnik/client/game/dialog/Dialog.java index 7164c2d..012eb4f 100644 --- a/game/src/main/java/cz/jzitnik/client/game/dialog/Dialog.java +++ b/game/src/main/java/cz/jzitnik/client/game/dialog/Dialog.java @@ -5,6 +5,11 @@ 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 { /** @@ -14,6 +19,12 @@ public class Dialog implements Event { 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, diff --git a/game/src/main/java/cz/jzitnik/client/game/dialog/OnEnd.java b/game/src/main/java/cz/jzitnik/client/game/dialog/OnEnd.java index 147e20f..b2bd3b5 100644 --- a/game/src/main/java/cz/jzitnik/client/game/dialog/OnEnd.java +++ b/game/src/main/java/cz/jzitnik/client/game/dialog/OnEnd.java @@ -20,6 +20,11 @@ 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" @@ -31,10 +36,18 @@ import java.util.Optional; @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, @@ -43,6 +56,7 @@ public interface OnEnd { super(new Run(item), onEnd); } + /** Internal runnable to give the item. */ @RequiredArgsConstructor private static class Run implements Runnable { private final GameItem item; @@ -56,6 +70,9 @@ public interface OnEnd { @InjectDependency private ResourceManager resourceManager; + /** + * {@inheritDoc} + */ @Override public void run() { Player player = gameState.getPlayer(); @@ -72,6 +89,7 @@ public interface OnEnd { } } + /** Action that runs arbitrary code. */ @Getter @RequiredArgsConstructor class RunCode implements OnEnd { @@ -79,24 +97,44 @@ public interface OnEnd { 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 ) { + /** + * 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, @@ -106,6 +144,9 @@ public interface OnEnd { 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(); @@ -126,6 +167,12 @@ public interface OnEnd { } } + /** + * 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)) diff --git a/game/src/main/java/cz/jzitnik/client/game/exceptions/InvalidCoordinatesException.java b/game/src/main/java/cz/jzitnik/client/game/exceptions/InvalidCoordinatesException.java index 5b53a54..a05a262 100644 --- a/game/src/main/java/cz/jzitnik/client/game/exceptions/InvalidCoordinatesException.java +++ b/game/src/main/java/cz/jzitnik/client/game/exceptions/InvalidCoordinatesException.java @@ -1,10 +1,23 @@ 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(); } diff --git a/game/src/main/java/cz/jzitnik/client/game/items/GameItem.java b/game/src/main/java/cz/jzitnik/client/game/items/GameItem.java index 6538c9f..5fbd10c 100644 --- a/game/src/main/java/cz/jzitnik/client/game/items/GameItem.java +++ b/game/src/main/java/cz/jzitnik/client/game/items/GameItem.java @@ -8,6 +8,11 @@ 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; @@ -16,6 +21,15 @@ public class GameItem implements Renderable { 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, diff --git a/game/src/main/java/cz/jzitnik/client/game/items/types/BeastSkin.java b/game/src/main/java/cz/jzitnik/client/game/items/types/BeastSkin.java index e72b9f5..54be8cf 100644 --- a/game/src/main/java/cz/jzitnik/client/game/items/types/BeastSkin.java +++ b/game/src/main/java/cz/jzitnik/client/game/items/types/BeastSkin.java @@ -1,6 +1,14 @@ package cz.jzitnik.client.game.items.types; +/** + * Represents a beast skin item type. + * + * @author Jakub Žitník (jzitnik) + */ public class BeastSkin implements ItemType { + /** + * {@inheritDoc} + */ @Override public Class getItemType() { return BeastSkin.class; diff --git a/game/src/main/java/cz/jzitnik/client/game/items/types/InteractableItem.java b/game/src/main/java/cz/jzitnik/client/game/items/types/InteractableItem.java index f3c28cd..905b87c 100644 --- a/game/src/main/java/cz/jzitnik/client/game/items/types/InteractableItem.java +++ b/game/src/main/java/cz/jzitnik/client/game/items/types/InteractableItem.java @@ -3,10 +3,26 @@ 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, } } diff --git a/game/src/main/java/cz/jzitnik/client/game/items/types/ItemType.java b/game/src/main/java/cz/jzitnik/client/game/items/types/ItemType.java index a2dfe1f..b304e4a 100644 --- a/game/src/main/java/cz/jzitnik/client/game/items/types/ItemType.java +++ b/game/src/main/java/cz/jzitnik/client/game/items/types/ItemType.java @@ -5,6 +5,12 @@ 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 The class type of the item + * @author Jakub Žitník (jzitnik) + */ @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, property = "name" @@ -17,5 +23,10 @@ import cz.jzitnik.client.game.items.types.weapons.Sword; @JsonSubTypes.Type(value = BeastSkin.class, name = "beast_skin"), }) public interface ItemType { + /** + * Gets the class representing this item type. + * + * @return The item type class + */ Class getItemType(); } diff --git a/game/src/main/java/cz/jzitnik/client/game/items/types/Junk.java b/game/src/main/java/cz/jzitnik/client/game/items/types/Junk.java index 9c45fa3..c7ebea9 100644 --- a/game/src/main/java/cz/jzitnik/client/game/items/types/Junk.java +++ b/game/src/main/java/cz/jzitnik/client/game/items/types/Junk.java @@ -1,6 +1,14 @@ package cz.jzitnik.client.game.items.types; +/** + * Represents a junk item type. + * + * @author Jakub Žitník (jzitnik) + */ public class Junk implements ItemType { + /** + * {@inheritDoc} + */ @Override public Class getItemType() { return Junk.class; diff --git a/game/src/main/java/cz/jzitnik/client/game/items/types/Key.java b/game/src/main/java/cz/jzitnik/client/game/items/types/Key.java index 2f9af47..325f525 100644 --- a/game/src/main/java/cz/jzitnik/client/game/items/types/Key.java +++ b/game/src/main/java/cz/jzitnik/client/game/items/types/Key.java @@ -1,6 +1,14 @@ package cz.jzitnik.client.game.items.types; +/** + * Represents a key item type. + * + * @author Jakub Žitník (jzitnik) + */ public class Key implements ItemType { + /** + * {@inheritDoc} + */ @Override public Class getItemType() { return Key.class; diff --git a/game/src/main/java/cz/jzitnik/client/game/items/types/food/Food.java b/game/src/main/java/cz/jzitnik/client/game/items/types/food/Food.java index 45902d2..0ce6f02 100644 --- a/game/src/main/java/cz/jzitnik/client/game/items/types/food/Food.java +++ b/game/src/main/java/cz/jzitnik/client/game/items/types/food/Food.java @@ -10,9 +10,19 @@ 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 { 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 @@ -20,6 +30,13 @@ public class Food implements InteractableItem, ItemType { 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); @@ -31,6 +48,9 @@ public class Food implements InteractableItem, ItemType { return InteractableItemResponse.CLEAR_ITEM; } + /** + * {@inheritDoc} + */ @Override public Class getItemType() { return Food.class; diff --git a/game/src/main/java/cz/jzitnik/client/game/items/types/interfaces/WeaponInterface.java b/game/src/main/java/cz/jzitnik/client/game/items/types/interfaces/WeaponInterface.java index e55352b..9a4f012 100644 --- a/game/src/main/java/cz/jzitnik/client/game/items/types/interfaces/WeaponInterface.java +++ b/game/src/main/java/cz/jzitnik/client/game/items/types/interfaces/WeaponInterface.java @@ -1,5 +1,15 @@ 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(); } diff --git a/game/src/main/java/cz/jzitnik/client/game/items/types/weapons/Sword.java b/game/src/main/java/cz/jzitnik/client/game/items/types/weapons/Sword.java index 0b66d23..90826e2 100644 --- a/game/src/main/java/cz/jzitnik/client/game/items/types/weapons/Sword.java +++ b/game/src/main/java/cz/jzitnik/client/game/items/types/weapons/Sword.java @@ -3,7 +3,17 @@ 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 diff --git a/game/src/main/java/cz/jzitnik/client/game/items/types/weapons/Weapon.java b/game/src/main/java/cz/jzitnik/client/game/items/types/weapons/Weapon.java index 9ff2e59..bacfa3a 100644 --- a/game/src/main/java/cz/jzitnik/client/game/items/types/weapons/Weapon.java +++ b/game/src/main/java/cz/jzitnik/client/game/items/types/weapons/Weapon.java @@ -4,15 +4,28 @@ 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, WeaponInterface { private final int dealDamage; + /** + * {@inheritDoc} + */ @Override public final Class getItemType() { return Weapon.class; } + /** + * Gets the damage dealt by this weapon. + * + * @return Damage value + */ @Override public int getDamageDeal() { return dealDamage; diff --git a/game/src/main/java/cz/jzitnik/client/game/mobs/DialogMob.java b/game/src/main/java/cz/jzitnik/client/game/mobs/DialogMob.java index bc389b4..4b9d75f 100644 --- a/game/src/main/java/cz/jzitnik/client/game/mobs/DialogMob.java +++ b/game/src/main/java/cz/jzitnik/client/game/mobs/DialogMob.java @@ -14,10 +14,25 @@ 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, @@ -37,6 +52,9 @@ public class DialogMob extends Mob { @InjectState private DialogState dialogState; + /** + * {@inheritDoc} + */ @Override public void interact() { log.debug("Interacting with dialog mob!"); diff --git a/game/src/main/java/cz/jzitnik/client/game/mobs/HittableMob.java b/game/src/main/java/cz/jzitnik/client/game/mobs/HittableMob.java index 9bfe88f..b19732e 100644 --- a/game/src/main/java/cz/jzitnik/client/game/mobs/HittableMob.java +++ b/game/src/main/java/cz/jzitnik/client/game/mobs/HittableMob.java @@ -20,8 +20,16 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +/** + * Abstract base class for mobs that can be hit and killed. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j public abstract class HittableMob extends Mob { + /** + * Called when the mob is killed. + */ public abstract void onKilled(); private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); @@ -31,6 +39,9 @@ public abstract class HittableMob extends Mob { private boolean hitAnimationOn = false; + /** + * {@inheritDoc} + */ @Override public BufferedImage getTexture() { if (hitAnimationOn) { @@ -40,6 +51,12 @@ public abstract class HittableMob extends Mob { return texture; } + /** + * Applies a red factor to an image, used for hit animation. + * + * @param src The source image + * @return The red-tinted image + */ public static BufferedImage applyRedFactor(BufferedImage src) { final float redFactor = 2f; int width = src.getWidth(); @@ -68,11 +85,23 @@ public abstract class HittableMob extends Mob { @InjectDependency private RoomTaskScheduler roomTaskScheduler; + /** + * Constructs a HittableMob. + * + * @param texture Texture + * @param tasks Tasks + * @param cords Coordinates + * @param collider Collider + * @param health Initial health + */ public HittableMob(BufferedImage texture, MobRoomTask[] tasks, RoomCords cords, RoomPart collider, int health) { super(texture, tasks, cords, collider); this.health = health; } + /** + * {@inheritDoc} + */ @Override public final void interact() { health -= gameState.getPlayer().getDamageDeal(); @@ -106,6 +135,9 @@ public abstract class HittableMob extends Mob { }, 250, TimeUnit.MILLISECONDS); } + /** + * Triggers a rerender of the mob's position. + */ private void rerender() { int forStartX = cords.getX(); int forStartY = cords.getY(); diff --git a/game/src/main/java/cz/jzitnik/client/game/mobs/HittableMobDrops.java b/game/src/main/java/cz/jzitnik/client/game/mobs/HittableMobDrops.java index 7cb2086..8435728 100644 --- a/game/src/main/java/cz/jzitnik/client/game/mobs/HittableMobDrops.java +++ b/game/src/main/java/cz/jzitnik/client/game/mobs/HittableMobDrops.java @@ -21,6 +21,11 @@ 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; @@ -29,6 +34,17 @@ public class HittableMobDrops extends HittableMob { @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, @@ -49,6 +65,9 @@ public class HittableMobDrops extends HittableMob { public void afterKill() { } + /** + * {@inheritDoc} + */ @Override public final void onKilled() { boolean addedIntoInventory = false; @@ -77,6 +96,15 @@ public class HittableMobDrops extends HittableMob { 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); diff --git a/game/src/main/java/cz/jzitnik/client/game/mobs/HittableMobNoDrops.java b/game/src/main/java/cz/jzitnik/client/game/mobs/HittableMobNoDrops.java index 511afe4..8ba8127 100644 --- a/game/src/main/java/cz/jzitnik/client/game/mobs/HittableMobNoDrops.java +++ b/game/src/main/java/cz/jzitnik/client/game/mobs/HittableMobNoDrops.java @@ -8,7 +8,22 @@ 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, @@ -21,6 +36,9 @@ public class HittableMobNoDrops extends HittableMob { super(resourceManager.getResource(texture), tasks, cords, collider, health); } + /** + * {@inheritDoc} + */ @Override public void onKilled() { diff --git a/game/src/main/java/cz/jzitnik/client/game/mobs/Mob.java b/game/src/main/java/cz/jzitnik/client/game/mobs/Mob.java index 141ce03..56fed8e 100644 --- a/game/src/main/java/cz/jzitnik/client/game/mobs/Mob.java +++ b/game/src/main/java/cz/jzitnik/client/game/mobs/Mob.java @@ -15,6 +15,11 @@ 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" @@ -39,6 +44,11 @@ public abstract class Mob implements Renderable, Selectable { @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; @@ -46,6 +56,14 @@ public abstract class Mob implements Renderable, Selectable { 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; diff --git a/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/BlindMobFollowingPlayerTask.java b/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/BlindMobFollowingPlayerTask.java index 3780ca3..adcf051 100644 --- a/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/BlindMobFollowingPlayerTask.java +++ b/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/BlindMobFollowingPlayerTask.java @@ -20,9 +20,20 @@ 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, @@ -33,11 +44,17 @@ public class BlindMobFollowingPlayerTask extends MobRoomTask { 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 @@ -68,6 +85,9 @@ public class BlindMobFollowingPlayerTask extends MobRoomTask { @InjectConfig private MicrophoneConfig microphoneConfig; + /** + * {@inheritDoc} + */ @Override public void run() { if (playerCords == null || (microphoneState.isMicrophoneSetup() && microphoneState.getMicrophoneVolume() > microphoneConfig.volumeThreshold())) { diff --git a/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/EnemyPlayerAttackingTask.java b/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/EnemyPlayerAttackingTask.java index 0eb8976..534308d 100644 --- a/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/EnemyPlayerAttackingTask.java +++ b/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/EnemyPlayerAttackingTask.java @@ -16,10 +16,22 @@ 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, @@ -31,11 +43,17 @@ public class EnemyPlayerAttackingTask extends MobRoomTask { 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; @@ -52,6 +70,9 @@ public class EnemyPlayerAttackingTask extends MobRoomTask { @InjectDependency private DependencyManager dependencyManager; + /** + * {@inheritDoc} + */ @Override public void run() { RoomCords playerCords = gameState.getPlayer().getPlayerCords(); diff --git a/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/MobFollowingPlayerTask.java b/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/MobFollowingPlayerTask.java index 0a0b43d..04214a9 100644 --- a/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/MobFollowingPlayerTask.java +++ b/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/MobFollowingPlayerTask.java @@ -29,10 +29,21 @@ import java.awt.image.BufferedImage; import java.util.List; import java.util.concurrent.TimeUnit; +/** + * Task that makes a mob follow the player using A* pathfinding. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j public class MobFollowingPlayerTask extends MobRoomTask { private final Task task; + /** + * Constructs a MobFollowingPlayerTask. + * + * @param speed Mob movement speed + * @param updateRateMs Execution rate in milliseconds + */ @JsonCreator public MobFollowingPlayerTask( @JsonProperty("speed") int speed, @@ -43,11 +54,17 @@ public class MobFollowingPlayerTask extends MobRoomTask { this.task = task; } + /** + * {@inheritDoc} + */ @Override public void setOwner(Mob mob) { task.setMob(mob); } + /** + * Internal task runnable logic. + */ @RequiredArgsConstructor static class Task implements Runnable { private final int speed; @@ -71,6 +88,19 @@ public class MobFollowingPlayerTask extends MobRoomTask { @InjectConfig private Debugging debugging; + /** + * Core logic to move a mob towards player coordinates. + * + * @param playerCords Target player coordinates + * @param mob Mob instance to move + * @param gameState Current game state + * @param speed Movement speed + * @param resourceManager Resource manager + * @param terminalState Terminal state + * @param screenBuffer Screen buffer + * @param debugging Debugging config + * @param eventManager Event manager + */ protected static void moveMob(RoomCords playerCords, Mob mob, GameState gameState, int speed, ResourceManager resourceManager, TerminalState terminalState, ScreenBuffer screenBuffer, Debugging debugging, EventManager eventManager) { RoomCords mobCords = mob.getCords(); List solidParts = gameState.getCurrentRoom().getColliders(); @@ -112,6 +142,9 @@ public class MobFollowingPlayerTask extends MobRoomTask { } } + /** + * {@inheritDoc} + */ @Override public void run() { moveMob(gameState.getPlayer().getPlayerCords(), mob, gameState, speed, resourceManager, terminalState, screenBuffer, debugging, eventManager); diff --git a/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/MobRoomTask.java b/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/MobRoomTask.java index 99373ab..57056c7 100644 --- a/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/MobRoomTask.java +++ b/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/MobRoomTask.java @@ -17,10 +17,27 @@ import java.util.concurrent.TimeUnit; @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); } diff --git a/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/utils/AStarAlg.java b/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/utils/AStarAlg.java index be59836..43eec66 100644 --- a/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/utils/AStarAlg.java +++ b/game/src/main/java/cz/jzitnik/client/game/mobs/tasks/utils/AStarAlg.java @@ -5,6 +5,11 @@ import cz.jzitnik.common.models.coordinates.RoomCords; import java.util.*; +/** + * Utility class for A* pathfinding algorithm. + * + * @author Jakub Žitník (jzitnik) + */ public class AStarAlg { private static final int MIN_X = 30; @@ -12,6 +17,15 @@ public class AStarAlg { private static final int MIN_Y = 10; private static final int MAX_Y = 113; + /** + * Finds a path from start to target coordinates avoiding colliders. + * + * @param start Start coordinates + * @param target Target coordinates + * @param colliders List of room colliders + * @param mobCollider Collider of the moving entity + * @return List of coordinates representing the path + */ public static List findPath(RoomCords start, RoomCords target, List colliders, RoomPart mobCollider) { PriorityQueue openSet = new PriorityQueue<>(Comparator.comparingInt(n -> n.f)); Set closedSet = new HashSet<>(); @@ -51,6 +65,13 @@ public class AStarAlg { return new ArrayList<>(); } + /** + * Gets neighbor nodes for a given node. + * + * @param current Current node + * @param target Target coordinates for heuristic + * @return List of neighbor nodes + */ private static List getNeighbors(Node current, RoomCords target) { List neighbors = new ArrayList<>(); @@ -68,6 +89,15 @@ public class AStarAlg { return neighbors; } + /** + * Checks if a position is valid (within bounds and not colliding). + * + * @param x X coordinate + * @param y Y coordinate + * @param colliders List of colliders + * @param mobCollider Entity collider + * @return true if valid + */ private static boolean isValidPosition(int x, int y, List colliders, RoomPart mobCollider) { if (x < MIN_X || x > MAX_X) return false; @@ -85,6 +115,12 @@ public class AStarAlg { return true; } + /** + * Reconstructs the path from the end node by following parents. + * + * @param endNode The destination node + * @return List of coordinates + */ private static List reconstructPath(Node endNode) { List path = new ArrayList<>(); Node current = endNode; @@ -96,12 +132,22 @@ public class AStarAlg { return path; } + /** + * Calculates the heuristic distance (diagonal distance) between two points. + * + * @param a Point A + * @param b Point B + * @return Heuristic value + */ private static int getHeuristic(RoomCords a, RoomCords b) { int dx = Math.abs(a.getX() - b.getX()); int dy = Math.abs(a.getY() - b.getY()); return Math.max(dx, dy); } + /** + * Internal node class for A* search. + */ private static class Node { int x, y; int g, h, f; diff --git a/game/src/main/java/cz/jzitnik/client/game/objects/Chest.java b/game/src/main/java/cz/jzitnik/client/game/objects/Chest.java index d6e3870..9bfaca0 100644 --- a/game/src/main/java/cz/jzitnik/client/game/objects/Chest.java +++ b/game/src/main/java/cz/jzitnik/client/game/objects/Chest.java @@ -36,6 +36,11 @@ import java.net.Socket; import java.util.HashSet; import java.util.List; +/** + * Represents a chest object that contains items. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j public final class Chest extends GameObject implements UIClickHandler { private static final int RENDER_PADDING = 1; @@ -70,6 +75,13 @@ public final class Chest extends GameObject implements UIClickHandler { @InjectConfig private Debugging debugging; + /** + * Constructs a Chest. + * + * @param cords Coordinates + * @param items Items in the chest + * @param resourceManager Resource manager + */ @JsonCreator public Chest( @JsonProperty("cords") RoomCords cords, @@ -80,12 +92,21 @@ public final class Chest extends GameObject implements UIClickHandler { this.items = Lists.newArrayList(items == null ? new GameItem[] {} : items); } + /** + * {@inheritDoc} + */ @Override public void interact() { log.debug("Interacted with chest"); render(false); } + /** + * Creates a Grid for the chest UI. + * + * @param itemCount Number of items + * @return Grid instance + */ private Grid createGrid(int itemCount) { return new Grid( Math.max(1, itemCount), // Items X @@ -99,6 +120,11 @@ public final class Chest extends GameObject implements UIClickHandler { ); } + /** + * Renders the chest UI. + * + * @param clear Whether to clear previous UI + */ private void render(boolean clear) { GameRoom currentRoom = gameState.getCurrentRoom(); Player player = gameState.getPlayer(); @@ -170,6 +196,9 @@ public final class Chest extends GameObject implements UIClickHandler { rendered = true; } + /** + * Clears previous UI rendering from buffers. + */ private void clearPreviousUI( GameRoom room, BufferedImage roomTexture, @@ -204,6 +233,9 @@ public final class Chest extends GameObject implements UIClickHandler { } } + /** + * Draws the chest UI to the buffers. + */ private void drawUI( Grid grid, Pixel[][] buffer, @@ -233,6 +265,12 @@ public final class Chest extends GameObject implements UIClickHandler { } } + /** + * Converts an ARGB integer to a ColoredPixel. + * + * @param argb The ARGB value + * @return The ColoredPixel + */ private Pixel pixelToColored(int argb) { int r = (argb >> 16) & 0xff; int g = (argb >> 8) & 0xff; @@ -240,6 +278,9 @@ public final class Chest extends GameObject implements UIClickHandler { return new ColoredPixel(new TextColor.RGB(r, g, b)); } + /** + * {@inheritDoc} + */ @Override public boolean handleClick(MouseAction mouseAction) { int mouseX = mouseAction.getPosition().getColumn(); @@ -267,6 +308,11 @@ public final class Chest extends GameObject implements UIClickHandler { return true; } + /** + * Handles item removal from the chest. + * + * @param item The item removed + */ public void handleItemRemoval(GameItem item) { items.remove(item); diff --git a/game/src/main/java/cz/jzitnik/client/game/objects/DroppedItem.java b/game/src/main/java/cz/jzitnik/client/game/objects/DroppedItem.java index bd77d6a..6e9c580 100644 --- a/game/src/main/java/cz/jzitnik/client/game/objects/DroppedItem.java +++ b/game/src/main/java/cz/jzitnik/client/game/objects/DroppedItem.java @@ -17,6 +17,11 @@ import lombok.Setter; import java.awt.image.BufferedImage; import java.io.Serializable; +/** + * Represents an item dropped on the ground in a room. + * + * @author Jakub Žitník (jzitnik) + */ @Getter @RequiredArgsConstructor public final class DroppedItem implements Selectable, Serializable { @@ -26,6 +31,9 @@ public final class DroppedItem implements Selectable, Serializable { @Setter private boolean isSelected = false; + /** + * {@inheritDoc} + */ @Override public BufferedImage getTexture() { return item.getTexture(); @@ -37,6 +45,9 @@ public final class DroppedItem implements Selectable, Serializable { @InjectDependency private EventManager eventManager; + /** + * {@inheritDoc} + */ @Override public void interact() { if (!gameState.getPlayer().addItem(item)) { diff --git a/game/src/main/java/cz/jzitnik/client/game/objects/GameObject.java b/game/src/main/java/cz/jzitnik/client/game/objects/GameObject.java index 2f6ff9e..246439f 100644 --- a/game/src/main/java/cz/jzitnik/client/game/objects/GameObject.java +++ b/game/src/main/java/cz/jzitnik/client/game/objects/GameObject.java @@ -12,6 +12,11 @@ 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( diff --git a/game/src/main/java/cz/jzitnik/client/game/objects/Interactable.java b/game/src/main/java/cz/jzitnik/client/game/objects/Interactable.java index c050911..a6aaa0e 100644 --- a/game/src/main/java/cz/jzitnik/client/game/objects/Interactable.java +++ b/game/src/main/java/cz/jzitnik/client/game/objects/Interactable.java @@ -1,5 +1,13 @@ 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(); } diff --git a/game/src/main/java/cz/jzitnik/client/game/objects/UIClickHandler.java b/game/src/main/java/cz/jzitnik/client/game/objects/UIClickHandler.java index ecc365e..80c47d1 100644 --- a/game/src/main/java/cz/jzitnik/client/game/objects/UIClickHandler.java +++ b/game/src/main/java/cz/jzitnik/client/game/objects/UIClickHandler.java @@ -2,12 +2,36 @@ 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; } diff --git a/game/src/main/java/cz/jzitnik/client/game/setup/GameSetup.java b/game/src/main/java/cz/jzitnik/client/game/setup/GameSetup.java index 6cc964a..62612b2 100644 --- a/game/src/main/java/cz/jzitnik/client/game/setup/GameSetup.java +++ b/game/src/main/java/cz/jzitnik/client/game/setup/GameSetup.java @@ -20,6 +20,11 @@ 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 { @@ -35,6 +40,11 @@ public class GameSetup { @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)); diff --git a/game/src/main/java/cz/jzitnik/client/game/setup/scenes/DeathScene.java b/game/src/main/java/cz/jzitnik/client/game/setup/scenes/DeathScene.java index b536227..5307f2b 100644 --- a/game/src/main/java/cz/jzitnik/client/game/setup/scenes/DeathScene.java +++ b/game/src/main/java/cz/jzitnik/client/game/setup/scenes/DeathScene.java @@ -4,7 +4,15 @@ import cz.jzitnik.client.screens.DeathScreen; import cz.jzitnik.client.screens.Screen; import cz.jzitnik.client.screens.scenes.Scene; +/** + * Scene displayed when the player dies. + * + * @author Jakub Žitník (jzitnik) + */ public class DeathScene extends Scene { + /** + * Constructs a DeathScene. + */ public DeathScene() { super(new Screen[]{new DeathScreen()}, new OnEndAction.Repeat()); } diff --git a/game/src/main/java/cz/jzitnik/client/game/setup/scenes/GameMenuScene.java b/game/src/main/java/cz/jzitnik/client/game/setup/scenes/GameMenuScene.java index 990472b..1763b9e 100644 --- a/game/src/main/java/cz/jzitnik/client/game/setup/scenes/GameMenuScene.java +++ b/game/src/main/java/cz/jzitnik/client/game/setup/scenes/GameMenuScene.java @@ -14,11 +14,22 @@ import cz.jzitnik.client.sound.SoundPlayer; import cz.jzitnik.client.utils.DependencyManager; import cz.jzitnik.client.utils.events.EventManager; +/** + * Scene representing the main game menu. + * + * @author Jakub Žitník (jzitnik) + */ public class GameMenuScene extends Scene { + /** + * Screen for playing background audio in the menu. + */ private static class GameMenuAudioScreen extends Screen { protected final SoundPlayer soundPlayer = new SoundPlayer(); protected boolean play = true; + /** + * {@inheritDoc} + */ @Override public void fullRender() { // No render here just basic audio playback @@ -29,17 +40,26 @@ public class GameMenuScene extends Scene { }).start(); } + /** + * {@inheritDoc} + */ @Override public void handleMouseAction(MouseAction event) { } + /** + * {@inheritDoc} + */ @Override public void handleKeyboardAction(KeyboardPressEvent event) { } } + /** + * Screen for displaying the menu image. + */ private static final class ImageScene extends BasicImageScene { @InjectState private GameState gameState; @@ -49,11 +69,20 @@ public class GameMenuScene extends Scene { private final GameMenuAudioScreen gameMenuAudioScreen; + /** + * Constructs an ImageScene. + * + * @param filePath Path to image + * @param gameMenuAudioScreen The audio screen to control + */ public ImageScene(String filePath, GameMenuAudioScreen gameMenuAudioScreen) { super(filePath); this.gameMenuAudioScreen = gameMenuAudioScreen; } + /** + * {@inheritDoc} + */ @Override public void handleKeyboardAction(KeyboardPressEvent event) { if (event.getKeyStroke().getKeyType() == KeyType.Enter) { @@ -65,6 +94,11 @@ public class GameMenuScene extends Scene { } } + /** + * Constructs a GameMenuScene. + * + * @param dependencyManager The dependency manager + */ public GameMenuScene(DependencyManager dependencyManager) { GameMenuAudioScreen gameMenuScreen = new GameMenuAudioScreen(); ImageScene basicImageScene = new ImageScene("menu.png", gameMenuScreen); diff --git a/game/src/main/java/cz/jzitnik/client/game/setup/scenes/IntroScene.java b/game/src/main/java/cz/jzitnik/client/game/setup/scenes/IntroScene.java index 2c26a85..f2a00bb 100644 --- a/game/src/main/java/cz/jzitnik/client/game/setup/scenes/IntroScene.java +++ b/game/src/main/java/cz/jzitnik/client/game/setup/scenes/IntroScene.java @@ -5,7 +5,17 @@ import cz.jzitnik.client.screens.scenes.Scene; import cz.jzitnik.client.screens.scenes.VideoSceneWithAudio; import cz.jzitnik.client.utils.DependencyManager; +/** + * Scene representing the introduction of the game. + * + * @author Jakub Žitník (jzitnik) + */ public class IntroScene extends Scene { + /** + * Constructs an IntroScene. + * + * @param dependencyManager The dependency manager + */ public IntroScene(DependencyManager dependencyManager) { super( new Screen[]{ diff --git a/game/src/main/java/cz/jzitnik/client/game/setup/scenes/WinScene.java b/game/src/main/java/cz/jzitnik/client/game/setup/scenes/WinScene.java index 237e5c8..127a88d 100644 --- a/game/src/main/java/cz/jzitnik/client/game/setup/scenes/WinScene.java +++ b/game/src/main/java/cz/jzitnik/client/game/setup/scenes/WinScene.java @@ -4,7 +4,15 @@ import cz.jzitnik.client.screens.WinScreen; import cz.jzitnik.client.screens.Screen; import cz.jzitnik.client.screens.scenes.Scene; +/** + * Scene displayed when the game is won. + * + * @author Jakub Žitník (jzitnik) + */ public class WinScene extends Scene { + /** + * Constructs a WinScene. + */ public WinScene() { super(new Screen[]{new WinScreen()}, new OnEndAction.Repeat()); } diff --git a/game/src/main/java/cz/jzitnik/client/game/setup/scenes/connect/ServerChoose.java b/game/src/main/java/cz/jzitnik/client/game/setup/scenes/connect/ServerChoose.java index c1a3d53..60a0d56 100644 --- a/game/src/main/java/cz/jzitnik/client/game/setup/scenes/connect/ServerChoose.java +++ b/game/src/main/java/cz/jzitnik/client/game/setup/scenes/connect/ServerChoose.java @@ -32,8 +32,18 @@ import lombok.extern.slf4j.Slf4j; import java.awt.*; import java.io.IOException; +/** + * Scene for choosing a server and action (create/connect). + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j public class ServerChoose extends Scene { + /** + * Constructs a ServerChoose scene. + * + * @param dependencyManager The dependency manager + */ public ServerChoose(DependencyManager dependencyManager) { GameMenuAudioScreen gameMenuScreen = new GameMenuAudioScreen(); ServerSelector serverSelector = new ServerSelector(); @@ -44,10 +54,16 @@ public class ServerChoose extends Scene { dependencyManager.inject(serverSelector); } + /** + * Screen for menu background audio. + */ private static class GameMenuAudioScreen extends Screen { protected final SoundPlayer soundPlayer = new SoundPlayer(); protected boolean play = true; + /** + * {@inheritDoc} + */ @Override public void fullRender() { // No render here just basic audio playback @@ -58,17 +74,26 @@ public class ServerChoose extends Scene { }).start(); } + /** + * {@inheritDoc} + */ @Override public void handleMouseAction(MouseAction event) { } + /** + * {@inheritDoc} + */ @Override public void handleKeyboardAction(KeyboardPressEvent event) { } } + /** + * Screen for entering the server IP. + */ private static final class ServerSelector extends Screen { private final StringBuilder ipBuffer = new StringBuilder(); private boolean connecting = false; @@ -91,6 +116,11 @@ public class ServerChoose extends Scene { @InjectDependency private DependencyManager dependencyManager; + /** + * Renders the input field. + * + * @param refresh Whether to refresh the screen + */ private void renderInput(boolean refresh) { var tg = terminalState.getTextGraphics(); TerminalScreen screen = terminalState.getTerminalScreen(); @@ -132,6 +162,9 @@ public class ServerChoose extends Scene { } } + /** + * {@inheritDoc} + */ @Override public void fullRender() { TerminalScreen screen = terminalState.getTerminalScreen(); @@ -160,6 +193,9 @@ public class ServerChoose extends Scene { } } + /** + * {@inheritDoc} + */ @Override public void handleKeyboardAction(KeyboardPressEvent event) { if (connecting) { @@ -197,11 +233,17 @@ public class ServerChoose extends Scene { } } + /** + * {@inheritDoc} + */ @Override public void handleMouseAction(MouseAction event) { } } + /** + * Screen for selecting between creating or connecting to a world. + */ private static final class ActionSelector extends Screen { @InjectDependency private TextRenderer textRenderer; @@ -217,6 +259,9 @@ public class ServerChoose extends Scene { private int selectedIndex = -1; + /** + * {@inheritDoc} + */ @Override public void fullRender() { TerminalScreen screen = terminalState.getTerminalScreen(); @@ -250,6 +295,9 @@ public class ServerChoose extends Scene { private static final int BUTTON_COUNT = 2; private static final int BUTTONS_HEIGHT = BUTTON_HEIGHT * BUTTON_COUNT + (BUTTON_COUNT - 1) * BUTTON_GAP; + /** + * Renders action buttons. + */ private void renderButtons() { var tg = terminalState.getTextGraphics(); TerminalSize terminalSize = terminalState.getTerminalScreen().getTerminalSize(); @@ -273,6 +321,9 @@ public class ServerChoose extends Scene { render(button.render("Connect to an existing world", selectedIndex == 1), BUTTON_PAD_X, BUTTON_PAD_Y + (BUTTON_HEIGHT + BUTTON_GAP), tg); } + /** + * {@inheritDoc} + */ @Override public void handleMouseAction(MouseAction event) { TerminalSize terminalSize = terminalState.getTerminalScreen().getTerminalSize(); @@ -318,6 +369,9 @@ public class ServerChoose extends Scene { } } + /** + * Refreshes the screen. + */ private void refresh() { try { terminalState.getTerminalScreen().refresh(com.googlecode.lanterna.screen.Screen.RefreshType.DELTA); @@ -326,6 +380,9 @@ public class ServerChoose extends Scene { } } + /** + * {@inheritDoc} + */ @Override public void handleKeyboardAction(KeyboardPressEvent event) { @@ -333,6 +390,9 @@ public class ServerChoose extends Scene { } + /** + * Screen for entering the world password. + */ private static final class ConnectWorld extends Screen { private final StringBuilder passBuffer = new StringBuilder(); private boolean connecting = false; @@ -355,6 +415,11 @@ public class ServerChoose extends Scene { @InjectDependency private DependencyManager dependencyManager; + /** + * Renders the input field. + * + * @param refresh Whether to refresh the screen + */ private void renderInput(boolean refresh) { var tg = terminalState.getTextGraphics(); TerminalScreen screen = terminalState.getTerminalScreen(); @@ -396,6 +461,9 @@ public class ServerChoose extends Scene { } } + /** + * {@inheritDoc} + */ @Override public void fullRender() { TerminalScreen screen = terminalState.getTerminalScreen(); @@ -424,6 +492,9 @@ public class ServerChoose extends Scene { } } + /** + * {@inheritDoc} + */ @Override public void handleKeyboardAction(KeyboardPressEvent event) { if (connecting) { @@ -454,11 +525,22 @@ public class ServerChoose extends Scene { } } + /** + * {@inheritDoc} + */ @Override public void handleMouseAction(MouseAction event) { } } + /** + * Internal helper to render an AlphaPixel buffer to TextGraphics. + * + * @param buffer The pixel buffer + * @param padX X padding + * @param padY Y padding + * @param tg The TextGraphics context + */ private static void render(AlphaPixel[][] buffer, int padX, int padY, TextGraphics tg) { for (int y = 0; y < buffer.length; y += 2) { for (int x = 0; x < buffer[y].length; x++) { diff --git a/game/src/main/java/cz/jzitnik/client/game/utils/Renderable.java b/game/src/main/java/cz/jzitnik/client/game/utils/Renderable.java index b1f4d87..3a32633 100644 --- a/game/src/main/java/cz/jzitnik/client/game/utils/Renderable.java +++ b/game/src/main/java/cz/jzitnik/client/game/utils/Renderable.java @@ -2,6 +2,16 @@ package cz.jzitnik.client.game.utils; import java.awt.image.BufferedImage; +/** + * Interface for objects that can be rendered. + * + * @author Jakub Žitník (jzitnik) + */ public interface Renderable { + /** + * Gets the texture to render. + * + * @return BufferedImage texture + */ BufferedImage getTexture(); } diff --git a/game/src/main/java/cz/jzitnik/client/game/utils/Selectable.java b/game/src/main/java/cz/jzitnik/client/game/utils/Selectable.java index a64f636..e86a830 100644 --- a/game/src/main/java/cz/jzitnik/client/game/utils/Selectable.java +++ b/game/src/main/java/cz/jzitnik/client/game/utils/Selectable.java @@ -5,12 +5,45 @@ import cz.jzitnik.common.models.coordinates.RoomCords; import java.awt.image.BufferedImage; +/** + * Interface for objects that can be selected and interacted with. + * + * @author Jakub Žitník (jzitnik) + */ public interface Selectable extends Interactable { + /** + * Checks if the object is currently selected. + * + * @return true if selected + */ boolean isSelected(); + + /** + * Sets the selection state of the object. + * + * @param selected Selection state + */ void setSelected(boolean selected); + + /** + * Gets the texture of the object. + * + * @return BufferedImage texture + */ BufferedImage getTexture(); + + /** + * Gets the coordinates of the object. + * + * @return RoomCords instance + */ RoomCords getCords(); + /** + * Checks if the object is selectable. + * + * @return true by default + */ default boolean isSelectable() { return true; } diff --git a/game/src/main/java/cz/jzitnik/client/screens/DeathScreen.java b/game/src/main/java/cz/jzitnik/client/screens/DeathScreen.java index a151fa5..9227792 100644 --- a/game/src/main/java/cz/jzitnik/client/screens/DeathScreen.java +++ b/game/src/main/java/cz/jzitnik/client/screens/DeathScreen.java @@ -11,10 +11,18 @@ import cz.jzitnik.client.states.TerminalState; import java.io.IOException; +/** + * Screen displayed when the player dies. + * + * @author Jakub Žitník (jzitnik) + */ public class DeathScreen extends Screen { @InjectState private TerminalState terminalState; + /** + * {@inheritDoc} + */ @Override public void fullRender() { TerminalScreen screen = terminalState.getTerminalScreen(); @@ -36,10 +44,16 @@ public class DeathScreen extends Screen { } } + /** + * {@inheritDoc} + */ @Override public void handleMouseAction(MouseAction event) { } + /** + * {@inheritDoc} + */ @Override public void handleKeyboardAction(KeyboardPressEvent event) { } diff --git a/game/src/main/java/cz/jzitnik/client/screens/Screen.java b/game/src/main/java/cz/jzitnik/client/screens/Screen.java index 68eae0e..2daf063 100644 --- a/game/src/main/java/cz/jzitnik/client/screens/Screen.java +++ b/game/src/main/java/cz/jzitnik/client/screens/Screen.java @@ -3,8 +3,28 @@ package cz.jzitnik.client.screens; import cz.jzitnik.client.events.KeyboardPressEvent; import cz.jzitnik.client.events.MouseAction; +/** + * Base abstract class for all game screens. + * + * @author Jakub Žitník (jzitnik) + */ public abstract class Screen { + /** + * Performs a full render of the screen. + */ public abstract void fullRender(); + + /** + * Handles mouse actions on the screen. + * + * @param event The mouse action event + */ public abstract void handleMouseAction(MouseAction event); + + /** + * Handles keyboard actions on the screen. + * + * @param event The keyboard press event + */ public abstract void handleKeyboardAction(KeyboardPressEvent event); } diff --git a/game/src/main/java/cz/jzitnik/client/screens/VideoPlayScreen.java b/game/src/main/java/cz/jzitnik/client/screens/VideoPlayScreen.java index b330ad1..05f34d6 100644 --- a/game/src/main/java/cz/jzitnik/client/screens/VideoPlayScreen.java +++ b/game/src/main/java/cz/jzitnik/client/screens/VideoPlayScreen.java @@ -18,6 +18,11 @@ import java.io.InputStream; import java.nio.file.Files; import java.nio.file.StandardCopyOption; +/** + * Abstract screen for playing videos using FFmpeg. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j public abstract class VideoPlayScreen extends Screen { @InjectDependency @@ -29,10 +34,18 @@ public abstract class VideoPlayScreen extends Screen { private final String videoPath; protected boolean isRenderedAlready; + /** + * Constructs a VideoPlayScreen. + * + * @param videoPath Path to the video resource + */ public VideoPlayScreen(String videoPath) { this.videoPath = videoPath; } + /** + * {@inheritDoc} + */ @Override public void fullRender() { if (!isRenderedAlready) { @@ -41,6 +54,9 @@ public abstract class VideoPlayScreen extends Screen { } } + /** + * Internal method to render the video frames. + */ protected final void render() { File tempVideo = null; try (InputStream resource = resourceManager.getResourceAsStream(videoPath)) { @@ -143,6 +159,12 @@ public abstract class VideoPlayScreen extends Screen { } } + /** + * Converts an RGB integer to a TextColor. + * + * @param rgb RGB value + * @return TextColor instance + */ private TextColor.RGB toColor(int rgb) { int r = (rgb >> 16) & 0xFF; int g = (rgb >> 8) & 0xFF; diff --git a/game/src/main/java/cz/jzitnik/client/screens/WinScreen.java b/game/src/main/java/cz/jzitnik/client/screens/WinScreen.java index 1bee99a..f4688e6 100644 --- a/game/src/main/java/cz/jzitnik/client/screens/WinScreen.java +++ b/game/src/main/java/cz/jzitnik/client/screens/WinScreen.java @@ -11,10 +11,18 @@ import cz.jzitnik.client.states.TerminalState; import java.io.IOException; +/** + * Screen displayed when the player wins. + * + * @author Jakub Žitník (jzitnik) + */ public class WinScreen extends Screen { @InjectState private TerminalState terminalState; + /** + * {@inheritDoc} + */ @Override public void fullRender() { TerminalScreen screen = terminalState.getTerminalScreen(); @@ -36,10 +44,16 @@ public class WinScreen extends Screen { } } + /** + * {@inheritDoc} + */ @Override public void handleMouseAction(MouseAction event) { } + /** + * {@inheritDoc} + */ @Override public void handleKeyboardAction(KeyboardPressEvent event) { } diff --git a/game/src/main/java/cz/jzitnik/client/screens/scenes/BasicImageScene.java b/game/src/main/java/cz/jzitnik/client/screens/scenes/BasicImageScene.java index 386c876..1e868dd 100644 --- a/game/src/main/java/cz/jzitnik/client/screens/scenes/BasicImageScene.java +++ b/game/src/main/java/cz/jzitnik/client/screens/scenes/BasicImageScene.java @@ -13,6 +13,11 @@ import cz.jzitnik.client.states.TerminalState; import java.awt.image.BufferedImage; import java.io.IOException; +/** + * A simple scene that displays a single image. + * + * @author Jakub Žitník (jzitnik) + */ public class BasicImageScene extends Screen { @InjectDependency private ResourceManager resourceManager; @@ -22,10 +27,18 @@ public class BasicImageScene extends Screen { private final String imagePath; + /** + * Constructs a BasicImageScene. + * + * @param filePath Path to the image resource + */ public BasicImageScene(String filePath) { imagePath = filePath; } + /** + * {@inheritDoc} + */ @Override public void fullRender() { BufferedImage image = resourceManager.getResource(imagePath); @@ -83,6 +96,12 @@ public class BasicImageScene extends Screen { } + /** + * Converts an RGB integer to a TextColor. + * + * @param rgb RGB value + * @return TextColor instance + */ private TextColor.RGB toColor(int rgb) { int r = (rgb >> 16) & 0xFF; int g = (rgb >> 8) & 0xFF; @@ -90,11 +109,17 @@ public class BasicImageScene extends Screen { return new TextColor.RGB(r, g, b); } + /** + * {@inheritDoc} + */ @Override public void handleMouseAction(MouseAction event) { } + /** + * {@inheritDoc} + */ @Override public void handleKeyboardAction(KeyboardPressEvent event) { diff --git a/game/src/main/java/cz/jzitnik/client/screens/scenes/BasicVideoScene.java b/game/src/main/java/cz/jzitnik/client/screens/scenes/BasicVideoScene.java index 3f6c68c..676704a 100644 --- a/game/src/main/java/cz/jzitnik/client/screens/scenes/BasicVideoScene.java +++ b/game/src/main/java/cz/jzitnik/client/screens/scenes/BasicVideoScene.java @@ -4,15 +4,31 @@ import cz.jzitnik.client.events.KeyboardPressEvent; import cz.jzitnik.client.events.MouseAction; import cz.jzitnik.client.screens.VideoPlayScreen; +/** + * A basic video playback scene. + * + * @author Jakub Žitník (jzitnik) + */ public final class BasicVideoScene extends VideoPlayScreen { + /** + * Constructs a BasicVideoScene. + * + * @param videoPath Path to video + */ public BasicVideoScene(String videoPath) { super(videoPath); } + /** + * {@inheritDoc} + */ @Override public void handleMouseAction(MouseAction event) { } + /** + * {@inheritDoc} + */ @Override public void handleKeyboardAction(KeyboardPressEvent event) { } diff --git a/game/src/main/java/cz/jzitnik/client/screens/scenes/Scene.java b/game/src/main/java/cz/jzitnik/client/screens/scenes/Scene.java index 24affa0..5802a55 100644 --- a/game/src/main/java/cz/jzitnik/client/screens/scenes/Scene.java +++ b/game/src/main/java/cz/jzitnik/client/screens/scenes/Scene.java @@ -12,6 +12,11 @@ import cz.jzitnik.client.utils.events.EventManager; import lombok.AllArgsConstructor; import lombok.Getter; +/** + * Abstract class representing a sequence of screens (parts). + * + * @author Jakub Žitník (jzitnik) + */ public abstract class Scene extends Screen { private final Screen[] parts; private Screen currentPart; @@ -28,11 +33,18 @@ public abstract class Scene extends Screen { @InjectDependency private EventManager eventManager; + /** + * Base class for actions to perform when a scene ends. + */ public static class OnEndAction { + /** Switch back to game view. */ public static class SwitchToGame extends OnEndAction {} + /** Repeat the scene. */ public static class Repeat extends OnEndAction {} + /** Do nothing. */ public static class None extends OnEndAction {} + /** Switch to a different screen. */ @Getter @AllArgsConstructor public static class SwitchToScreen extends OnEndAction { @@ -40,12 +52,21 @@ public abstract class Scene extends Screen { } } + /** + * Constructs a Scene. + * + * @param parts The screens that make up this scene + * @param onEndAction The action to perform when finished + */ public Scene(Screen[] parts, OnEndAction onEndAction) { this.parts = parts; this.currentPart = parts[0]; this.onEndAction = onEndAction; } + /** + * {@inheritDoc} + */ @Override public void fullRender() { if (!isRenderedAlready) { @@ -56,6 +77,9 @@ public abstract class Scene extends Screen { } } + /** + * Internal method to render scene parts sequentially. + */ private void render() { while (currentPart != null) { dependencyManager.inject(currentPart); @@ -81,16 +105,25 @@ public abstract class Scene extends Screen { } } + /** + * Switches from the scene back to the main game. + */ protected void switchToGame() { gameState.setScreen(null); eventManager.emitEvent(new FullRoomDraw(true)); } + /** + * {@inheritDoc} + */ @Override public void handleMouseAction(MouseAction event) { currentPart.handleMouseAction(event); } + /** + * {@inheritDoc} + */ @Override public void handleKeyboardAction(KeyboardPressEvent event) { currentPart.handleKeyboardAction(event); diff --git a/game/src/main/java/cz/jzitnik/client/screens/scenes/VideoSceneWithAudio.java b/game/src/main/java/cz/jzitnik/client/screens/scenes/VideoSceneWithAudio.java index 94b1996..16fb27f 100644 --- a/game/src/main/java/cz/jzitnik/client/screens/scenes/VideoSceneWithAudio.java +++ b/game/src/main/java/cz/jzitnik/client/screens/scenes/VideoSceneWithAudio.java @@ -6,16 +6,30 @@ import cz.jzitnik.client.screens.VideoPlayScreen; import cz.jzitnik.client.sound.SoundPlayer; import lombok.extern.slf4j.Slf4j; +/** + * A video scene that also plays audio. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j public final class VideoSceneWithAudio extends VideoPlayScreen { private final SoundPlayer soundPlayer = new SoundPlayer(); private final String audioPath; + /** + * Constructs a VideoSceneWithAudio. + * + * @param videoPath Path to video + * @param audioPath Path to audio + */ public VideoSceneWithAudio(String videoPath, String audioPath) { super(videoPath); this.audioPath = audioPath; } + /** + * {@inheritDoc} + */ @Override public void fullRender() { if (!isRenderedAlready) { @@ -26,15 +40,24 @@ public final class VideoSceneWithAudio extends VideoPlayScreen { } } + /** + * Starts playing the audio in a separate thread. + */ private void playSound() { new Thread(() -> soundPlayer.playSound(audioPath, 100, 100)).start(); } + /** + * {@inheritDoc} + */ @Override public void handleMouseAction(MouseAction event) { } + /** + * {@inheritDoc} + */ @Override public void handleKeyboardAction(KeyboardPressEvent event) { diff --git a/game/src/main/java/cz/jzitnik/client/socket/AbstractSocketEventHandler.java b/game/src/main/java/cz/jzitnik/client/socket/AbstractSocketEventHandler.java index 223136f..73a4488 100644 --- a/game/src/main/java/cz/jzitnik/client/socket/AbstractSocketEventHandler.java +++ b/game/src/main/java/cz/jzitnik/client/socket/AbstractSocketEventHandler.java @@ -2,6 +2,17 @@ package cz.jzitnik.client.socket; import cz.jzitnik.common.socket.SocketMessage; +/** + * Base abstract class for all client-side socket event handlers. + * + * @param The type of SocketMessage this handler handles + * @author Jakub Žitník (jzitnik) + */ public abstract class AbstractSocketEventHandler { + /** + * Handles the received socket event. + * + * @param event The event message + */ public abstract void handle(T event); } diff --git a/game/src/main/java/cz/jzitnik/client/socket/Client.java b/game/src/main/java/cz/jzitnik/client/socket/Client.java index 5ea3731..03aedfe 100644 --- a/game/src/main/java/cz/jzitnik/client/socket/Client.java +++ b/game/src/main/java/cz/jzitnik/client/socket/Client.java @@ -10,6 +10,11 @@ import java.io.*; import java.net.URI; import java.nio.ByteBuffer; +/** + * WebSocket client for handling server communication. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @Dependency @ClientEndpoint @@ -19,11 +24,21 @@ public class Client { @InjectDependency private SocketEventManager socketEventManager; + /** + * Called when the connection is opened. + * + * @param session The WebSocket session + */ @OnOpen public void onOpen(Session session) { this.session = session; } + /** + * Called when a binary message is received. + * + * @param buffer The message buffer + */ @OnMessage public void onMessage(ByteBuffer buffer) { try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(buffer.array()))) { @@ -34,6 +49,12 @@ public class Client { } } + /** + * Sends a socket message to the server. + * + * @param message The message to send + * @throws IOException If an I/O error occurs + */ public void send(SocketMessage message) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); @@ -43,6 +64,13 @@ public class Client { session.getBasicRemote().sendBinary(ByteBuffer.wrap(baos.toByteArray())); } + /** + * Connects to the server at the specified IP. + * + * @param ip The server IP address + * @throws DeploymentException If deployment fails + * @throws IOException If an I/O error occurs + */ public void connect(String ip) throws DeploymentException, IOException { WebSocketContainer container = ContainerProvider.getWebSocketContainer(); container.connectToServer(this, URI.create(String.format("ws://%s:8025/ws", ip))); diff --git a/game/src/main/java/cz/jzitnik/client/socket/SocketEventManager.java b/game/src/main/java/cz/jzitnik/client/socket/SocketEventManager.java index 154802f..c16886a 100644 --- a/game/src/main/java/cz/jzitnik/client/socket/SocketEventManager.java +++ b/game/src/main/java/cz/jzitnik/client/socket/SocketEventManager.java @@ -18,6 +18,11 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; +/** + * Manages dispatching of socket events received from the server. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @Dependency public class SocketEventManager extends Thread { @@ -33,10 +38,21 @@ public class SocketEventManager extends Thread { @InjectState private RunningState runningState; + /** + * Emits a socket event to be handled. + * + * @param event The socket event message + */ public void emitEvent(SocketMessage event) { eventQueue.add(event); } + /** + * Constructs a SocketEventManager and discovers handlers. + * + * @param reflections Reflections instance + * @param dependencyManager Dependency manager + */ public SocketEventManager(Reflections reflections, DependencyManager dependencyManager) { this.dependencyManager = dependencyManager; setDaemon(true); @@ -55,6 +71,9 @@ public class SocketEventManager extends Thread { } } + /** + * Main loop for processing socket events. + */ @Override public void run() { for (Object instance : handlers.values()) { @@ -80,6 +99,11 @@ public class SocketEventManager extends Thread { return (AbstractSocketEventHandler) handlers.get(type); } + /** + * Internal helper to handle a socket event using its handler. + * + * @param event The event to handle + */ @SuppressWarnings("unchecked") private void handleEvent(SocketMessage event) { eventExecutor.submit(() -> { diff --git a/game/src/main/java/cz/jzitnik/client/socket/events/ConnectGameHandler.java b/game/src/main/java/cz/jzitnik/client/socket/events/ConnectGameHandler.java index 37a1343..71ef9ee 100644 --- a/game/src/main/java/cz/jzitnik/client/socket/events/ConnectGameHandler.java +++ b/game/src/main/java/cz/jzitnik/client/socket/events/ConnectGameHandler.java @@ -13,6 +13,11 @@ import cz.jzitnik.client.utils.events.EventManager; import cz.jzitnik.common.socket.messages.game.connection.ConnectToAGameResponse; import lombok.extern.slf4j.Slf4j; +/** + * Handler for the ConnectToAGameResponse socket event. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @SocketEventHandler(ConnectToAGameResponse.class) public class ConnectGameHandler extends AbstractSocketEventHandler { @@ -23,6 +28,11 @@ public class ConnectGameHandler extends AbstractSocketEventHandler { @@ -22,6 +27,11 @@ public class CreateGameHandler extends AbstractSocketEventHandler { @@ -18,6 +23,11 @@ public class GameWinHandler extends AbstractSocketEventHandler { @InjectDependency private cz.jzitnik.client.utils.roomtasks.RoomTaskScheduler roomTaskScheduler; + /** + * Handles the GameWin event by showing the win scene. + * + * @param event The GameWin event + */ @Override public void handle(GameWin event) { log.debug("Game won!"); diff --git a/game/src/main/java/cz/jzitnik/client/socket/events/ItemTookFromChestHandler.java b/game/src/main/java/cz/jzitnik/client/socket/events/ItemTookFromChestHandler.java index 9925d22..fcf2edc 100644 --- a/game/src/main/java/cz/jzitnik/client/socket/events/ItemTookFromChestHandler.java +++ b/game/src/main/java/cz/jzitnik/client/socket/events/ItemTookFromChestHandler.java @@ -10,11 +10,21 @@ import cz.jzitnik.client.game.objects.GameObject; import cz.jzitnik.client.socket.AbstractSocketEventHandler; import cz.jzitnik.common.socket.messages.items.ItemTookFromChest; +/** + * Handler for the ItemTookFromChest socket event. + * + * @author Jakub Žitník (jzitnik) + */ @SocketEventHandler(ItemTookFromChest.class) public class ItemTookFromChestHandler extends AbstractSocketEventHandler { @InjectState private GameState gameState; + /** + * Handles the ItemTookFromChest event by removing the item from the chest in the local state. + * + * @param event The ItemTookFromChest event + */ @Override public void handle(ItemTookFromChest event) { for (GameRoom room : gameState.getAllRooms()) { diff --git a/game/src/main/java/cz/jzitnik/client/socket/events/MovePlayerRoomResponseHandler.java b/game/src/main/java/cz/jzitnik/client/socket/events/MovePlayerRoomResponseHandler.java index 2b9f166..f3327b3 100644 --- a/game/src/main/java/cz/jzitnik/client/socket/events/MovePlayerRoomResponseHandler.java +++ b/game/src/main/java/cz/jzitnik/client/socket/events/MovePlayerRoomResponseHandler.java @@ -12,6 +12,11 @@ import cz.jzitnik.common.socket.messages.room.MovePlayerRoomResponse; import java.util.Set; +/** + * Handler for the MovePlayerRoomResponse socket event. + * + * @author Jakub Žitník (jzitnik) + */ @SocketEventHandler(MovePlayerRoomResponse.class) public class MovePlayerRoomResponseHandler extends AbstractSocketEventHandler { @InjectDependency @@ -20,6 +25,11 @@ public class MovePlayerRoomResponseHandler extends AbstractSocketEventHandler ids = event.getIds(); diff --git a/game/src/main/java/cz/jzitnik/client/socket/events/PlayerArrivalChangeHandler.java b/game/src/main/java/cz/jzitnik/client/socket/events/PlayerArrivalChangeHandler.java index ac5bca6..59f0e3a 100644 --- a/game/src/main/java/cz/jzitnik/client/socket/events/PlayerArrivalChangeHandler.java +++ b/game/src/main/java/cz/jzitnik/client/socket/events/PlayerArrivalChangeHandler.java @@ -24,6 +24,11 @@ import lombok.extern.slf4j.Slf4j; import java.awt.image.BufferedImage; +/** + * Handler for the PlayerArrivalChange socket event. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @SocketEventHandler(PlayerArrivalChange.class) public class PlayerArrivalChangeHandler extends AbstractSocketEventHandler { @@ -45,6 +50,11 @@ public class PlayerArrivalChangeHandler extends AbstractSocketEventHandler { @@ -22,6 +27,11 @@ public class PlayerDeathHandler extends AbstractSocketEventHandler @InjectDependency private cz.jzitnik.client.utils.roomtasks.RoomTaskScheduler roomTaskScheduler; + /** + * Handles the PlayerDeath event by showing the death scene. + * + * @param event The PlayerDeath event + */ @Override public void handle(PlayerDeath event) { log.debug("Player death: {}", event.playerId()); diff --git a/game/src/main/java/cz/jzitnik/client/socket/events/PlayerDisconnectedHandler.java b/game/src/main/java/cz/jzitnik/client/socket/events/PlayerDisconnectedHandler.java index bed6d39..7bf9acc 100644 --- a/game/src/main/java/cz/jzitnik/client/socket/events/PlayerDisconnectedHandler.java +++ b/game/src/main/java/cz/jzitnik/client/socket/events/PlayerDisconnectedHandler.java @@ -6,11 +6,21 @@ import cz.jzitnik.client.game.GameState; import cz.jzitnik.client.socket.AbstractSocketEventHandler; import cz.jzitnik.common.socket.messages.player.PlayerDisconnected; +/** + * Handler for the PlayerDisconnected socket event. + * + * @author Jakub Žitník (jzitnik) + */ @SocketEventHandler(PlayerDisconnected.class) public class PlayerDisconnectedHandler extends AbstractSocketEventHandler { @InjectState private GameState gameState; + /** + * Handles the event when a player disconnects from the game. + * + * @param event The PlayerDisconnected event + */ @Override public void handle(PlayerDisconnected event) { gameState.getAllOtherPlayers().removeIf(player -> player.getId() == event.playerId()); diff --git a/game/src/main/java/cz/jzitnik/client/socket/events/PlayerJoinedHandler.java b/game/src/main/java/cz/jzitnik/client/socket/events/PlayerJoinedHandler.java index f01d126..992c28b 100644 --- a/game/src/main/java/cz/jzitnik/client/socket/events/PlayerJoinedHandler.java +++ b/game/src/main/java/cz/jzitnik/client/socket/events/PlayerJoinedHandler.java @@ -8,12 +8,22 @@ import cz.jzitnik.client.socket.AbstractSocketEventHandler; import cz.jzitnik.common.socket.messages.player.PlayerJoined; import lombok.extern.slf4j.Slf4j; +/** + * Handler for the PlayerJoined socket event. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @SocketEventHandler(PlayerJoined.class) public class PlayerJoinedHandler extends AbstractSocketEventHandler { @InjectState private GameState gameState; + /** + * Handles the event when a new player joins the game. + * + * @param event The PlayerJoined event + */ @Override public void handle(PlayerJoined event) { log.debug("Player joined: {}", event.playerCreation().getId()); diff --git a/game/src/main/java/cz/jzitnik/client/socket/events/PlayerMovedInUrRoomHandler.java b/game/src/main/java/cz/jzitnik/client/socket/events/PlayerMovedInUrRoomHandler.java index 84a15a6..3fea964 100644 --- a/game/src/main/java/cz/jzitnik/client/socket/events/PlayerMovedInUrRoomHandler.java +++ b/game/src/main/java/cz/jzitnik/client/socket/events/PlayerMovedInUrRoomHandler.java @@ -24,6 +24,11 @@ import lombok.extern.slf4j.Slf4j; import java.awt.image.BufferedImage; +/** + * Handler for the PlayerMovedInUrRoom socket event. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @SocketEventHandler(PlayerMovedInUrRoom.class) public class PlayerMovedInUrRoomHandler extends AbstractSocketEventHandler { @@ -45,6 +50,11 @@ public class PlayerMovedInUrRoomHandler extends AbstractSocketEventHandler { + /** + * Handles the Test event. + * + * @param event The Test event + */ @Override public void handle(Test event) { log.debug("Got test: {}", event); diff --git a/game/src/main/java/cz/jzitnik/client/sound/SoundPlayer.java b/game/src/main/java/cz/jzitnik/client/sound/SoundPlayer.java index 293a38f..c23ae46 100644 --- a/game/src/main/java/cz/jzitnik/client/sound/SoundPlayer.java +++ b/game/src/main/java/cz/jzitnik/client/sound/SoundPlayer.java @@ -7,10 +7,22 @@ import java.util.concurrent.atomic.AtomicReference; import lombok.extern.slf4j.Slf4j; +/** + * Utility for playing audio files. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j public class SoundPlayer { private final AtomicReference currentLine = new AtomicReference<>(); + /** + * Plays a sound file with specified volume levels. + * + * @param filePath Path to the .ogg file + * @param backendVolume Volume level from the backend (0-100) + * @param masterVolume Master volume level (0-100) + */ public void playSound(String filePath, int backendVolume, int masterVolume) { long threadId = Thread.currentThread().threadId(); diff --git a/game/src/main/java/cz/jzitnik/client/states/DialogState.java b/game/src/main/java/cz/jzitnik/client/states/DialogState.java index 4e36f41..a6b5415 100644 --- a/game/src/main/java/cz/jzitnik/client/states/DialogState.java +++ b/game/src/main/java/cz/jzitnik/client/states/DialogState.java @@ -4,6 +4,11 @@ import cz.jzitnik.client.annotations.State; import cz.jzitnik.client.game.dialog.Dialog; import lombok.Data; +/** + * Holds the state of active dialogs. + * + * @author Jakub Žitník (jzitnik) + */ @State @Data public class DialogState { diff --git a/game/src/main/java/cz/jzitnik/client/states/MicrophoneState.java b/game/src/main/java/cz/jzitnik/client/states/MicrophoneState.java index 1c540e0..361d572 100644 --- a/game/src/main/java/cz/jzitnik/client/states/MicrophoneState.java +++ b/game/src/main/java/cz/jzitnik/client/states/MicrophoneState.java @@ -3,6 +3,11 @@ package cz.jzitnik.client.states; import cz.jzitnik.client.annotations.State; import lombok.Data; +/** + * Holds the state of the microphone input. + * + * @author Jakub Žitník (jzitnik) + */ @Data @State public class MicrophoneState { diff --git a/game/src/main/java/cz/jzitnik/client/states/PlayerConfig.java b/game/src/main/java/cz/jzitnik/client/states/PlayerConfig.java index 38d1595..5d7f65d 100644 --- a/game/src/main/java/cz/jzitnik/client/states/PlayerConfig.java +++ b/game/src/main/java/cz/jzitnik/client/states/PlayerConfig.java @@ -2,6 +2,11 @@ package cz.jzitnik.client.states; import cz.jzitnik.client.annotations.State; +/** + * Holds player configuration settings like volume. + * + * @author Jakub Žitník (jzitnik) + */ @State public class PlayerConfig { private int masterVolume = 100; diff --git a/game/src/main/java/cz/jzitnik/client/states/PlayerMovementState.java b/game/src/main/java/cz/jzitnik/client/states/PlayerMovementState.java index 6f5b966..f66760f 100644 --- a/game/src/main/java/cz/jzitnik/client/states/PlayerMovementState.java +++ b/game/src/main/java/cz/jzitnik/client/states/PlayerMovementState.java @@ -5,6 +5,11 @@ import lombok.Data; import java.util.concurrent.ScheduledFuture; +/** + * Holds the state related to player movement and stamina. + * + * @author Jakub Žitník (jzitnik) + */ @Data @State public class PlayerMovementState { diff --git a/game/src/main/java/cz/jzitnik/client/states/RenderState.java b/game/src/main/java/cz/jzitnik/client/states/RenderState.java index 85e5a12..2c29b19 100644 --- a/game/src/main/java/cz/jzitnik/client/states/RenderState.java +++ b/game/src/main/java/cz/jzitnik/client/states/RenderState.java @@ -4,6 +4,11 @@ import cz.jzitnik.client.annotations.State; import lombok.Getter; import lombok.Setter; +/** + * Holds the state of the rendering system. + * + * @author Jakub Žitník (jzitnik) + */ @State @Getter @Setter diff --git a/game/src/main/java/cz/jzitnik/client/states/RunningState.java b/game/src/main/java/cz/jzitnik/client/states/RunningState.java index f52a53f..185f113 100644 --- a/game/src/main/java/cz/jzitnik/client/states/RunningState.java +++ b/game/src/main/java/cz/jzitnik/client/states/RunningState.java @@ -3,6 +3,11 @@ package cz.jzitnik.client.states; import cz.jzitnik.client.annotations.State; import lombok.Data; +/** + * Holds the running state of the application. + * + * @author Jakub Žitník (jzitnik) + */ @Data @State public class RunningState { diff --git a/game/src/main/java/cz/jzitnik/client/states/ScreenBuffer.java b/game/src/main/java/cz/jzitnik/client/states/ScreenBuffer.java index 17de964..0e1fbb1 100644 --- a/game/src/main/java/cz/jzitnik/client/states/ScreenBuffer.java +++ b/game/src/main/java/cz/jzitnik/client/states/ScreenBuffer.java @@ -5,6 +5,11 @@ import cz.jzitnik.client.ui.pixels.AlphaPixel; import cz.jzitnik.client.ui.pixels.Pixel; import lombok.Data; +/** + * Holds the buffers used for rendering the game screen. + * + * @author Jakub Žitník (jzitnik) + */ @Data @State public class ScreenBuffer { diff --git a/game/src/main/java/cz/jzitnik/client/states/TerminalState.java b/game/src/main/java/cz/jzitnik/client/states/TerminalState.java index 4cfdc41..b1974aa 100644 --- a/game/src/main/java/cz/jzitnik/client/states/TerminalState.java +++ b/game/src/main/java/cz/jzitnik/client/states/TerminalState.java @@ -5,6 +5,11 @@ import com.googlecode.lanterna.screen.TerminalScreen; import cz.jzitnik.client.annotations.State; import lombok.Data; +/** + * Holds the state of the terminal and its graphics context. + * + * @author Jakub Žitník (jzitnik) + */ @State @Data public class TerminalState { diff --git a/game/src/main/java/cz/jzitnik/client/tasks/StaminaIncreaseTask.java b/game/src/main/java/cz/jzitnik/client/tasks/StaminaIncreaseTask.java index f1b49fb..c164d95 100644 --- a/game/src/main/java/cz/jzitnik/client/tasks/StaminaIncreaseTask.java +++ b/game/src/main/java/cz/jzitnik/client/tasks/StaminaIncreaseTask.java @@ -16,6 +16,11 @@ import cz.jzitnik.client.utils.events.EventManager; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +/** + * Background task that checks if stamina should be increased. + * + * @author Jakub Žitník (jzitnik) + */ @ScheduledTask(rate = 1, rateUnit = TimeUnit.SECONDS) public class StaminaIncreaseTask implements Runnable { @InjectState @@ -33,6 +38,9 @@ public class StaminaIncreaseTask implements Runnable { @InjectConfig private PlayerConfig playerConfig; + /** + * {@inheritDoc} + */ @Override public void run() { if (playerMovementState.getStaminaIncreaseSchedule() != null) { @@ -47,6 +55,9 @@ public class StaminaIncreaseTask implements Runnable { } } + /** + * Logic to increase stamina at a fixed rate. + */ public static class IncreaseStamina implements Runnable { @InjectState private PlayerMovementState playerMovementState; @@ -60,6 +71,9 @@ public class StaminaIncreaseTask implements Runnable { @InjectDependency private EventManager eventManager; + /** + * {@inheritDoc} + */ @Override public void run() { long nowTime = System.currentTimeMillis(); diff --git a/game/src/main/java/cz/jzitnik/client/threads/MicrophoneThread.java b/game/src/main/java/cz/jzitnik/client/threads/MicrophoneThread.java index 54b8393..1047195 100644 --- a/game/src/main/java/cz/jzitnik/client/threads/MicrophoneThread.java +++ b/game/src/main/java/cz/jzitnik/client/threads/MicrophoneThread.java @@ -13,6 +13,11 @@ import lombok.extern.slf4j.Slf4j; import javax.sound.sampled.LineUnavailableException; +/** + * Thread responsible for processing microphone input and updating volume state. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @ThreadRegistry public class MicrophoneThread extends ShutdownableThread { @@ -21,6 +26,9 @@ public class MicrophoneThread extends ShutdownableThread { private AudioDispatcher dispatcher; + /** + * Main execution loop for audio processing. + */ @Override public void run() { try { @@ -62,6 +70,9 @@ public class MicrophoneThread extends ShutdownableThread { } } + /** + * Shuts down the audio dispatcher and stops the thread. + */ @Override public void shutdown() { if (dispatcher != null && !dispatcher.isStopped()) { diff --git a/game/src/main/java/cz/jzitnik/client/ui/DialogUI.java b/game/src/main/java/cz/jzitnik/client/ui/DialogUI.java index 27b9c50..1b36edd 100644 --- a/game/src/main/java/cz/jzitnik/client/ui/DialogUI.java +++ b/game/src/main/java/cz/jzitnik/client/ui/DialogUI.java @@ -24,6 +24,11 @@ import lombok.extern.slf4j.Slf4j; import static cz.jzitnik.client.events.handlers.DialogEventHandler.*; +/** + * UI component for handling interactions with dialogs. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @UI @Dependency @@ -47,6 +52,12 @@ public class DialogUI { @InjectDependency private EventManager eventManager; + /** + * Handles mouse clicks on dialog buttons. + * + * @param mouseAction The mouse action + * @return true if handled + */ @MouseHandler(MouseHandlerType.CLICK) public boolean handleClick(MouseAction mouseAction) { if (dialogState.getCurrentDialog() == null || dialogState.isRenderInProgress()) { @@ -130,6 +141,12 @@ public class DialogUI { return true; } + /** + * Handles mouse movement over dialog buttons. + * + * @param mouseAction The mouse action + * @return true if handled + */ @MouseHandler(MouseHandlerType.MOVE) public boolean handleMove(MouseAction mouseAction) { if (dialogState.getCurrentDialog() == null || dialogState.isRenderInProgress()) { @@ -198,6 +215,11 @@ public class DialogUI { return true; } + /** + * Sets the currently hovered button index and triggers a rerender of the dialog. + * + * @param index Hovered button index + */ private void setHoveredButtonIndex(int index) { if (dialogState.getHoveredButtonIndex() != index) { dialogState.setHoveredButtonIndex(index); @@ -205,6 +227,12 @@ public class DialogUI { } } + /** + * Clears the dialog area in the override buffer. + * + * @param start Starting terminal position + * @param size Size of the dialog + */ private void clearDialog(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++) { diff --git a/game/src/main/java/cz/jzitnik/client/ui/GlobalShortcuts.java b/game/src/main/java/cz/jzitnik/client/ui/GlobalShortcuts.java index 02b0ac4..59cd700 100644 --- a/game/src/main/java/cz/jzitnik/client/ui/GlobalShortcuts.java +++ b/game/src/main/java/cz/jzitnik/client/ui/GlobalShortcuts.java @@ -9,24 +9,47 @@ import cz.jzitnik.client.events.*; import cz.jzitnik.client.utils.events.EventManager; import cz.jzitnik.common.socket.messages.Test; +/** + * UI component for global keyboard shortcuts. + * + * @author Jakub Žitník (jzitnik) + */ @UI @Dependency public class GlobalShortcuts { @InjectDependency private EventManager eventManager; + /** + * Triggers a full redraw. + * + * @param ignored Event context + * @return true + */ @KeyboardPressHandler(keyType = KeyType.F5) public boolean refresh(KeyboardPressEvent ignored) { eventManager.emitEvent(new FullRedrawEvent()); return true; } + /** + * Triggers an exit event. + * + * @param ignored Event context + * @return true + */ @KeyboardPressHandler(keyType = KeyType.Escape) public boolean exit(KeyboardPressEvent ignored) { eventManager.emitEvent(new ExitEvent()); return true; } + /** + * Handles player movement keys. + * + * @param event The keyboard event + * @return true + */ @KeyboardPressHandler(character = 'w') @KeyboardPressHandler(character = 'a') @KeyboardPressHandler(character = 's') @@ -36,6 +59,12 @@ public class GlobalShortcuts { return true; } + /** + * Sends a test socket message. + * + * @param event The keyboard event + * @return true + */ @KeyboardPressHandler(character = 'p') public boolean debugSocket(KeyboardPressEvent event) { eventManager.emitEvent(new SendSocketMessageEvent(new Test())); diff --git a/game/src/main/java/cz/jzitnik/client/ui/Inventory.java b/game/src/main/java/cz/jzitnik/client/ui/Inventory.java index 8390187..d626210 100644 --- a/game/src/main/java/cz/jzitnik/client/ui/Inventory.java +++ b/game/src/main/java/cz/jzitnik/client/ui/Inventory.java @@ -40,21 +40,31 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; +/** + * UI component for managing and rendering the player inventory. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @UI @Dependency public class Inventory { private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); + /** Number of item slots horizontally. */ public static final int ITEMS_X = 3; + /** Number of item slots vertically. */ public static final int ITEMS_Y = 5; private static final int OUTER_BORDER_WIDTH = 2; private static final int INNER_BORDER_WIDTH = 1; private static final int ITEM_SIZE = 16; // Characters private static final int ITEM_PADDING = 2; // padding on each side + /** Color for inventory borders. */ public static final AlphaPixel BORDER_COLOR = new ColoredPixel(new TextColor.RGB(41, 29, 19)); + /** Default background color for item slots. */ public static final AlphaPixel BACKGROUND_COLOR = new ColoredPixel(new TextColor.RGB(61, 45, 29)); + /** Background color for hovered item slots. */ public static final AlphaPixel BACKGROUND_COLOR_HOVERED = new ColoredPixel(new TextColor.RGB(77, 56, 36)); private static final AlphaPixel BACKGROUND_COLOR_SELECTED = @@ -64,9 +74,11 @@ public class Inventory { private static final AlphaPixel BACKGROUND_COLOR_EQUIPPED_SELECTED = new ColoredPixel(new TextColor.RGB(58, 170, 176)); private static final int ITEM_SLOT_SIZE = ITEM_SIZE + ITEM_PADDING * 2; + /** Overall width of the inventory UI. */ public static final int INVENTORY_WIDTH = OUTER_BORDER_WIDTH * 2 + (ITEMS_X * (ITEM_SLOT_SIZE + INNER_BORDER_WIDTH) - INNER_BORDER_WIDTH); + /** Overall height of the inventory UI. */ public static final int INVENTORY_HEIGHT = OUTER_BORDER_WIDTH * 2 + (ITEMS_Y * (ITEM_SLOT_SIZE + INNER_BORDER_WIDTH) - INNER_BORDER_WIDTH); @@ -107,6 +119,9 @@ public class Inventory { @Getter private int offsetY; + /** + * Calculates the offset for rendering the inventory on the screen. + */ private void calculateOffset() { BufferedImage room = resourceManager.getResource(ResourceManager.Resource.ROOM1); TerminalSize terminalSize = terminalState.getTerminalScreen().getTerminalSize(); @@ -117,6 +132,12 @@ public class Inventory { offsetX = (maxX / 2) - (INVENTORY_WIDTH / 2); } + /** + * Handles dropping an item from the inventory. + * + * @param ignored Event context + * @return true if an item was dropped + */ @KeyboardPressHandler(character = 'q') @KeyboardPressHandler(character = 'Q') public boolean handleItemDrop(KeyboardPressEvent ignored) { @@ -158,6 +179,12 @@ public class Inventory { return true; } + /** + * Handles a mouse click on the inventory UI. + * + * @param mouseAction The mouse action + * @return true if handled + */ @MouseHandler(MouseHandlerType.CLICK) public boolean handleClick(MouseAction mouseAction) { inventoryState.onNextDragTakeItemOnIndex = -1; @@ -252,6 +279,12 @@ public class Inventory { return true; } + /** + * Handles mouse movement over the inventory UI. + * + * @param mouseAction The mouse action + * @return true if handled + */ @MouseHandler(MouseHandlerType.MOVE) public boolean handleMove(MouseAction mouseAction) { TerminalPosition terminalPosition = calculateActualCords(mouseAction.getPosition()); @@ -274,6 +307,12 @@ public class Inventory { return true; } + /** + * Handles other mouse actions (drag, etc.). + * + * @param mouseAction The mouse action + * @return true if handled + */ @MouseHandler(MouseHandlerType.ELSE) public boolean handleElse(MouseAction mouseAction) { TerminalPosition terminalPosition = calculateActualCords(mouseAction.getPosition()); @@ -308,10 +347,19 @@ public class Inventory { return true; } + /** + * Translates terminal position to inventory-local coordinates. + * + * @param position Terminal position + * @return Local terminal position + */ private TerminalPosition calculateActualCords(TerminalPosition position) { return new TerminalPosition(position.getColumn() - offsetX, position.getRow() * 2 - offsetY); } + /** + * Rerenders the inventory into the screen buffer. + */ @Render public void renderInventoryRerender() { calculateOffset(); @@ -383,6 +431,7 @@ public class Inventory { } } + /** Internal state of the inventory UI. */ private static class InventoryState { protected int hoveredItem = -1; protected int selectedItem = -1; diff --git a/game/src/main/java/cz/jzitnik/client/ui/Stats.java b/game/src/main/java/cz/jzitnik/client/ui/Stats.java index f729ed1..3df738d 100644 --- a/game/src/main/java/cz/jzitnik/client/ui/Stats.java +++ b/game/src/main/java/cz/jzitnik/client/ui/Stats.java @@ -18,6 +18,11 @@ import lombok.Getter; import java.awt.image.BufferedImage; +/** + * UI component for rendering player stats (health, stamina). + * + * @author Jakub Žitník (jzitnik) + */ @Getter @UI @Dependency @@ -28,10 +33,14 @@ public class Stats { public static final int ICON_BAR_MARGIN = 2; public static final int BAR_HEIGHT = 8; public static final int BAR_PADDING = 2; + /** Overall height of the stats UI. */ public static final int HEIGHT = BAR_HEIGHT * BARS_COUNT + (BAR_PADDING * (BARS_COUNT - 1)); + /** Overall width of the stats UI. */ public static final int WIDTH = BAR_WIDTH + ICON_SIZE + ICON_BAR_MARGIN; + /** X offset from terminal top-left. */ public static final int OFFSET_X = 5; + /** Y offset from terminal top-left. */ public static final int OFFSET_Y = 5; private static final Pixel HEALTH_COLOR = new ColoredPixel(new TextColor.RGB(205, 0, 0)); @@ -46,6 +55,9 @@ public class Stats { @InjectDependency private ResourceManager resourceManager; + /** + * Rerenders the stats bars into the screen buffer. + */ @Render public void rerender() { var buffer = screenBuffer.getRenderedBuffer(); diff --git a/game/src/main/java/cz/jzitnik/client/ui/pixels/AlphaPixel.java b/game/src/main/java/cz/jzitnik/client/ui/pixels/AlphaPixel.java index a7e13f8..bf8a4e4 100644 --- a/game/src/main/java/cz/jzitnik/client/ui/pixels/AlphaPixel.java +++ b/game/src/main/java/cz/jzitnik/client/ui/pixels/AlphaPixel.java @@ -3,14 +3,31 @@ package cz.jzitnik.client.ui.pixels; import com.googlecode.lanterna.TextColor; import lombok.Getter; +/** + * Abstract class for a pixel with transparency support. + * + * @author Jakub Žitník (jzitnik) + */ @Getter public sealed abstract class AlphaPixel extends Pixel permits Empty, ColoredPixel { private final float alpha; + + /** + * Constructs an AlphaPixel. + * + * @param color Pixel color + * @param alpha Alpha value (0.0 to 1.0) + */ public AlphaPixel(TextColor color, float alpha) { super(color); this.alpha = alpha; } + /** + * Checks if the pixel is fully transparent. + * + * @return true if alpha is 0 + */ public boolean isTransparent() { return alpha == 0f; } diff --git a/game/src/main/java/cz/jzitnik/client/ui/pixels/ColoredPixel.java b/game/src/main/java/cz/jzitnik/client/ui/pixels/ColoredPixel.java index 767da0a..ff934aa 100644 --- a/game/src/main/java/cz/jzitnik/client/ui/pixels/ColoredPixel.java +++ b/game/src/main/java/cz/jzitnik/client/ui/pixels/ColoredPixel.java @@ -2,11 +2,27 @@ package cz.jzitnik.client.ui.pixels; import com.googlecode.lanterna.TextColor; +/** + * A pixel with a specific color and optional alpha. + * + * @author Jakub Žitník (jzitnik) + */ public final class ColoredPixel extends AlphaPixel { + /** + * Constructs a fully opaque ColoredPixel. + * + * @param color The color + */ public ColoredPixel(TextColor color) { super(color, 1f); } + /** + * Constructs a ColoredPixel with specified transparency. + * + * @param color The color + * @param alpha Alpha transparency + */ public ColoredPixel(TextColor color, float alpha) { super(color, alpha); } diff --git a/game/src/main/java/cz/jzitnik/client/ui/pixels/Empty.java b/game/src/main/java/cz/jzitnik/client/ui/pixels/Empty.java index 219cc2d..93562c5 100644 --- a/game/src/main/java/cz/jzitnik/client/ui/pixels/Empty.java +++ b/game/src/main/java/cz/jzitnik/client/ui/pixels/Empty.java @@ -1,6 +1,14 @@ package cz.jzitnik.client.ui.pixels; +/** + * Represents an empty (transparent) pixel. + * + * @author Jakub Žitník (jzitnik) + */ public final class Empty extends AlphaPixel { + /** + * Constructs an Empty pixel. + */ public Empty() { super(null, 0f); } diff --git a/game/src/main/java/cz/jzitnik/client/ui/pixels/Pixel.java b/game/src/main/java/cz/jzitnik/client/ui/pixels/Pixel.java index 1d7a1b9..d4a3bb9 100644 --- a/game/src/main/java/cz/jzitnik/client/ui/pixels/Pixel.java +++ b/game/src/main/java/cz/jzitnik/client/ui/pixels/Pixel.java @@ -4,6 +4,11 @@ import com.googlecode.lanterna.TextColor; import lombok.AllArgsConstructor; import lombok.Getter; +/** + * Base abstract class for a screen pixel. + * + * @author Jakub Žitník (jzitnik) + */ @Getter @AllArgsConstructor public sealed abstract class Pixel permits AlphaPixel { diff --git a/game/src/main/java/cz/jzitnik/client/ui/utils/Button.java b/game/src/main/java/cz/jzitnik/client/ui/utils/Button.java index c2876fb..0390f39 100644 --- a/game/src/main/java/cz/jzitnik/client/ui/utils/Button.java +++ b/game/src/main/java/cz/jzitnik/client/ui/utils/Button.java @@ -5,6 +5,11 @@ import cz.jzitnik.client.utils.TextRenderer; import java.awt.*; +/** + * Represents a rendered UI button. + * + * @author Jakub Žitník (jzitnik) + */ public record Button( AlphaPixel borderColor, AlphaPixel backgroundColor, @@ -16,6 +21,13 @@ public record Button( float fontSize, TextRenderer textRenderer ) { + /** + * Renders the button with text. + * + * @param text Button text + * @param selected Whether the button is selected/hovered + * @return 2D array of AlphaPixels + */ public AlphaPixel[][] render(String text, boolean selected) { AlphaPixel[][] buf = new AlphaPixel[height][width]; AlphaPixel[][] textBuf = textRenderer.renderTextSingleLine(text, width - borderWidth * 2, height - borderWidth * 2, textColor, fontSize, true, true); diff --git a/game/src/main/java/cz/jzitnik/client/ui/utils/Grid.java b/game/src/main/java/cz/jzitnik/client/ui/utils/Grid.java index d97ba3a..7070d36 100644 --- a/game/src/main/java/cz/jzitnik/client/ui/utils/Grid.java +++ b/game/src/main/java/cz/jzitnik/client/ui/utils/Grid.java @@ -5,6 +5,11 @@ import cz.jzitnik.client.ui.pixels.Pixel; import java.awt.image.BufferedImage; +/** + * Utility class for rendering items in a grid layout. + * + * @author Jakub Žitník (jzitnik) + */ public class Grid { private final int itemsX; private final int itemsY; @@ -20,6 +25,18 @@ public class Grid { private final int gridWidth; private final int gridHeight; + /** + * Constructs a Grid. + * + * @param itemsX Number of items horizontally + * @param itemsY Number of items vertically + * @param outerBorderWidth Outer border width + * @param innerBorderWidth Inner border width + * @param itemSize Item size + * @param itemPadding Item padding + * @param borderColor Border color + * @param backgroundColor Background color + */ public Grid( int itemsX, int itemsY, @@ -50,10 +67,23 @@ public class Grid { (itemsY * (itemSlotSize + innerBorderWidth) - innerBorderWidth); } + /** + * Renders items into the grid. + * + * @param textures Item textures + * @return 2D pixel array + */ public Pixel[][] render(BufferedImage[] textures) { return render(textures, new Pixel[textures.length]); } + /** + * Renders items into the grid with custom backgrounds. + * + * @param textures Item textures + * @param customBackgrounds Custom backgrounds for slots + * @return 2D pixel array + */ public Pixel[][] render(BufferedImage[] textures, Pixel[] customBackgrounds) { Pixel[][] buffer = new Pixel[gridHeight][gridWidth]; @@ -141,6 +171,14 @@ public class Grid { return getItemIndexAt(x, y, false); } + /** + * Calculates which item index corresponds to the given coordinates. + * + * @param x X coordinate + * @param y Y coordinate + * @param ignoreInnerBorder Whether to ignore inner borders + * @return Item index or -1 + */ public int getItemIndexAt(int x, int y, boolean ignoreInnerBorder) { if (x < 0 || x >= gridWidth || y < 0 || y >= gridHeight) { return -1; @@ -178,10 +216,20 @@ public class Grid { return row * itemsX + col; } + /** + * Gets the grid width. + * + * @return width + */ public int getWidth() { return gridWidth; } + /** + * Gets the grid height. + * + * @return height + */ public int getHeight() { return gridHeight; } diff --git a/game/src/main/java/cz/jzitnik/client/ui/utils/Input.java b/game/src/main/java/cz/jzitnik/client/ui/utils/Input.java index 1cb9e8d..10cb555 100644 --- a/game/src/main/java/cz/jzitnik/client/ui/utils/Input.java +++ b/game/src/main/java/cz/jzitnik/client/ui/utils/Input.java @@ -11,6 +11,11 @@ import lombok.RequiredArgsConstructor; import java.awt.*; +/** + * UI component for rendering an input field. + * + * @author Jakub Žitník (jzitnik) + */ @AllArgsConstructor @RequiredArgsConstructor public class Input { @@ -19,6 +24,12 @@ public class Input { private final int height; private final int width; + /** + * Renders the input field. + * + * @param textRenderer Text renderer + * @return 2D pixel array + */ public AlphaPixel[][] render(TextRenderer textRenderer) { AlphaPixel[][] buffer = new AlphaPixel[height][width]; AlphaPixel[][] textBuf = new AlphaPixel[0][0]; diff --git a/game/src/main/java/cz/jzitnik/client/utils/DependencyManager.java b/game/src/main/java/cz/jzitnik/client/utils/DependencyManager.java index 8912c4a..4de94c2 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/DependencyManager.java +++ b/game/src/main/java/cz/jzitnik/client/utils/DependencyManager.java @@ -25,11 +25,21 @@ import java.lang.reflect.Method; import java.nio.file.Path; import java.util.*; +/** + * Manages dependency injection and configuration loading. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j public class DependencyManager extends InjectableValues { private final ClassToInstanceMap configs = MutableClassToInstanceMap.create(); private final ClassToInstanceMap data = MutableClassToInstanceMap.create(); + /** + * Constructs a DependencyManager and initializes dependencies using reflection. + * + * @param reflections The reflections instance to scan for components + */ public DependencyManager(Reflections reflections) { ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); data.put(ObjectMapper.class, mapper); @@ -92,6 +102,13 @@ public class DependencyManager extends InjectableValues { } + /** + * Retrieves a dependency or throws an exception if not found. + * + * @param clazz The class of the dependency + * @param The type of the dependency + * @return The dependency instance + */ public T getDependencyOrThrow(Class clazz) { T instance = data.getInstance(clazz); @@ -102,14 +119,35 @@ public class DependencyManager extends InjectableValues { return instance; } + /** + * Retrieves a dependency if present. + * + * @param clazz The class of the dependency + * @param The type of the dependency + * @return An Optional containing the dependency + */ public Optional getDependency(Class clazz) { return Optional.ofNullable(data.getInstance(clazz)); } + /** + * Retrieves a configuration instance if present. + * + * @param clazz The configuration class + * @param The type of the configuration + * @return An Optional containing the configuration + */ public Optional getConfig(Class clazz) { return Optional.ofNullable(configs.getInstance(clazz)); } + /** + * Retrieves a configuration instance or throws an exception if not found. + * + * @param clazz The configuration class + * @param The type of the configuration + * @return The configuration instance + */ public T getConfigOrThrow(Class clazz) { T instance = configs.getInstance(clazz); @@ -120,6 +158,11 @@ public class DependencyManager extends InjectableValues { return instance; } + /** + * Injects dependencies into an object instance. + * + * @param instance The object to inject dependencies into + */ public void inject(Object instance) { StateManager stateManager = (StateManager) data.get(StateManager.class); @@ -192,6 +235,9 @@ public class DependencyManager extends InjectableValues { } } + /** + * Finds an injectable value for Jackson deserialization. + */ @Override public Object findInjectableValue(DeserializationContext ctxt, Object valueId, BeanProperty forProperty, Object beanInstance, Boolean optional, Boolean useInput) throws JacksonException { if (valueId instanceof Class clazz) { @@ -233,6 +279,9 @@ public class DependencyManager extends InjectableValues { return null; } + /** + * Creates a snapshot of injectable values (not implemented). + */ @Override public InjectableValues snapshot() { return null; diff --git a/game/src/main/java/cz/jzitnik/client/utils/GlobalIOHandlerRepository.java b/game/src/main/java/cz/jzitnik/client/utils/GlobalIOHandlerRepository.java index 61aa022..29a0a86 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/GlobalIOHandlerRepository.java +++ b/game/src/main/java/cz/jzitnik/client/utils/GlobalIOHandlerRepository.java @@ -16,6 +16,11 @@ import java.lang.reflect.Method; import java.util.*; import java.util.function.Predicate; +/** + * Repository for global input and output (rendering) handlers. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @Dependency public class GlobalIOHandlerRepository { @@ -30,10 +35,21 @@ public class GlobalIOHandlerRepository { @InjectDependency private DependencyManager dependencyManager; + /** + * Constructs a GlobalIOHandlerRepository. + * + * @param reflections Reflections instance to scan for UI components + */ public GlobalIOHandlerRepository(Reflections reflections) { this.reflections = reflections; } + /** + * Triggers mouse click handlers. + * + * @param mouseEvent The mouse action + * @return true if handled + */ public boolean click(MouseAction mouseEvent) { for (Predicate handler : mouseClickHandlers) { if (handler.test(mouseEvent)) { @@ -44,6 +60,12 @@ public class GlobalIOHandlerRepository { return false; } + /** + * Triggers mouse move handlers. + * + * @param mouseEvent The mouse action + * @return true if handled + */ public boolean move(MouseAction mouseEvent) { for (Predicate handler : mouseMoveHandlers) { if (handler.test(mouseEvent)) { @@ -53,6 +75,12 @@ public class GlobalIOHandlerRepository { return false; } + /** + * Triggers other mouse action handlers. + * + * @param mouseEvent The mouse action + * @return true if handled + */ public boolean mElse(MouseAction mouseEvent) { for (Predicate handler : mouseElseHandlers) { if (handler.test(mouseEvent)) { @@ -62,6 +90,12 @@ public class GlobalIOHandlerRepository { return false; } + /** + * Triggers keyboard press handlers. + * + * @param keyboardPressEvent The keyboard event + * @return true if handled + */ public boolean keyboard(KeyboardPressEvent keyboardPressEvent) { KeyType keyType = keyboardPressEvent.getKeyStroke().getKeyType(); if (keyType == KeyType.Character) { @@ -78,10 +112,16 @@ public class GlobalIOHandlerRepository { return false; } + /** + * Triggers all registered renderers. + */ public void renderAll() { renderers.forEach(Runnable::run); } + /** + * Scans for UI components and registers their handlers. + */ public void setup() { Set> classes = reflections.getTypesAnnotatedWith(UI.class); for (Class clazz : classes) { diff --git a/game/src/main/java/cz/jzitnik/client/utils/RerenderUtils.java b/game/src/main/java/cz/jzitnik/client/utils/RerenderUtils.java index 752d533..f86bca5 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/RerenderUtils.java +++ b/game/src/main/java/cz/jzitnik/client/utils/RerenderUtils.java @@ -23,8 +23,20 @@ import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; +/** + * Utility class for rerendering parts of the game screen. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j public class RerenderUtils { + /** + * Calculates the starting coordinates to center a room in the terminal. + * + * @param room The room image + * @param terminalSize The terminal dimensions + * @return Starting RoomCords + */ public static RoomCords getStart(BufferedImage room, TerminalSize terminalSize) { int width = room.getWidth(); int height = room.getHeight(); @@ -37,6 +49,23 @@ public class RerenderUtils { return new RoomCords(x, y); } + /** + * Rerenders a specific part of the screen. + * + * @param startX Start X in room coordinates + * @param endX End X in room coordinates + * @param startY Start Y in room coordinates + * @param endY End Y in room coordinates + * @param screenStartX Screen X offset + * @param screenStartY Screen Y offset + * @param currentRoom The current game room + * @param room The room image + * @param player The player instance + * @param screenBuffer The screen buffer + * @param resourceManager The resource manager + * @param debugging Debugging configuration + * @param otherPlayers List of other players + */ public static void rerenderPart(int startX, int endX, int startY, int endY, int screenStartX, int screenStartY, GameRoom currentRoom, BufferedImage room, Player player, ScreenBuffer screenBuffer, ResourceManager resourceManager, Debugging debugging, List otherPlayers) { var buffer = screenBuffer.getRenderedBuffer(); var overrideBuffer = currentRoom.getOverrideBuffer(); @@ -61,9 +90,30 @@ public class RerenderUtils { } } + /** + * Result of a single pixel rendering operation. + * + * @param pixel The pixel color value + * @param isPlayer true if the pixel belongs to a player + */ public record PixelResult(int pixel, boolean isPlayer) { } + /** + * Determines the pixel color at a specific coordinate. + * + * @param currentRoom The current room + * @param room The room image + * @param doors The doors image + * @param doorPositions Set of door positions + * @param player The player + * @param resourceManager The resource manager + * @param x X coordinate + * @param y Y coordinate + * @param debugging Debugging configuration + * @param visiblePlayer List of visible players + * @return The resulting pixel data + */ public static PixelResult getPixel(GameRoom currentRoom, BufferedImage room, BufferedImage doors, Set doorPositions, Player player, ResourceManager resourceManager, int x, int y, Debugging debugging, List visiblePlayer) { float factor = 1.5f; // brightness multiplier if (debugging.renderColliders() && currentRoom.getColliders().stream().anyMatch(collider -> collider.isWithin(new RoomCords(x, y)))) { @@ -190,6 +240,12 @@ public class RerenderUtils { return new PixelResult(room.getRGB(x, y), false); } + /** + * Determines which doors are present in the room. + * + * @param currentRoom The room to check + * @return Set of door positions + */ public static Set getDoorPositions(GameRoom currentRoom) { Set doorPositions = new HashSet<>(); if (currentRoom.getLeft() != null) doorPositions.add(FullRoomDrawHandler.DoorPosition.LEFT); @@ -200,9 +256,23 @@ public class RerenderUtils { return doorPositions; } + /** + * Represents color data of a pixel. + * + * @param r Red component + * @param g Green component + * @param b Blue component + * @param alpha Alpha component + */ public record ColorData(int r, int g, int b, int alpha) { } + /** + * Extracts color data from an integer pixel value. + * + * @param pixel The pixel value + * @return ColorData instance + */ public static ColorData getPixelData(int pixel) { int alpha = (pixel >> 24) & 0xff; int r = (pixel >> 16) & 0xff; diff --git a/game/src/main/java/cz/jzitnik/client/utils/ScheduledSerializedTaskManager.java b/game/src/main/java/cz/jzitnik/client/utils/ScheduledSerializedTaskManager.java index 1a51b5f..a1dc57a 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/ScheduledSerializedTaskManager.java +++ b/game/src/main/java/cz/jzitnik/client/utils/ScheduledSerializedTaskManager.java @@ -15,6 +15,11 @@ import java.util.concurrent.TimeUnit; // THIS WILL DEFINITELY NEED MORE TESTING +/** + * Manages scheduled tasks that can be serialized (currently focused on scheduling). + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @Dependency public class ScheduledSerializedTaskManager { @@ -22,10 +27,27 @@ public class ScheduledSerializedTaskManager { private ScheduledTaskManager scheduledTaskManager; private final ScheduleList scheduleList = new ScheduleList(); + /** + * Schedules a task at a fixed rate. + * + * @param runnable Task to run + * @param rate Execution rate + * @param rateUnit Time unit for rate + * @return Scheduled future + */ public ScheduledFuture scheduleAtFixedRate(Runnable runnable, long rate, TimeUnit rateUnit) { return scheduleAtFixedRate(runnable, 0, rate, rateUnit); } + /** + * Schedules a task with an initial delay and fixed rate. + * + * @param runnable Task to run + * @param initialDelay Initial delay + * @param rate Execution rate + * @param rateUnit Time unit for rate + * @return Scheduled future + */ public ScheduledFuture scheduleAtFixedRate(Runnable runnable, long initialDelay, long rate, TimeUnit rateUnit) { return scheduleList.add( new ScheduleList.Schedule<>( @@ -38,6 +60,14 @@ public class ScheduledSerializedTaskManager { ); } + /** + * Schedules a one-time task. + * + * @param runnable Task to run + * @param delay Delay + * @param unit Time unit + * @return Scheduled future + */ public ScheduledFuture schedule(Runnable runnable, long delay, TimeUnit unit) { return scheduleList.add( new ScheduleList.Schedule<>( @@ -50,6 +80,15 @@ public class ScheduledSerializedTaskManager { ); } + /** + * Schedules a one-time callable task. + * + * @param runnable Callable task + * @param delay Delay + * @param unit Time unit + * @param Return type + * @return Scheduled future + */ public ScheduledFuture schedule(Callable runnable, long delay, TimeUnit unit) { return scheduleList.add( new ScheduleList.Schedule<>( @@ -63,6 +102,12 @@ public class ScheduledSerializedTaskManager { } // TODO: When saving the game run this to get all scheduled serialized tasks + + /** + * Retrieves the list of currently scheduled tasks for serialization. + * + * @return Schedule list + */ public ScheduleList getScheduleList() { Set> newList = new HashSet<>(); @@ -85,8 +130,12 @@ public class ScheduledSerializedTaskManager { // TODO: Create some function that will resume all the schedules from the [ScheduleList] class + /** + * Represents a list of schedules. + */ @Getter public static class ScheduleList implements Serializable { + /** Type of scheduled task. */ protected enum ScheduleType { REPEAT_AT_FIXED_RATE, SCHEDULE, @@ -100,6 +149,7 @@ public class ScheduledSerializedTaskManager { this.schedules = new HashSet<>(); } + /** Represents a single schedule. */ @Getter public static class Schedule implements Serializable { private final ScheduleType type; @@ -120,6 +170,13 @@ public class ScheduledSerializedTaskManager { private final Set> schedules; + /** + * Adds a schedule to the list. + * + * @param schedule The schedule + * @param Return type + * @return Scheduled future + */ public ScheduledFuture add(Schedule schedule) { schedules.add(schedule); diff --git a/game/src/main/java/cz/jzitnik/client/utils/ScheduledTaskManager.java b/game/src/main/java/cz/jzitnik/client/utils/ScheduledTaskManager.java index e7782f8..d72f52f 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/ScheduledTaskManager.java +++ b/game/src/main/java/cz/jzitnik/client/utils/ScheduledTaskManager.java @@ -14,6 +14,11 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +/** + * Manages and schedules periodic tasks. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @Dependency public class ScheduledTaskManager { @@ -24,6 +29,12 @@ public class ScheduledTaskManager { @InjectConfig private ThreadPoolConfig threadPoolConfig; + /** + * Constructs a ScheduledTaskManager and discovers scheduled tasks. + * + * @param reflections The reflections instance to scan for tasks + * @param dependencyManager The dependency manager to inject into tasks + */ public ScheduledTaskManager(Reflections reflections, DependencyManager dependencyManager) { this.dependencyManager = dependencyManager; var classes = reflections.getTypesAnnotatedWith(ScheduledTask.class); @@ -45,6 +56,9 @@ public class ScheduledTaskManager { } } + /** + * Starts all discovered scheduled tasks. + */ public void startAll() { scheduler = Executors.newScheduledThreadPool(threadPoolConfig.taskThreadCount()); for (Registry instance : instances) { @@ -53,10 +67,21 @@ public class ScheduledTaskManager { } } + /** + * Temporarily schedules a task at a fixed rate. + * + * @param runnable The task to run + * @param rate The execution rate + * @param rateUnit The time unit for the rate + * @return A ScheduledFuture representing the task + */ public ScheduledFuture tempScheduleFixedRate(Runnable runnable, long rate, TimeUnit rateUnit) { return scheduler.scheduleAtFixedRate(runnable, 0, rate, rateUnit); } + /** + * Shuts down the scheduler and all running tasks. + */ public void shutdown() { try { scheduler.shutdown(); @@ -72,6 +97,9 @@ public class ScheduledTaskManager { } } + /** + * Internal registry for a scheduled task and its configuration. + */ private record Registry(Runnable runnable, ScheduledTask scheduledTask) { } } diff --git a/game/src/main/java/cz/jzitnik/client/utils/ShutdownableThread.java b/game/src/main/java/cz/jzitnik/client/utils/ShutdownableThread.java index 8400862..1e3dd36 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/ShutdownableThread.java +++ b/game/src/main/java/cz/jzitnik/client/utils/ShutdownableThread.java @@ -1,6 +1,13 @@ package cz.jzitnik.client.utils; +/** + * Abstract class for threads that can be cleanly shut down. + * + * @author Jakub Žitník (jzitnik) + */ public abstract class ShutdownableThread extends Thread { + /** Main thread loop. */ public abstract void run(); + /** Cleanly shuts down the thread. */ public abstract void shutdown(); } diff --git a/game/src/main/java/cz/jzitnik/client/utils/StateManager.java b/game/src/main/java/cz/jzitnik/client/utils/StateManager.java index d57298b..2bcbd0f 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/StateManager.java +++ b/game/src/main/java/cz/jzitnik/client/utils/StateManager.java @@ -10,11 +10,22 @@ import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Optional; +/** + * Manages game state instances. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @Dependency public class StateManager { private final HashMap, Object> data = new HashMap<>(); + /** + * Constructs a StateManager and discovers state classes using reflection. + * + * @param reflections Reflections instance to scan for state classes + * @param dependencyManager Dependency manager to pass to states if needed + */ public StateManager(Reflections reflections, DependencyManager dependencyManager) { var classes = reflections.getTypesAnnotatedWith(State.class); @@ -36,15 +47,34 @@ public class StateManager { } } + /** + * Manually registers a state instance. + * + * @param instance The state instance to register + */ public void registerManually(Object instance) { data.put(instance.getClass(), instance); } + /** + * Retrieves a state instance if present. + * + * @param clazz The class of the state + * @param The state type + * @return An Optional containing the state + */ @SuppressWarnings("unchecked") public Optional get(Class clazz) { return Optional.ofNullable((T) data.get(clazz)); } + /** + * Retrieves a state instance or returns null if not found. + * + * @param clazz The class of the state + * @param The state type + * @return The state instance + */ @SuppressWarnings("unchecked") public T getOrThrow(Class clazz) { return (T) data.get(clazz); diff --git a/game/src/main/java/cz/jzitnik/client/utils/TextRenderer.java b/game/src/main/java/cz/jzitnik/client/utils/TextRenderer.java index 580039b..7d0e2ce 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/TextRenderer.java +++ b/game/src/main/java/cz/jzitnik/client/utils/TextRenderer.java @@ -17,12 +17,29 @@ import java.io.IOException; import java.util.ArrayList; import java.util.List; +/** + * Utility class for rendering text into pixel buffers. + * + * @author Jakub Žitník (jzitnik) + */ @Dependency public class TextRenderer { @InjectDependency private ResourceManager resourceManager; + /** + * Renders a single line of text into a pixel buffer. + * + * @param text Text to render + * @param width Buffer width + * @param height Buffer height + * @param textColor Color of the text + * @param size Font size + * @param centeredHorizontally Whether to center horizontally + * @param centeredVertically Whether to center vertically + * @return 2D array of AlphaPixels + */ public AlphaPixel[][] renderTextSingleLine(String text, int width, int height, Color textColor, float size, boolean centeredHorizontally, boolean centeredVertically) { Font font = loadFont(size); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); @@ -55,6 +72,17 @@ public class TextRenderer { return convertToPixels(img, width, height); } + /** + * Renders multi-line text with word wrapping. + * + * @param text Text to render + * @param width Buffer width + * @param height Buffer height + * @param textColor Color + * @param size Font size + * @param centered Whether to center lines + * @return 2D array of AlphaPixels + */ public AlphaPixel[][] renderText(String text, int width, int height, Color textColor, float size, boolean centered) { Font font = loadFont(size); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); @@ -84,6 +112,16 @@ public class TextRenderer { return convertToPixels(img, width, height); } + /** + * Renders an array of pixel buffers for a typing animation. + * + * @param text Full text + * @param width Buffer width + * @param height Buffer height + * @param textColor Color + * @param size Font size + * @return 3D array of AlphaPixels (frames) + */ public AlphaPixel[][][] renderTypingAnimation(String text, int width, int height, Color textColor, float size) { Font font = loadFont(size); BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); @@ -131,6 +169,9 @@ public class TextRenderer { return frames; } + /** + * Calculates the vertical offset for text rendering. + */ private int calculateVerticalOffset(String text, Font font, FontRenderContext frc, List lines) { if (lines.isEmpty() || text.isBlank()) return 0; @@ -146,6 +187,9 @@ public class TextRenderer { return (int) topPixelPos; } + /** + * Loads the default font with specified size. + */ private Font loadFont(float size) { try { return Font.createFont(Font.TRUETYPE_FONT, resourceManager.getResourceAsStream("fonts/default.ttf")).deriveFont(size); @@ -154,6 +198,9 @@ public class TextRenderer { } } + /** + * Creates a Graphics2D context for a BufferedImage. + */ private Graphics2D createGraphics(BufferedImage img, Font font, Color color) { Graphics2D g2d = img.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); @@ -163,6 +210,9 @@ public class TextRenderer { return g2d; } + /** + * Clears an image buffer. + */ private void clearImage(BufferedImage img) { Graphics2D g = img.createGraphics(); g.setComposite(AlphaComposite.Clear); @@ -170,6 +220,9 @@ public class TextRenderer { g.dispose(); } + /** + * Calculates word wrapping for a given text. + */ private List calculateWordWrapping(String text, FontMetrics fm, int width, int height) { List lines = new ArrayList<>(); String[] words = text.split(" "); @@ -193,6 +246,9 @@ public class TextRenderer { return lines; } + /** + * Converts a BufferedImage to a 2D AlphaPixel array. + */ private AlphaPixel[][] convertToPixels(BufferedImage img, int width, int height) { AlphaPixel[][] pixels = new AlphaPixel[height][width]; int[] rawPixels = new int[width * height]; @@ -216,6 +272,14 @@ public class TextRenderer { return pixels; } + /** + * Measures the dimensions of a block of text. + * + * @param text Text + * @param maxWidth Max width + * @param size Font size + * @return Dimensions + */ public Dimension measureText(String text, int maxWidth, float size) { Font font = loadFont(size); BufferedImage tmp = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB); diff --git a/game/src/main/java/cz/jzitnik/client/utils/ThreadManager.java b/game/src/main/java/cz/jzitnik/client/utils/ThreadManager.java index 63569fa..16321c9 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/ThreadManager.java +++ b/game/src/main/java/cz/jzitnik/client/utils/ThreadManager.java @@ -7,11 +7,22 @@ import org.reflections.Reflections; import java.lang.reflect.InvocationTargetException; import java.util.HashSet; +/** + * Manages the lifecycle of application threads. + * + * @author Jakub Žitník (jzitnik) + */ @Dependency public class ThreadManager { private final HashSet threads = new HashSet<>(); private final DependencyManager dependencyManager; + /** + * Constructs a ThreadManager and discovers shutdownable threads. + * + * @param reflections The reflections instance to scan for threads + * @param dependencyManager The dependency manager to inject into threads + */ public ThreadManager(Reflections reflections, DependencyManager dependencyManager) { this.dependencyManager = dependencyManager; @@ -32,6 +43,9 @@ public class ThreadManager { } } + /** + * Starts all discovered threads. + */ public void startAll() { for (ShutdownableThread thread : threads) { dependencyManager.inject(thread); @@ -39,6 +53,9 @@ public class ThreadManager { } } + /** + * Shuts down all managed threads. + */ public void shutdownAll() { for (ShutdownableThread thread : threads) { thread.shutdown(); diff --git a/game/src/main/java/cz/jzitnik/client/utils/UIRoomClickHandlerRepository.java b/game/src/main/java/cz/jzitnik/client/utils/UIRoomClickHandlerRepository.java index d1707a3..52997e1 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/UIRoomClickHandlerRepository.java +++ b/game/src/main/java/cz/jzitnik/client/utils/UIRoomClickHandlerRepository.java @@ -13,6 +13,11 @@ import cz.jzitnik.client.game.objects.UIClickHandler; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +/** + * Repository for UI click handlers tied to specific rooms. + * + * @author Jakub Žitník (jzitnik) + */ @Dependency public class UIRoomClickHandlerRepository { private final Map> roomSpecificHandlers = new ConcurrentHashMap<>(); @@ -21,11 +26,26 @@ public class UIRoomClickHandlerRepository { @InjectDependency private GlobalIOHandlerRepository globalIOHandlerRepository; + /** + * Registers a handler for the current room. + * + * @param screenPart The part of the screen covered by the handler + * @param uiClickHandler The handler implementation + * @return Hash code of the screen part + */ public int registerCurrentRoomHandler(RerenderScreen.ScreenPart screenPart, UIClickHandler uiClickHandler) { GameRoom currentRoom = gameState.getCurrentRoom(); return registerRoomSpecificHandler(currentRoom, screenPart, uiClickHandler); } + /** + * Registers a handler for a specific room. + * + * @param gameRoom The room + * @param screenPart The screen part + * @param uiClickHandler The handler implementation + * @return Hash code of the screen part + */ public int registerRoomSpecificHandler(GameRoom gameRoom, RerenderScreen.ScreenPart screenPart, UIClickHandler uiClickHandler) { if (!roomSpecificHandlers.containsKey(gameRoom)) { roomSpecificHandlers.put(gameRoom, new ConcurrentHashMap<>()); @@ -36,6 +56,12 @@ public class UIRoomClickHandlerRepository { return screenPart.hashCode(); } + /** + * Handles a mouse click by checking room-specific and global handlers. + * + * @param mouseAction The mouse action + * @return true if handled + */ public boolean handleClick(MouseAction mouseAction) { if (roomSpecificHandlers.containsKey(gameState.getCurrentRoom())) { Map handlers = roomSpecificHandlers.get(gameState.getCurrentRoom()); @@ -56,6 +82,12 @@ public class UIRoomClickHandlerRepository { return globalIOHandlerRepository.click(mouseAction); } + /** + * Handles other mouse actions. + * + * @param mouseAction The mouse action + * @return true if handled + */ public boolean handleElse(MouseAction mouseAction) { if (roomSpecificHandlers.containsKey(gameState.getCurrentRoom())) { Map handlers = roomSpecificHandlers.get(gameState.getCurrentRoom()); @@ -76,6 +108,12 @@ public class UIRoomClickHandlerRepository { return globalIOHandlerRepository.mElse(mouseAction); } + /** + * Handles mouse movement. + * + * @param mouseAction The mouse action + * @return true if handled + */ public boolean handleMove(MouseAction mouseAction) { if (roomSpecificHandlers.containsKey(gameState.getCurrentRoom())) { Map handlers = roomSpecificHandlers.get(gameState.getCurrentRoom()); @@ -95,6 +133,11 @@ public class UIRoomClickHandlerRepository { return globalIOHandlerRepository.move(mouseAction); } + /** + * Removes a handler for the current room. + * + * @param screenPartHashCode The hash code of the screen part to remove + */ public void removeHandlerForCurrentRoom(int screenPartHashCode) { GameRoom currentRoom = gameState.getCurrentRoom(); if (!roomSpecificHandlers.containsKey(currentRoom)) return; diff --git a/game/src/main/java/cz/jzitnik/client/utils/events/AbstractEventHandler.java b/game/src/main/java/cz/jzitnik/client/utils/events/AbstractEventHandler.java index e5924d3..0dbf228 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/events/AbstractEventHandler.java +++ b/game/src/main/java/cz/jzitnik/client/utils/events/AbstractEventHandler.java @@ -1,5 +1,16 @@ package cz.jzitnik.client.utils.events; +/** + * Base class for all client-side event handlers. + * + * @param The type of Event this handler handles + * @author Jakub Žitník (jzitnik) + */ public abstract class AbstractEventHandler { + /** + * Handles the received event. + * + * @param event The event to handle + */ public abstract void handle(T event); } diff --git a/game/src/main/java/cz/jzitnik/client/utils/events/Event.java b/game/src/main/java/cz/jzitnik/client/utils/events/Event.java index 5e5fac4..3acc001 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/events/Event.java +++ b/game/src/main/java/cz/jzitnik/client/utils/events/Event.java @@ -1,4 +1,9 @@ package cz.jzitnik.client.utils.events; +/** + * Base interface for all client-side events. + * + * @author Jakub Žitník (jzitnik) + */ public interface Event { } diff --git a/game/src/main/java/cz/jzitnik/client/utils/events/EventManager.java b/game/src/main/java/cz/jzitnik/client/utils/events/EventManager.java index 1fee7a9..5eec660 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/events/EventManager.java +++ b/game/src/main/java/cz/jzitnik/client/utils/events/EventManager.java @@ -15,6 +15,11 @@ import java.util.HashMap; import java.util.List; import java.util.concurrent.*; +/** + * Manages the dispatching and handling of client-side events. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @Dependency public class EventManager extends Thread { @@ -33,30 +38,66 @@ public class EventManager extends Thread { return (AbstractEventHandler) handlers.get(type); } + /** + * Emits a single event. + * + * @param event The event to emit + */ public void emitEvent(Event event) { eventQueue.add(new EventRecord(new Event[]{event})); } + /** + * Emits a single event with a callback to run after handling. + * + * @param event The event to emit + * @param callback The callback to run + */ public void emitEvent(Event event, Runnable callback) { eventQueue.add(new EventRecord(new Event[]{event}, callback)); } + /** + * Emits an array of events. + * + * @param events The events to emit + */ public void emitEvent(Event[] events) { eventQueue.add(new EventRecord(events)); } + /** + * Emits a list of events. + * + * @param events The events to emit + */ public void emitEvent(List events) { eventQueue.add(new EventRecord(events.toArray(new Event[]{}))); } + /** + * Emits a list of events with a callback. + * + * @param events The events to emit + * @param callback The callback to run + */ public void emitEvent(List events, Runnable callback) { eventQueue.add(new EventRecord(events.toArray(new Event[]{}), callback)); } + /** + * Emits an array of events with a callback. + * + * @param events The events to emit + * @param callback The callback to run + */ public void emitEvent(Event[] events, Runnable callback) { eventQueue.add(new EventRecord(events, callback)); } + /** + * Internal record to store events and their callback. + */ private record EventRecord(Event[] events, Runnable callback) { public EventRecord(Event[] events) { this(events, () -> { @@ -64,6 +105,12 @@ public class EventManager extends Thread { } } + /** + * Constructs an EventManager by discovering handlers. + * + * @param reflections Reflections instance + * @param dependencyManager Dependency manager + */ public EventManager(Reflections reflections, DependencyManager dependencyManager) { this.dependencyManager = dependencyManager; setDaemon(true); @@ -82,6 +129,9 @@ public class EventManager extends Thread { } } + /** + * Main execution loop for processing events. + */ @Override public void run() { for (Object instance : handlers.values()) { @@ -102,6 +152,11 @@ public class EventManager extends Thread { eventExecutor.shutdown(); } + /** + * Handles an individual event record. + * + * @param eventRecord The event record to handle + */ @SuppressWarnings("unchecked") private void handleEvent(EventRecord eventRecord) { eventExecutor.submit(() -> { diff --git a/game/src/main/java/cz/jzitnik/client/utils/roomtasks/RoomTask.java b/game/src/main/java/cz/jzitnik/client/utils/roomtasks/RoomTask.java index 5d7b05e..c30d4ef 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/roomtasks/RoomTask.java +++ b/game/src/main/java/cz/jzitnik/client/utils/roomtasks/RoomTask.java @@ -6,6 +6,11 @@ import lombok.RequiredArgsConstructor; import java.util.concurrent.TimeUnit; +/** + * Abstract class representing a task tied to a room's lifecycle. + * + * @author Jakub Žitník (jzitnik) + */ @RequiredArgsConstructor @Getter public abstract class RoomTask { diff --git a/game/src/main/java/cz/jzitnik/client/utils/roomtasks/RoomTaskScheduler.java b/game/src/main/java/cz/jzitnik/client/utils/roomtasks/RoomTaskScheduler.java index 9252634..07b35a1 100644 --- a/game/src/main/java/cz/jzitnik/client/utils/roomtasks/RoomTaskScheduler.java +++ b/game/src/main/java/cz/jzitnik/client/utils/roomtasks/RoomTaskScheduler.java @@ -16,6 +16,11 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +/** + * Schedules and manages tasks specific to a game room. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @Dependency public class RoomTaskScheduler { @@ -29,17 +34,26 @@ public class RoomTaskScheduler { private boolean firstRun = true; + /** + * Initializes the scheduler executor. + */ @PostInit public void initExecutor() { scheduler = Executors.newScheduledThreadPool(threadPoolConfig.taskThreadCount()); } + /** + * Shuts down all current tasks and reinitializes the executor. + */ public void shutdownTasks() { shutdownAll(); initExecutor(); firstRun = true; } + /** + * Internal method to shut down the executor and await termination. + */ private void shutdownAll() { scheduler.shutdown(); @@ -56,10 +70,18 @@ public class RoomTaskScheduler { } } + /** + * Performs a final shutdown of the scheduler. + */ public void finalShutdown() { shutdownAll(); } + /** + * Stops a specific room task. + * + * @param task The task to stop + */ public void stopTask(RoomTask task) { if (!tasks.containsKey(task)) { return; @@ -70,6 +92,11 @@ public class RoomTaskScheduler { tasks.remove(task); } + /** + * Sets up new schedulers for a room, typically called on room change. + * + * @param currentRoom The new current room + */ public void setupNewSchedulers(GameRoom currentRoom) { if (!firstRun) { shutdownAll(); @@ -83,6 +110,12 @@ public class RoomTaskScheduler { firstRun = false; } + /** + * Registers tasks for a new mob and stops its old tasks. + * + * @param mob The new mob + * @param oldTasks The mob's old tasks to stop + */ public void registerNewMob(Mob mob, RoomTask[] oldTasks) { for (RoomTask oldTask : oldTasks) { stopTask(oldTask); @@ -91,6 +124,11 @@ public class RoomTaskScheduler { registerNewTasks(mob.getTasks()); } + /** + * Internal method to register and schedule a set of tasks. + * + * @param registerTasks The tasks to register + */ private void registerNewTasks(RoomTask[] registerTasks) { for (RoomTask task : registerTasks) { dependencyManager.inject(task.getTask()); diff --git a/server/src/main/java/cz/jzitnik/server/Main.java b/server/src/main/java/cz/jzitnik/server/Main.java index 1eda49c..2ba4d9f 100644 --- a/server/src/main/java/cz/jzitnik/server/Main.java +++ b/server/src/main/java/cz/jzitnik/server/Main.java @@ -10,7 +10,18 @@ import org.reflections.Reflections; import java.util.*; +/** + * Main entry point for the game server. + * + * @author Jakub Žitník (jzitnik) + */ public class Main { + /** + * Starts the server and initializes the application context. + * + * @param args Command line arguments + * @throws DeploymentException If server deployment fails + */ public static void main(String[] args) throws DeploymentException { GlobalContext globalContext = new GlobalContext(); AppContext.set(globalContext); diff --git a/server/src/main/java/cz/jzitnik/server/annotations/EventHandler.java b/server/src/main/java/cz/jzitnik/server/annotations/EventHandler.java index efc0d51..1db8989 100644 --- a/server/src/main/java/cz/jzitnik/server/annotations/EventHandler.java +++ b/server/src/main/java/cz/jzitnik/server/annotations/EventHandler.java @@ -7,8 +7,18 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +/** + * Annotation to mark a class as an event handler for a specific SocketMessage. + * + * @author Jakub Žitník (jzitnik) + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface EventHandler { + /** + * The class of the SocketMessage this handler handles. + * + * @return The message class + */ Class value(); } diff --git a/server/src/main/java/cz/jzitnik/server/context/AppContext.java b/server/src/main/java/cz/jzitnik/server/context/AppContext.java index 73f719f..b1145e8 100644 --- a/server/src/main/java/cz/jzitnik/server/context/AppContext.java +++ b/server/src/main/java/cz/jzitnik/server/context/AppContext.java @@ -1,12 +1,27 @@ package cz.jzitnik.server.context; +/** + * Global application context holder. + * + * @author Jakub Žitník (jzitnik) + */ public class AppContext { private static GlobalContext globalContext; + /** + * Sets the global context. + * + * @param context The context to set + */ public static void set(GlobalContext context) { globalContext = context; } + /** + * Gets the global context. + * + * @return The global context + */ public static GlobalContext get() { return globalContext; } diff --git a/server/src/main/java/cz/jzitnik/server/context/GameManager.java b/server/src/main/java/cz/jzitnik/server/context/GameManager.java index 6ff385e..fe80e23 100644 --- a/server/src/main/java/cz/jzitnik/server/context/GameManager.java +++ b/server/src/main/java/cz/jzitnik/server/context/GameManager.java @@ -1,4 +1,9 @@ package cz.jzitnik.server.context; +/** + * Manages game instances (currently empty). + * + * @author Jakub Žitník (jzitnik) + */ public class GameManager { } diff --git a/server/src/main/java/cz/jzitnik/server/context/GlobalContext.java b/server/src/main/java/cz/jzitnik/server/context/GlobalContext.java index 6ce06a7..513e632 100644 --- a/server/src/main/java/cz/jzitnik/server/context/GlobalContext.java +++ b/server/src/main/java/cz/jzitnik/server/context/GlobalContext.java @@ -11,6 +11,11 @@ import java.io.IOException; import java.io.InputStream; import java.util.*; +/** + * Holds global server state and configuration. + * + * @author Jakub Žitník (jzitnik) + */ public class GlobalContext { @Getter private final HashMap sessions = new HashMap<>(); @@ -25,14 +30,28 @@ public class GlobalContext { @Getter private final Properties properties; + /** + * Registers a client with their session. + * + * @param client The client to register + */ public void registerClient(Client client) { sessions.put(client.getSession().getSession(), client); } + /** + * Finds a game by its password. + * + * @param pass The game password + * @return An Optional containing the game if found + */ public Optional getGame(String pass) { return games.stream().filter(game -> game.getPassword().equals(pass)).findFirst(); } + /** + * Constructs a GlobalContext and loads configuration properties. + */ public GlobalContext() { Properties props = new Properties(); diff --git a/server/src/main/java/cz/jzitnik/server/events/AbstractEventHandler.java b/server/src/main/java/cz/jzitnik/server/events/AbstractEventHandler.java index 28e7f28..55a323b 100644 --- a/server/src/main/java/cz/jzitnik/server/events/AbstractEventHandler.java +++ b/server/src/main/java/cz/jzitnik/server/events/AbstractEventHandler.java @@ -5,8 +5,21 @@ import cz.jzitnik.server.context.GlobalContext; import cz.jzitnik.server.game.Client; import lombok.RequiredArgsConstructor; +/** + * Base class for all socket event handlers. + * + * @param The type of SocketMessage this handler handles + * @author Jakub Žitník (jzitnik) + */ @RequiredArgsConstructor public abstract class AbstractEventHandler { protected final GlobalContext globalContext; + + /** + * Handles the received socket event. + * + * @param event The event message + * @param client The client who sent the event + */ public abstract void handle(T event, Client client); } diff --git a/server/src/main/java/cz/jzitnik/server/events/EventManager.java b/server/src/main/java/cz/jzitnik/server/events/EventManager.java index 55b1e1d..92401b6 100644 --- a/server/src/main/java/cz/jzitnik/server/events/EventManager.java +++ b/server/src/main/java/cz/jzitnik/server/events/EventManager.java @@ -14,18 +14,38 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; +/** + * Manages the dispatching and handling of socket events. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j public class EventManager extends Thread { private ExecutorService eventExecutor; private final HashMap, AbstractEventHandler> handlers = new HashMap<>(); private final BlockingQueue eventQueue = new LinkedBlockingQueue<>(); + /** + * Internal registry to store event and associated client. + */ private record Registry(SocketMessage event, Client client) {} + /** + * Emits an event to be handled by the manager. + * + * @param event The socket event message + * @param client The client who sent the event + */ public void emitEvent(SocketMessage event, Client client) { eventQueue.add(new Registry(event, client)); } + /** + * Constructs an EventManager by discovering handlers using reflection. + * + * @param reflections The reflection instance to scan for handlers + * @param globalContext The global context to pass to handlers + */ public EventManager(Reflections reflections, GlobalContext globalContext) { setDaemon(true); @@ -43,6 +63,9 @@ public class EventManager extends Thread { } } + /** + * The main execution loop for processing events in the queue. + */ @Override public void run() { eventExecutor = Executors.newFixedThreadPool(6); @@ -58,11 +81,24 @@ public class EventManager extends Thread { //eventExecutor.shutdown(); } + /** + * Gets a handler for a specific message type. + * + * @param type The type of the message + * @param The message type + * @return The associated event handler + */ @SuppressWarnings("unchecked") private AbstractEventHandler getHandler(Class type) { return (AbstractEventHandler) handlers.get(type); } + /** + * Handles an individual event using its associated handler. + * + * @param event The event message + * @param client The client who sent it + */ @SuppressWarnings("unchecked") private void handleEvent(SocketMessage event, Client client) { eventExecutor.submit(() -> { diff --git a/server/src/main/java/cz/jzitnik/server/events/handlers/ConnectToAGameHandler.java b/server/src/main/java/cz/jzitnik/server/events/handlers/ConnectToAGameHandler.java index 4884773..469f0d1 100644 --- a/server/src/main/java/cz/jzitnik/server/events/handlers/ConnectToAGameHandler.java +++ b/server/src/main/java/cz/jzitnik/server/events/handlers/ConnectToAGameHandler.java @@ -15,12 +15,28 @@ import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.ObjectReader; import tools.jackson.dataformat.yaml.YAMLFactory; +/** + * Handler for the ConnectToAGame event. + * + * @author Jakub Žitník (jzitnik) + */ @EventHandler(ConnectToAGame.class) public class ConnectToAGameHandler extends AbstractEventHandler { + /** + * Constructs a ConnectToAGameHandler. + * + * @param globalContext The global context + */ public ConnectToAGameHandler(GlobalContext globalContext) { super(globalContext); } + /** + * Handles the ConnectToAGame event by validating the game password and adding the player to the game. + * + * @param event The ConnectToAGame event message + * @param client The client who wants to connect + */ @Override public void handle(ConnectToAGame event, Client client) { var gameOptional = globalContext.getGame(event.gamePass().toUpperCase()); diff --git a/server/src/main/java/cz/jzitnik/server/events/handlers/CreateGameHandler.java b/server/src/main/java/cz/jzitnik/server/events/handlers/CreateGameHandler.java index 43b4d60..a794fc6 100644 --- a/server/src/main/java/cz/jzitnik/server/events/handlers/CreateGameHandler.java +++ b/server/src/main/java/cz/jzitnik/server/events/handlers/CreateGameHandler.java @@ -19,12 +19,28 @@ import tools.jackson.dataformat.yaml.YAMLFactory; import java.util.ArrayList; import java.util.List; +/** + * Handler for the CreateGame event. + * + * @author Jakub Žitník (jzitnik) + */ @EventHandler(CreateGame.class) public class CreateGameHandler extends AbstractEventHandler { + /** + * Constructs a CreateGameHandler. + * + * @param globalContext The global context + */ public CreateGameHandler(GlobalContext globalContext) { super(globalContext); } + /** + * Handles the CreateGame event by creating a new game instance and initializing the owner player. + * + * @param event The CreateGame event message + * @param client The client who requested game creation + */ @Override public void handle(CreateGame event, Client client) { ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); diff --git a/server/src/main/java/cz/jzitnik/server/events/handlers/GameWinHandler.java b/server/src/main/java/cz/jzitnik/server/events/handlers/GameWinHandler.java index fc39ff7..f2c43e0 100644 --- a/server/src/main/java/cz/jzitnik/server/events/handlers/GameWinHandler.java +++ b/server/src/main/java/cz/jzitnik/server/events/handlers/GameWinHandler.java @@ -6,12 +6,28 @@ import cz.jzitnik.server.context.GlobalContext; import cz.jzitnik.server.events.AbstractEventHandler; import cz.jzitnik.server.game.Client; +/** + * Handler for the GameWin event. + * + * @author Jakub Žitník (jzitnik) + */ @EventHandler(GameWin.class) public class GameWinHandler extends AbstractEventHandler { + /** + * Constructs a GameWinHandler. + * + * @param globalContext The global context + */ public GameWinHandler(GlobalContext globalContext) { super(globalContext); } + /** + * Handles the GameWin event by notifying all players in the game. + * + * @param event The GameWin event message + * @param client The client who triggered the win + */ @Override public void handle(GameWin event, Client client) { for (Client player : client.getGame().getPlayers()) { diff --git a/server/src/main/java/cz/jzitnik/server/events/handlers/ItemTookFromChestHandler.java b/server/src/main/java/cz/jzitnik/server/events/handlers/ItemTookFromChestHandler.java index e4c0d31..b0a3ac4 100644 --- a/server/src/main/java/cz/jzitnik/server/events/handlers/ItemTookFromChestHandler.java +++ b/server/src/main/java/cz/jzitnik/server/events/handlers/ItemTookFromChestHandler.java @@ -6,12 +6,28 @@ import cz.jzitnik.server.context.GlobalContext; import cz.jzitnik.server.events.AbstractEventHandler; import cz.jzitnik.server.game.Client; +/** + * Handler for the ItemTookFromChest event. + * + * @author Jakub Žitník (jzitnik) + */ @EventHandler(ItemTookFromChest.class) public class ItemTookFromChestHandler extends AbstractEventHandler { + /** + * Constructs an ItemTookFromChestHandler. + * + * @param globalContext The global context + */ public ItemTookFromChestHandler(GlobalContext globalContext) { super(globalContext); } + /** + * Handles the ItemTookFromChest event by recording the modifier and notifying all players. + * + * @param event The ItemTookFromChest event message + * @param client The client who took the item + */ @Override public void handle(ItemTookFromChest event, Client client) { client.getGame().getItemModifiers().add(event); diff --git a/server/src/main/java/cz/jzitnik/server/events/handlers/MovePlayerRoomHandler.java b/server/src/main/java/cz/jzitnik/server/events/handlers/MovePlayerRoomHandler.java index 7de43db..6287d46 100644 --- a/server/src/main/java/cz/jzitnik/server/events/handlers/MovePlayerRoomHandler.java +++ b/server/src/main/java/cz/jzitnik/server/events/handlers/MovePlayerRoomHandler.java @@ -11,13 +11,29 @@ import lombok.extern.slf4j.Slf4j; import java.util.stream.Collectors; +/** + * Handler for the MovePlayerRoom event. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @EventHandler(MovePlayerRoom.class) public class MovePlayerRoomHandler extends AbstractEventHandler { + /** + * Constructs a MovePlayerRoomHandler. + * + * @param globalContext The global context + */ public MovePlayerRoomHandler(GlobalContext globalContext) { super(globalContext); } + /** + * Handles the MovePlayerRoom event by moving the player to a new room and notifying other players. + * + * @param event The MovePlayerRoom event message + * @param client The client who is moving + */ @Override public void handle(MovePlayerRoom event, Client client) { String oldRoomId = client.getPlayer().getCurrentRoom(); diff --git a/server/src/main/java/cz/jzitnik/server/events/handlers/PlayerDeathHandler.java b/server/src/main/java/cz/jzitnik/server/events/handlers/PlayerDeathHandler.java index 4bae0b9..bd5c822 100644 --- a/server/src/main/java/cz/jzitnik/server/events/handlers/PlayerDeathHandler.java +++ b/server/src/main/java/cz/jzitnik/server/events/handlers/PlayerDeathHandler.java @@ -6,12 +6,28 @@ import cz.jzitnik.server.context.GlobalContext; import cz.jzitnik.server.events.AbstractEventHandler; import cz.jzitnik.server.game.Client; +/** + * Handler for the PlayerDeath event. + * + * @author Jakub Žitník (jzitnik) + */ @EventHandler(PlayerDeath.class) public class PlayerDeathHandler extends AbstractEventHandler { + /** + * Constructs a PlayerDeathHandler. + * + * @param globalContext The global context + */ public PlayerDeathHandler(GlobalContext globalContext) { super(globalContext); } + /** + * Handles the PlayerDeath event by notifying all players in the game. + * + * @param event The PlayerDeath event message + * @param client The client who died (or reported the death) + */ @Override public void handle(PlayerDeath event, Client client) { for (Client player : client.getGame().getPlayers()) { diff --git a/server/src/main/java/cz/jzitnik/server/events/handlers/PlayerMoveHandler.java b/server/src/main/java/cz/jzitnik/server/events/handlers/PlayerMoveHandler.java index 91ad4fc..eab833a 100644 --- a/server/src/main/java/cz/jzitnik/server/events/handlers/PlayerMoveHandler.java +++ b/server/src/main/java/cz/jzitnik/server/events/handlers/PlayerMoveHandler.java @@ -7,12 +7,28 @@ import cz.jzitnik.server.context.GlobalContext; import cz.jzitnik.server.events.AbstractEventHandler; import cz.jzitnik.server.game.Client; +/** + * Handler for the PlayerMove event. + * + * @author Jakub Žitník (jzitnik) + */ @EventHandler(PlayerMove.class) public class PlayerMoveHandler extends AbstractEventHandler { + /** + * Constructs a PlayerMoveHandler. + * + * @param globalContext The global context + */ public PlayerMoveHandler(GlobalContext globalContext) { super(globalContext); } + /** + * Handles the PlayerMove event by updating the player's position and notifying others in the same room. + * + * @param event The PlayerMove event message + * @param client The client who moved + */ @Override public void handle(PlayerMove event, Client client) { client.getPlayer().getCords().updateCords(event.newCords()); diff --git a/server/src/main/java/cz/jzitnik/server/game/Client.java b/server/src/main/java/cz/jzitnik/server/game/Client.java index 32394d4..c762463 100644 --- a/server/src/main/java/cz/jzitnik/server/game/Client.java +++ b/server/src/main/java/cz/jzitnik/server/game/Client.java @@ -4,6 +4,11 @@ import cz.jzitnik.server.socket.SocketSession; import lombok.Getter; import lombok.Setter; +/** + * Represents a connected client in the server. + * + * @author Jakub Žitník (jzitnik) + */ @Getter public final class Client { private final SocketSession session; @@ -12,12 +17,25 @@ public final class Client { @Setter private Game game; + /** + * Constructs a Client with session, player and game. + * + * @param session The socket session + * @param player The player associated with the client + * @param game The game the client is part of + */ public Client(SocketSession session, Player player, Game game) { this.session = session; this.player = player; this.game = game; } + /** + * Constructs a Client with session and player. + * + * @param session The socket session + * @param player The player associated with the client + */ public Client(SocketSession session, Player player) { this(session, player, null); } diff --git a/server/src/main/java/cz/jzitnik/server/game/Game.java b/server/src/main/java/cz/jzitnik/server/game/Game.java index 936b51e..f2b683c 100644 --- a/server/src/main/java/cz/jzitnik/server/game/Game.java +++ b/server/src/main/java/cz/jzitnik/server/game/Game.java @@ -7,6 +7,11 @@ import lombok.Getter; import java.util.ArrayList; import java.util.List; +/** + * Represents a game instance on the server. + * + * @author Jakub Žitník (jzitnik) + */ @Getter @AllArgsConstructor public class Game { diff --git a/server/src/main/java/cz/jzitnik/server/game/Player.java b/server/src/main/java/cz/jzitnik/server/game/Player.java index 33dff31..0fd5e57 100644 --- a/server/src/main/java/cz/jzitnik/server/game/Player.java +++ b/server/src/main/java/cz/jzitnik/server/game/Player.java @@ -6,6 +6,11 @@ import cz.jzitnik.common.socket.messages.player.PlayerRotation; import lombok.Getter; import lombok.Setter; +/** + * Represents a player in the game. + * + * @author Jakub Žitník (jzitnik) + */ @Getter public class Player { private final int id; @@ -15,12 +20,22 @@ public class Player { @Setter private String currentRoom; + /** + * Constructs a Player from a PlayerCreation object. + * + * @param creation The player creation data + */ public Player(PlayerCreation creation) { id = creation.getId(); cords = creation.getPlayerCords(); playerRotation = PlayerRotation.FRONT; } + /** + * Converts the player state to a PlayerCreation object. + * + * @return A new PlayerCreation instance + */ public PlayerCreation toPlayerCreation() { return new PlayerCreation(cords, null); } diff --git a/server/src/main/java/cz/jzitnik/server/socket/GlobalContextConfigurator.java b/server/src/main/java/cz/jzitnik/server/socket/GlobalContextConfigurator.java index 2454e4d..2f207ff 100644 --- a/server/src/main/java/cz/jzitnik/server/socket/GlobalContextConfigurator.java +++ b/server/src/main/java/cz/jzitnik/server/socket/GlobalContextConfigurator.java @@ -5,8 +5,20 @@ import jakarta.websocket.HandshakeResponse; import jakarta.websocket.server.HandshakeRequest; import jakarta.websocket.server.ServerEndpointConfig; +/** + * Configurator for the WebSocket endpoint to inject the GlobalContext. + * + * @author Jakub Žitník (jzitnik) + */ public class GlobalContextConfigurator extends ServerEndpointConfig.Configurator { + /** + * Modifies the handshake to include the GlobalContext in user properties. + * + * @param sec The server endpoint configuration + * @param request The handshake request + * @param response The handshake response + */ @Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { sec.getUserProperties().put("globalContext", AppContext.get()); diff --git a/server/src/main/java/cz/jzitnik/server/socket/SocketSession.java b/server/src/main/java/cz/jzitnik/server/socket/SocketSession.java index 20c9396..7da9673 100644 --- a/server/src/main/java/cz/jzitnik/server/socket/SocketSession.java +++ b/server/src/main/java/cz/jzitnik/server/socket/SocketSession.java @@ -9,11 +9,21 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; +/** + * Wrapper for a WebSocket session to facilitate sending messages. + * + * @author Jakub Žitník (jzitnik) + */ @RequiredArgsConstructor @Getter public class SocketSession { private final Session session; + /** + * Sends a SocketMessage to the client. + * + * @param message The message to send + */ public void sendMessage(SocketMessage message) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); diff --git a/server/src/main/java/cz/jzitnik/server/socket/WebSocket.java b/server/src/main/java/cz/jzitnik/server/socket/WebSocket.java index a0aa476..47f7ea1 100644 --- a/server/src/main/java/cz/jzitnik/server/socket/WebSocket.java +++ b/server/src/main/java/cz/jzitnik/server/socket/WebSocket.java @@ -11,12 +11,23 @@ import lombok.extern.slf4j.Slf4j; import java.io.*; +/** + * WebSocket endpoint for handling game socket communication. + * + * @author Jakub Žitník (jzitnik) + */ @Slf4j @ServerEndpoint(value = "/ws", configurator = GlobalContextConfigurator.class) public class WebSocket { private GlobalContext globalContext; + /** + * Called when a new WebSocket connection is opened. + * + * @param session The WebSocket session + * @param config The endpoint configuration + */ @OnOpen public void onOpen(Session session, EndpointConfig config) { this.globalContext = (GlobalContext) config.getUserProperties().get("globalContext"); @@ -25,6 +36,12 @@ public class WebSocket { log.debug("Client connected: {}", session.getId()); } + /** + * Called when a binary message is received. + * + * @param bytes The received bytes + * @param session The WebSocket session + */ @OnMessage public void onMessage(byte[] bytes, Session session) { try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes); @@ -37,6 +54,12 @@ public class WebSocket { } } + /** + * Called when a WebSocket connection is closed. + * + * @param session The WebSocket session + * @param reason The reason for closing + */ @OnClose public void onClose(Session session, CloseReason reason) { Client client = globalContext.getSessions().get(session); @@ -59,6 +82,12 @@ public class WebSocket { log.debug("Connection closed: {}", reason); } + /** + * Called when a WebSocket error occurs. + * + * @param session The WebSocket session + * @param throwable The error that occurred + */ @OnError public void onError(Session session, Throwable throwable) { throwable.printStackTrace(); diff --git a/server/src/main/java/cz/jzitnik/server/utils/PasswordGenerator.java b/server/src/main/java/cz/jzitnik/server/utils/PasswordGenerator.java index 17a2f55..babc6cc 100644 --- a/server/src/main/java/cz/jzitnik/server/utils/PasswordGenerator.java +++ b/server/src/main/java/cz/jzitnik/server/utils/PasswordGenerator.java @@ -2,10 +2,21 @@ package cz.jzitnik.server.utils; import java.security.SecureRandom; +/** + * Utility class for generating random passwords. + * + * @author Jakub Žitník (jzitnik) + */ public class PasswordGenerator { private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static final SecureRandom RANDOM = new SecureRandom(); + /** + * Generates a random alphanumeric password of specified length. + * + * @param length The length of the password to generate + * @return The generated password string + */ public static String generatePassword(int length) { if (length <= 0) { throw new IllegalArgumentException("Password length must be greater than 0");