Battleship-JavaScript icon indicating copy to clipboard operation
Battleship-JavaScript copied to clipboard

Battleship

Open XRIDER123 opened this issue 1 year ago • 0 comments

class Ship { private final String name; private final int length; private Cell position; private boolean horizontal; private int health;

public Ship(String name, int length) {
    this.name = name;
    this.length = length;
    this.health = length;
}

public String getName() {
    return name;
}

public int getLength() {
    return length;
}

public int getHealth() {
    return health;
}

public void setPosition(Cell position, boolean horizontal) {
    this.position = position;
    this.horizontal = horizontal;
}

public boolean isPositioned() {
    return position != null;
}

public boolean isInBounds() {
    if (!isPositioned()) {
        return false;
    }
    int x = position.getColumn();
    int y = position.getRow();
    if (horizontal) {
        if (x + length > 10) {
            return false;
        }
    } else {
        if (y + length > 10) {
            return false;
        }
    }
    return true;
}

public boolean intersectsWith(Cell cell) {
    if (!isPositioned()) {
        return false;
    }
    int x = cell.getColumn();
    int y = cell.getRow();
    int startX = position.getColumn();
    int startY = position.getRow();
    if (horizontal) {
        if (y != startY) {
            return false;
        }
        if (x < startX || x >= startX + length) {
            return false;
        }
    } else {
        if (x != startX) {
            return false;
        }
        if (y < startY || y >= startY + length) {
            return false;
        }
    }
    return true;
}

XRIDER123 avatar Nov 21 '24 19:11 XRIDER123