I wanted to make a very simply Battleship game in Java, any feedback is welcome.
Nevermind the getters / setters. Just assume they are there.
class Game {
Board board = new Board();
void playGame() {
Scanner scanner = new Scanner(System.in);
while (!board.allShipsSank()) {
System.out.println("Enter missile locations, x and y.");
int x = scanner.nextInt();
int y = scanner.nextInt();
board.shoot(x, y);
}
}
}
class Board {
Set<Ship> ships = new HashSet<>();
boolean allShipsSank() {
for (Ship ship : ships)
if (!ship.isSank())
return false;
return true;
}
void shoot(int x, int y) {
for (Ship ship : ships) {
if (ship.shipGeographic.orientation == ShipGeographic.Orientation.HORIZONTAL) {
if (y == ship.shipGeographic.y && ship.shipGeographic.x <= x && x <= ship.shipGeographic.x + ship.len) {
ship.missileAt(x - ship.shipGeographic.x);
return;
}
}
if (ship.shipGeographic.orientation == ShipGeographic.Orientation.VERTICAL) {
if (x == ship.shipGeographic.x && ship.shipGeographic.y <= y && y <= ship.shipGeographic.y + ship.len) {
ship.missileAt(ship.shipGeographic.y + y);
return;
}
}
}
}
}
class ShipGeographic {
enum Orientation {
HORIZONTAL, VERTICAL;
}
int x;
int y;
ShipGeographic.Orientation orientation;
}
class Ship {
// length of the ship
int len;
// Nodes where this ship has been hit
Set<Integer> hit = new HashSet<>();
// Where this Ship is
ShipGeographic shipGeographic;
Ship(int len) {
this.len = len;
}
boolean isSank() {
return hit.size() == len;
}
// For example, if ship is hit at head, parameter is 0
// Missile at same node of ship has no effect
void missileAt(int offsetFromLen) {
if (hit.add(offsetFromLen)) {
System.out.println("boom!");
System.out.println(hit);
}
}
}
here is how I initialize and run the game:
class App {
public static void main(String[] args) {
Game game = new Game();
// Just some sample data!
{
Ship ship = new Ship(3);
ShipGeographic shipGeographic = new ShipGeographic();
shipGeographic.orientation = ShipGeographic.Orientation.HORIZONTAL;
shipGeographic.x = 1;
shipGeographic.y = 1;
ship.shipGeographic = shipGeographic;
game.board.ships.add(ship);
}
game.playGame();
}
}
A sample run:
Enter missile locations, x and y.
1
1
boom!
[0]
Enter missile locations, x and y.
5
5
Enter missile locations, x and y.
2
1
boom!
[0, 1]
Enter missile locations, x and y.
3
1
boom!
[0, 1, 2]
Process finished with exit code 0