Skip to content

Battleship #1

@XRIDER123

Description

@XRIDER123

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;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions