HoangHai-portliofio-projects / Projects / 4.Battleship_java / src / Ship.java
Ship.java
Raw
import java.util.ArrayList;
import java.util.Arrays;

public class Ship {
    String name;

    ArrayList <int[]> shipLocation = new ArrayList<>();
    
    public void createRandomLocation() {
        String randomDirection;
        int x, y;

        int ran1 = (int) (Math.random()* ( (1-0+1 ) + 0));
        randomDirection = (ran1 == 0 ? "ngang" : "doc");

        if (randomDirection.equals("doc")) {
            x = (int) (Math.random()*((4-0 +1)+0));
            y = (int) (Math.random()*(((6-0) + 1) + 0));

            int[] firstCell = new int[2];
            int[] secondCell = new int [2];
            int[] thirdCell = new int [2];

            //address HODLDER VALUE of each Cells of Ship's address
            firstCell[0] = x;
            firstCell[1] = y;
            secondCell[0] = x+1;
            secondCell[1] = y;
            thirdCell[0] = x+2;
            thirdCell[1] = y;
            this.shipLocation.add(firstCell);
            this.shipLocation.add(secondCell);
            this.shipLocation.add(thirdCell);
        } else {
            y = (int) (Math.random()* ((4-0 +1)+0) );
            
            x = (int) (Math.random()* ((6-0 +1)+0) );

            int[] firstCell = new int[2];
            int[] secondCell = new int [2];
            int[] thirdCell = new int [2];

            //address HODLDER VALUE of each Cells of Ship's address
            firstCell[0] = x;
            firstCell[1] = y;
            secondCell[0] = x;
            secondCell[1] = y+1;
            thirdCell[0] = x;
            thirdCell[1] = y+2;
            this.shipLocation.add(firstCell);
            this.shipLocation.add(secondCell);
            this.shipLocation.add(thirdCell);

        }
    }
    
    public Ship () {
        createRandomLocation();
//        System.out.println("A new ship is created");
//        for (int [] arr : this.shipLocation) {
//            System.out.println(Arrays.toString(arr));
//        }
    }
}