Class Server

java.lang.Object
com.alessiocascini.battleship.server.Server

public class Server extends Object
The main entry point for the Battleship game server. This class manages client connections, player synchronization during the placement phase, and tracks the state of the game (ship positions and hits).
Author:
Alessio Cascini
  • Constructor Summary

    Constructors
    Constructor
    Description
     
  • Method Summary

    Modifier and Type
    Method
    Description
    static int
    Calculates the number of ships based on the total number of occupied cells.
    static boolean
     
    static void
    main(String[] args)
    Starts the server on port 5000 and handles the game lifecycle.
    static int[][]
    processMove(boolean isPlayerOne, int[] move)
    Processes a move from a player and checks if it's a hit, a miss, or a sinking move.
    static void
    storeShipPositions(int[][][] positions)
    Stores the coordinates of ships placed by a player.

    Methods inherited from class Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • Server

      public Server()
  • Method Details

    • main

      public static void main(String[] args)
      Starts the server on port 5000 and handles the game lifecycle. Phase 1: Accepts connections for ship placement. Phase 2: Accepts connections for game moves.
      Parameters:
      args - Command line arguments (not used)
    • getShipCount

      public static int getShipCount()
      Calculates the number of ships based on the total number of occupied cells.
      Returns:
      The current ship count
    • storeShipPositions

      public static void storeShipPositions(int[][][] positions)
      Stores the coordinates of ships placed by a player. This method is synchronized to safely update the game state and notify waiting threads.
      Parameters:
      positions - A 3D array containing the coordinates for each ship
    • isWaitingForSecondPlayer

      public static boolean isWaitingForSecondPlayer()
      Returns:
      true if the server is still waiting for the second player to finish placement
    • processMove

      public static int[][] processMove(boolean isPlayerOne, int[] move)
      Processes a move from a player and checks if it's a hit, a miss, or a sinking move.
      Parameters:
      isPlayerOne - Boolean indicating if the attacker is Player 1
      move - Array representing the [row, col] of the move
      Returns:
      An empty array for a miss, an array with one cell for a hit, or all ship cells if the ship is sunk.