Search code examples
c#design-decisionsjagged-arrays

C# Battleships Class/Structure


greetings, im am new to programming and at the moment developing a clone of the game battleships. i need to implement a fleet of 5 ships. this is what i have done so far:

class Cell holds the status of a table cell:

public class Cell
{
    // class for holding cell status information
    public enum cellState
    {
        WATER,
        SCAN,
        SHIPUNIT,
        SHOT,
        HIT
    }

    public Cell()
    {
        currentCell = cellState.WATER;
    }

    public Cell(cellState CellState)
    {
        currentCell = CellState;
    }

    public cellState currentCell { get; set; }
}

class GridUnit holds table cell info:

public class GridUnit
{
    public GridUnit()
    {
        Column = 0;
        Row = 0;
    }

    public GridUnit(int column, int row)
    {
        Column = column;
        Row = row;
    }

    public int Column { get; set; }

    public int Row { get; set; }
}

finally class Shipunit contains both the above classes and acts as a wrapper for state info of an individual cell:

public class ShipUnit
{
    public GridUnit gridUnit = new GridUnit();

    public Cell cell = new Cell(Cell.cellState.SHIPUNIT);
}

at the moment i am thinking about implementing the fleet info in a Jagged Array like this:

ShipUnit[][] Fleet = new ShipUnit[][]
{
new ShipUnit[] {ShipUnit,ShipUnit,ShipUnit,ShipUnit,ShipUnit},
new ShipUnit[] {ShipUnit,ShipUnit,ShipUnit,ShipUnit},
new ShipUnit[] {ShipUnit,ShipUnit,ShipUnit}
new ShipUnit[] {ShipUnit,ShipUnit,ShipUnit}
new ShipUnit[] {ShipUnit,ShipUnit}
};

i realize the last bit of code does not work. it is only for presenting the idea.

but the problem being i need a field that states what type of ship each line of jagged array represent and i dont think it is practical to state this info in every cell information.

so i would like some ideas of implementation of this issue from you.

thank you.


Solution

  • class Ship
    {
        ShipUnit[] shipUnits;
        string type;
        public Ship(int length, string type)
        {
            shipUnits = new ShipUnit[length];
            this.type = type;
        }
    }
    
    Ship[] fleet = new Ship[5];
    fleet[0] = new Ship(5, "Carrier");
    fleet[1] = new Ship(4, "Battleship");
    fleet[2] = new Ship(3, "Submarine");
    fleet[3] = new Ship(3, "Something else");
    fleet[4] = new Ship(2, "Destroyer");