During the preparation of this work, the authors used GitHub Copilot and DeepL to assist with writing the Javadoc and to check the grammar of this report. Moreover, Copilot has been used as a review tool in some pull requests on GitHub (for example, here). After using this tool/service, the authors reviewed and edited the content as needed and take full responsibility for the content of the final report/artifact.
This report presents the âDonkey Kong: Rushâ project, realized for the âDistributed Systemâ course at the University of Bologna. The project involves the development of a 2D multiplayer platform video game inspired by the classic Donkey Kong. The system is designed around an Entity-Component-System (ECS) architecture written in Java, utilizing JavaFX for rendering. The main focus of the project is the implementation of smooth multiplayer gameplay. The solution combines the hostâs authority over the deterministic environment with a reactive handling of local inputs, guaranteeing an experience free of blocking lag for the players.
âDonkey Kong: Rushâ is a desktop application featuring a graphical user interface (GUI). Specifically, it is a 2D multiplayer platform video game, which takes inspiration from the original Donkey Kong arcade game.
The software provides a competitive multiplayer platforming experience. Users are located on separate desktop machines connected over the same local area network. Thus, distribution is a fundamental requirement for this project to enable a seamless multiplayer experience, as it allows players on physically separate machines across a network to connect, interact, and share the same virtual space.
Interaction is continuous and in real-time during an active game session. The system captures inputs and exchanges state updates across the network multiple times per second to maintain synchronization.
Players interact with the system via the GUI during setup or keyboard controls during the game. The game controls consist of standard keybindings for movement (left/right, climbing ladders) and jumping.
The system does not require persistent, long-term data storage. All necessary data represents the state of the ongoing match (such as player and barrel coordinates).
The game relies on multiple user roles:
| Term | Definition |
|---|---|
| Host | A player who actively plays the game, processes local input, acts as the authoritative entity for game-world generation (e.g., barrels), and broadcasts the state to clients. |
| Guest | A player who actively plays the game, processes local input, and receives continuous world state updates from the host. |
| Spectator | A passive user who does not generate input but receives real-time updates to render and watch the match. |
| Lobby | The pre-game networking state where users connect and are assigned their respective roles (host, guest, or spectator) before the match begins. |
| Entity | Any distinct object in the game world. |
| Barrel | A dynamic entity that deals damage when a player comes into contact with it. |
| Ladder | A climbable entity in the game level that enables players to move vertically regardless of gravity. |
| Mario | The playable avatar assigned to the host, capable of moving horizontally, jumping, and climbing ladders. |
| Luigi | The playable avatar assigned to the guest, sharing identical movement mechanics with Mario while competing in the race to the top. |
| Pauline | The static goal entity positioned at the top of the level; colliding with her triggers the winning condition and concludes the match. |
| Donkey Kong | The non-playable antagonist entity positioned at the top of the arena, serving as the source that periodically spawns rolling barrels. |
| Description | Acceptance Criterion | Â |
|---|---|---|
| The system must allow users to join a lobby and automatically assign them a role (host, guest, or spectator) based on join order or preference. | A user successfully connects to the server and receives a distinct role assignment (host, guest, or spectator) before the game starts. | Â |
| The system must allow active players to move horizontally (left/right), jump, and climb ladders. | Pressing the designated keys updates the playerâs position appropriately on the screen according to game physics (gravity, collision). | Â |
| The system must synchronize the game state (entities positions, and lives) between all connected clients in real time. | When the host moves or a barrel spawns, the guest and Spectators see the updated positions on their screens without noticeable desynchronization. | Â |
| The system must detect collisions between players and damaging entities (e.g., barrels), deducting a life upon impact. | When a playerâs character intersects with a barrel, the playerâs life count decreases by 1, and the character respawns at the starting position. | Â |
| The system must declare a winner if a player reaches the goal (Pauline) or declare a loser if a playerâs lives reach zero. | The game transitions to a âGame Overâ screen displaying the correct winner or loser when the goal is touched or 3 lives are lost. | Â |
These requirements define the behavioral aspects and quality attributes of the system.
| Description | Acceptance Criterion |
|---|---|
| The game must update and render at a consistent frame rate to ensure smooth gameplay. | The local game loop executes consistently at the target of 60 Frames-Per-Second (FPS). |
| State updates must be transmitted rapidly to prevent visual stuttering or unfair advantages. | State update payloads are serialized, transmitted over the local network, and deserialized by the receiving client. |
| The system must ensure automatic recovery from disconnections for non-host users. | If a guest or spectator loses their network connection and subsequently reconnects to the server while the match is still active, the system automatically restores their role and resumes sending them real-time game state updates without requiring a full lobby reset. |
| Code must be modular and documented to make extensions and changes easy. | Modularity is enforced by strictly decoupling data structures from execution logic, avoiding deep and rigid inheritance trees. Maintainability is verified by the presence of comprehensive Javadoc comments on all core API interfaces, ensuring new features can be integrated rapidly. |
Evolvability and maintainability: To ensure long-term maintainability and ease of updates, the systemâs architecture must decouple game state data from execution logic. The design must allow new game mechanics or objects to be added modularly, avoiding rigid class hierarchies.
Fault tolerance, dependability, and availability: While data integrity for long-term storage is irrelevant since all match state is kept in volatile memory, the system must gracefully handle network faults. If a playerâs connection drops, the central server must detect the failure and immediately broadcast a game-over message, resetting the lobby to prevent deadlocks and ensure continued availability for future matches.
Resource sharing: The active game world acts as a synchronized shared resource. The host is responsible for managing authoritative game mechanics and synchronizing this shared state with the guest and Spectators via continuous network message broadcasts.
Transparency: The system provides basic location transparency; clients seamlessly connect to the lobby without needing to know the physical network topology of the other players. However, failure transparency is intentionally absent; if a connection drops, the failure is explicitly exposed to the remaining users via the game over UI.
Scalability: The game is explicitly bounded to a small, finite number of simultaneous connections (one host, one guest, and passive Spectators) on a local area network. It is not expected to scale horizontally to thousands of users or handle massive data growth over time.
Security and trust: As a local LAN game without persistent or sensitive data storage, there is no need for cryptographic schemes, data encryption, or complex authentication mechanisms.
The project follows the Model-View-Controller (MVC) and Entity-Component-System (ECS) architectural patterns. The MVC pattern is used to separate the User Interface (UI) from the game logic, while the ECS pattern is used because it favors composition over inheritance, providing flexibility to add/remove behaviors (components) and logic loops (systems).
Regarding its distributed nature, the system utilizes an event-driven Client-Server architecture. Within this framework, the project implements a hybrid synchronization model that combines a leader-follower pattern for the environment with distributed authority for player movement. The session creator acts as the authoritative host for the game world, holding exclusive control over global state transitions and environmental entities, such as generating and moving barrels. However, for player characters, the system utilizes client-side authority: each client independently calculates its own characterâs movement and actions locally, transmitting these authoritative updates to the other peers. This design guarantees a consistent world state while completely eliminating input lag for the players.
To support the gameâs multiplayer requirements, the infrastructure relies on a centralized star topology where all network traffic flows through the main server.
The game is designed to be deployed and played over a Local Area Network (LAN) and the network distribution of the components depends dynamically on the playersâ roles:
Therefore, the infrastructure is entirely localized within the playersâ shared local network.
Components do not rely on static IP configuration. Instead, they dynamically discover active sessions using a custom service discovery mechanism based on UDP broadcasts: when a player attempts to join or spectate a game, their client sends a UDP discovery request to the entire subnet. The hostâs server listens for these packets and replies directly to the sender with the necessary connection details (IP, port, etc.).
Moreover, to avoid scenarios where multiple players attempt to host a lobby simultaneously on the same network, lobbies constantly broadcast their presence. If a server detects another active lobby with a higher priority, it yields its host status, shuts down its server component, and connects as a client.

The domain models the distributed system and its state synchronization through specific entities, which are mapped to the underlying infrastructure based on a partitioned authority model:
HOST, GUEST, or SPECTATOR). It acts as the
single source of truth for the game phase and connection fault tolerance.The overall state of the application is decoupled into two distinct layers:
IDLE,JUMP), facing
directions, remaining lives, and a list of active dynamic obstacles (their id, and coordinates).Communication relies on serialized JSON messages, categorized by interaction type:
Peer Discovery (UDP): Messages exchanged to resolve local network topology.
DISCOVER (Guest â LAN): Client request broadcasted to search for available game sessions.LOBBY (Host â Guest): host reply advertising its port, lobby ID, and slot availability.Session and Fault Tolerance (Server â Client): Messages orchestrating the match lifecycle, role delegation, and managing connection drops.
ROLE_ASSIGNMENT: Instructs a newly connected client of its domain role (HOST, GUEST, or SPECTATOR).GAME_START: Commands clients to instantiate the ECS world and begin the simulation loop.GUEST_DISCONNECTED: Notifies clients of a connection drop, triggering a 30-second fault-tolerance timer on the
server.GUEST_RECONNECTED: Signals the successful recovery of the guestâs connection within the allowed time frame.RESTORE_STATE: Authoritative event forcing a reconnected guest to sync back to specific coordinates and lives to
safely resume the session.GAME_OVER: Broadcasts the definitive termination of the match, carrying the reason and the winnerâs name.Game State and Commands (Client â Server): High-frequency state payloads and authoritative triggers mapping in-game events to the network.
HOST_UPDATE: Broadcasts the Hostâs avatar state alongside a comprehensive list of all active dynamic obstacles
(BarrelData).GUEST_UPDATE: Broadcasts exclusively the guestâs avatar state.PLAYER_DIED: Triggered locally when a playerâs health drops to zero. The server intercepts this and broadcasts a
GAME_OVER event.GOAL_REACHED: Triggered locally when a player successfully collides with the final objective. The server
intercepts it and declares the matchâs end via GAME_OVER.ENTITY_DESTROYED: Event instructing remote clients to remove a specific network entity from their local ECS
world.
The systemâs interaction is event-driven and asynchronous, with the server acting as a central relay for all messages, using both WebSocket for continuous state updates and UDP for initial discovery. The communication patterns naturally adapt to the applicationâs lifecycle, which can be divided into four main phases.
The interaction lifecycle begins with network discovery. To find available game sessions, clients periodically broadcast UDP datagrams across the local network. Concurrently, nodes hosting an open lobby listen for these broadcasts and reply immediately upon receiving a valid request, provided there are still open slots in the lobby. Once a lobby is discovered, the system establishes a persistent connection to guarantee stable data exchange. Clients connect to the central server, which handles the session and assigns specific roles.

During the active game phase, communication becomes continuous and is driven by the game loop. At every frame, dedicated broadcasting systems collect the current state of relevant entities and dispatch structured JSON payloads. These payloads include spatial coordinates, current animation states, facing directions, and remaining lives.
To maintain a responsive experience and minimize input lag, the game adopts a split-authority state synchronization pattern. The host dictates the state of the shared environment, such as the spawning and tracking of dynamic obstacles like barrels, alongside its own avatar. Meanwhile, the guest retains authoritative control over its own characterâs movements. The central server continuously relays these updates to the opposing player and broadcasts them to all connected spectators. Alongside this continuous stream, asynchronous events (e.g., a player reaching the goal or losing a life) trigger the dispatch of specific control messages to notify all connected nodes.

The architecture is designed to handle unexpected network interruptions. Disconnection and reconnection trigger notification messages across the system. If a disconnected guest reconnects within the allowed timeframe, the host dispatches a synchronization payload to restore the guestâs last known coordinates and lives, resuming the game seamlessly. Finally, when a winning or losing condition is met, the central server broadcasts a game-over control message. This event triggers the UI observers, transitioning players to the final summary screens and tearing down the active game session.

The system behavior is modeled as an event-driven architecture where the server acts as the central Finite State Machine (FSM), while clients react to the serverâs state transitions.
The server behavior is modeled through four states, each representing a distinct phase of the game session:
WAITING_PLAYERS: The initial state of the server immediately after the lobby is created. The server has a
host (or is waiting for one to connect), but the guest is missing. In this state, the UDP Discovery mechanism
broadcasts that the guest slot is available. Spectators can join during this phase without
triggering transitions.GAME_RUNNING: The state in which the match is active. The host and the guest continuously exchange their
respective state updates.WAITING_RECONNECT: A fault-tolerance state. It occurs when, during an active match, the guest drops the
connection. The game âfreezesâ for the guest, while the server waits for a maximum timeout (30 seconds). If the guest
reconnects within this window, the server restores its last known state and resumes the match. If the timeout
expires, the server declares a connection loss (without winner) and transitions to GAME_OVER. Similarly, if the host
disconnects, the match is immediately terminated with a connection loss for all participants.GAME_OVER: The terminal state where the match ends due to victory, defeat, or definitive disconnection. The
server can either reset the lobby to WAITING_PLAYERS or shut down entirely.
The client is modeled as a reactive state machine driven by messages received from the server and events generated by the local game loop. Its behavior differs according to the role assigned during the lobby phase, but all clients share the same lifecycle:
DISCONNECTED: The client is not connected to a session. A player searches for an available lobby through UDP
discovery, while a spectator searches for an active game to observe.CONNECTING: After discovering a lobby, the client establishes a connection and waits for a ROLE_ASSIGNMENT
message. The assigned role determines which messages the client may send during the match.WAITING_FOR_GAME: The client has joined the lobby and waits for GAME_START. It initializes the local
interface and prepares the ECS world, but does not yet process gameplay input.PLAYING: Upon receiving GAME_START, the client starts the game loop. An active player converts
keyboard input into local events and updates its own avatar immediately. The host also simulates the shared
environment, including barrel generation and movement. At regular intervals, it sends HOST_UPDATE messages
containing its avatar and barrel state, while the guest sends GUEST_UPDATE messages containing only its own avatar
state. Spectators do not send gameplay updates.
During PLAYING, local movement is intentionally handled without waiting for a network round trip, eliminating input
latency for the controlled avatar. Remote entities are updated from the most recent network snapshot, and incoming
authoritative coordinates overwrite stale local values to preserve eventual consistency. Local collision and goal
events are published as PLAYER_DIED or GOAL_REACHED messages; the server validates the resulting session
transition and broadcasts the final outcome to every connected client.
WAITING_RECONNECT: If the guest loses its connection, its local gameplay is suspended while the client attempts
to reconnect to the session. A successful reconnection causes the client to receive a RESTORE_STATE message with
the avatarâs coordinates and remaining lives, after which the world and game loop resume. To detect this connection
drop locally, the guest and spectator clients monitor the incoming HOST_UPDATE messages. If no updates are received
for 1.5 seconds, the clients assume a network drop and freeze their local rendering to prevent divergent gameplay. If
the connection remains broken and no messages arrive for 40 seconds, the clients locally time out, clean up the
session, and force a transition to GAME_OVER.GAME_OVER: When the client receives GAME_OVER, it stops processing gameplay updates, displays the result
identified by the server, and releases the active game resources. The user can then return to the main menu or exit
the application.This chapter details the specific technology-dependent choices made to realize the architectural design, focusing on network protocols, data serialization, and the frameworks exploited.
DISCOVER datagrams on port 8081 across the LAN, and available hosts reply
directly with the WebSocket connection details.JsonObject to automatically map incoming and
outgoing JSON payloads directly to immutable Java record classes (e.g., HostUpdateMessage, GuestUpdateMessage).
This choice eliminated boilerplate parsing code while maintaining high human-readability, which greatly sped up the
debugging process.World instance. Once a match concludes or the central server shuts down, this ephemeral game state is completely
flushed./play endpoint is granted the authoritative host
role, the second becomes the guest, and any subsequent users (or those connecting directly to the /spectate
endpoint) are restricted to read-only spectator access.The project relies on a specific technology stack to achieve its concurrency and rendering goals:
record classes are exploited to define immutable ECS Components (e.g., PositionComponent,
VelocityComponent) and network messages, ensuring thread safety.DatagramSocket for UDP broadcasting.inbound.guest_update), where the dedicated ECS receiver system consumes them asynchronously, preventing network
operations from blocking the main game loop.Canvas and a GraphicsContext to manually draw and clear sprite sheets frame-by-frame. The core game loop is driven
by a JavaFX AnimationTimer, which triggers the ECS engineâs main update cycle to process physics and render
the graphics concurrently at a targeted 60 FPS.To guarantee the overall reliability, state consistency, and fault tolerance of the distributed architecture, the validation phase was conducted through a combination of automated unit and integration tests, alongside manual acceptance testing.
Automated testing was implemented using JUnit 5 and managed via the Gradle build tool, and can be run via
./gradlew test. These tests are also used to validate the codebase within continuous integration pipelines ensuring
that every pull request is validated before being merged.
WorldTest verifies the core ECS mechanics (adding/removing entities and components).FactoryTest ensures entities are assembled with the correct components.PhysicsSystemTest, GravitySystemTest, etc.) are used to verify each systemâs
behavior in isolation, including edge cases like boundary clamping and event dispatching, by using a real,
in-memory WorldImpl instance and manually invoking the update method.These tests are useful to verify the functional requirements related to horizontal movement, jumping, collision detection, etc., as well as the modularity non-functional requirement.
EndGameScenariosTest verifies direct win and death callbacks and guest disconnection handling.LobbyVerticleTest, ClientVerticleTest, and DiscoveryResponderTest verify isolated network and discovery
behavior, including WebSocket role assignment and broadcasting, client message forwarding through the event bus,
and UDP discovery responses.StateReceiverSystemTest and NetworkBroadcastSystemTest verify the correct integration between the network and
the game loop, ensuring that messages arriving on the event bus update the local ECS entities and that outgoing
state payloads are correctly formatted.While automated tests comprehensively covered the programmatic logic and network routing, the real-time distributed nature of the game required manual End-to-End (E2E) testing in a production-like LAN environment with multiple physical machines. Evaluating subjective quality metricsâsuch as the smoothness of the JavaFX rendering and the tactile responsiveness of controlsâalongside simulating physical network adapter disconnections to validate the fault-tolerance window, necessitated human observation and manual intervention.
Before deploying the software, the target machine must meet the following software requirements:
To deploy the application, users can download the pre-built JAR file from the release section and execute it directly
using java -jar donkeykong-fat.jar in the same directory where the JAR is located.
Alternatively, the source code can be cloned from the repository:
git clone https://github.com/mircoterenzi/donkey-kong
cd donkey-kong
and the application can be run directly using the Gradle wrapper, using ./gradlew run on Linux/macOS or
gradlew.bat run on Windows. This approach is particularly useful for developers who wish to modify the code or
contribute to the project.
Main menu: Upon launch, the user is presented with a graphical interface offering two options:
Note that, if the lobby is already full (i.e., two players are connected), the system will automatically redirect the user to the spectate mode, ensuring that he can still enjoy the game as an observer.

â / A to move left, â / D to move right.â / W to climb up ladders, â / S to climb down.spacebar to jump over obstacles and gaps.
Game objective: Navigate your avatar from the bottom of the screen to the top to rescue Pauline. Avoid the rolling barrels spawned by Donkey Kong. If you collide with a barrel, you will lose a life and respawn at the bottom. The game ends when a player reaches Pauline or loses all 3 lives.
I am highly satisfied with the outcome of this project. Building a real-time multiplayer game from scratch required meticulous planning, but it ultimately provided a deep understanding of distributed synchronization and network routing.
Regarding the projectâs strengths, I consider the fault-tolerance mechanisms and the seamless LAN matchmaking to be the highlights of our work, resulting in a highly accessible and resilient application, alongside the overall fluidity and responsiveness of the gameplay. The primary weakness of the product is tied to its network topology, where the authoritative server is hosted directly on one of the client machines. While perfectly suited for a small LAN environment, scaling the system to a wide area network (WAN) or supporting concurrent multi-lobby sessions would require extracting the backend logic into a dedicated, standalone microservice.
Within the group, I had an excellent and highly productive experience collaborating with Terenzi. While he focused on the core ECS architecture and the discovery mechanism, my specific contributions centered on the structural network architecture, fault tolerance, and validation. I took charge of engineering the core network communication layer using Eclipse Vert.x. I was responsible for defining the message exchange protocols, managing the EventBus routing, and successfully decoupling the asynchronous network payloads from the synchronous game engine. Furthermore, I led the validation phase through rigorous testing and implemented the client-side fault-tolerance logic to ensure smooth recovery from network drops.
I enjoyed working on this project because it allowed me to explore both distributed-systems concepts and real-time multiplayer game development. I am particularly satisfied with the final result and with the way the different architectural components were integrated.
Initially, I focused on the design and implementation of the Entity-Component-System architecture and the core game logic. I contributed to defining how entities, components, and systems interact, keeping the game logic modular and extensible. In particular, I worked on the movement, physics, gravity, collision-detection and collision-resolution systems, as well as on animation and game-state management. Regarding the distributed aspects of the project, one of my main contributions was the design and implementation of an automatic LAN lobby-discovery mechanism. Instead of requiring players to manually exchange IP addresses and configure connection details, clients can search the local network for available game sessions. When a suitable lobby is found, the client connects automatically; otherwise, a new lobby is created and the player becomes the host. The same mechanism also supports spectator discovery and includes a conflict-resolution procedure for handling multiple lobbies started simultaneously. I also contributed to the network communication layer, which manages the exchange of messages between the host, guest, and spectators. This layer is responsible for forwarding game-state updates, broadcasting information to spectators, synchronizing player and barrel state, handling game-start and game-over events, and managing temporary guest disconnections and reconnections.
Overall, I believe that the main strength of the project is its modularity. The ECS architecture separates data from behavior, while the networking and user-interface responsibilities are divided into dedicated components. This makes it possible to add new features or modify existing ones without requiring extensive changes to unrelated parts of the system. Moreover, regarding network synchronization, since the project follows a hybrid authority model: each client simulates the movement and physics of its own player locally and player collisions and damage are evaluated locally instead of relying on a strictly server-authoritative model. This improves responsiveness and makes gameplay smoother by reducing visible latency effects, such as rubber-banding during movement and jumps. The main drawback of this approach is the trade-off between responsiveness and security. Since collision, damage, and death decisions are made by the clients themselves, a malicious client could potentially tamper with its local game state or send fraudulent events. A stricter server-authoritative architecture would provide stronger protection against cheating, but would also introduce additional latency and complexity.
While the current implementation successfully fulfills the core requirements of a distributed, real-time multiplayer platformer, several avenues for improvement and architectural expansion remain.
MapFactory. Future iterations could introduce dynamic map loading by parsing external configuration files (e.g.,
JSON or Tiled map formats). This would require extending the network protocol to broadcast a LEVEL_LOAD message,
ensuring that all distributed clients successfully load and synchronize the same level assets before the GAME_START
event is triggered.