programmieren-projekt/src/Board.java

99 lines
2.4 KiB
Java

import java.util.ArrayList;
import java.util.List;
public class Board {
private List<HitResponse> hits;
private List<Ship> ships;
private final int size;
public Board(int size) {
this.size = size;
this.ships = new ArrayList<>();
this.hits = new ArrayList<>();
this.createShip(size - 13);
}
public synchronized HitResponse hit (Point point){
HitResponse response = new HitResponse(HitResponseType.MISS,point);
for (int i = 0; i < this.ships.size(); i++) {
HitResponseType type = this.ships.get(i).shootOnShip(point);
if ( type == HitResponseType.SUNK) {
for (int ii = 0; ii < this.ships.size(); ii++) {
if (!this.ships.get(ii).isSunk()) {
response.setType(type);
this.addHits(response);
return response;
}
}
response.setType(HitResponseType.VICTORY);
this.addHits(response);
return response;
} else if (type == HitResponseType.HIT) {
response.setType(type);
this.addHits(response);
return response;
}
}
this.addHits(response);
return response;
}
private void propagateSunk(Point p) {
HitResponse hit = this.getHitResponseOnPoint(p);
if (hit == null || hit.getType() != HitResponseType.HIT) return;
hit.setType(HitResponseType.SUNK);
propagateSunk(new Point(p.getX() + 1, p.getY()));
propagateSunk(new Point(p.getX() - 1, p.getY()));
propagateSunk(new Point(p.getX(), p.getY() + 1));
propagateSunk(new Point(p.getX(), p.getY() - 1));
}
private void createShip(int semester){
List<ShipData> shipData = Ship.semeterList.get(semester -1);
for (int i = 0; i < shipData.size(); i++) {
this.ships.add(new Ship(shipData.get(i).size(), shipData.get(i).name()));
}
}
public List<Ship> getShips() {
return ships;
}
public synchronized boolean addHits(HitResponse hitResponse) {
if (this.getHitResponseOnPoint(hitResponse.getPoint()) == null){
this.hits.add(hitResponse);
//Propagate sunk for display purposes
if (hitResponse.getType() == HitResponseType.SUNK) {
hitResponse.setType(HitResponseType.HIT);
propagateSunk(hitResponse.getPoint());
}
return true;
}
return false;
}
public synchronized HitResponse getHitResponseOnPoint(Point point) {
for (int i = 0; i < this.hits.size(); i++){
if (this.hits.get(i).getPoint().equals(point)){
return this.hits.get(i);
}
}
return null;
}
public int getSize() {
return this.size;
}
}