javacw#5
111unknown
java
2 years ago
2.3 kB
2
Indexable
Never
import java.util.*; public class BattleShips { private static class Ship { int hp; boolean isReal; int length; Ship(){ this.hp = 0; this.isReal = false; this.length = 0; } } private static class Score { double sunk; double damaged; double notTouched; double points; Score() { this.sunk = 0.0; this.damaged = 0.0; this.notTouched = 0.0; this.points = 0.0; } void checkShips(Ship[] ships) { for(int i=0;i<ships.length;i++) { if (ships[i].isReal){ if (ships[i].hp == 0) { this.sunk++; } else if (ships[i].hp > 0 && ships[i].hp != ships[i].length) { this.damaged++; } else { this.notTouched++; } } } this.points = this.sunk * 1 + this.damaged * 0.5 - this.notTouched * 1; } } public static Map<String, Double> damagedOrSunk(final int[][] board, final int[][] attacks) { /*Starting game Initialize*/ Map<String, Double> map = new HashMap<>(); Ship[] ships = new Ship[]{new Ship(), new Ship(), new Ship()}; Score score = new Score(); int attacksCount = attacks.length; for (int[] i : board){ for(int j : i){ if (j != 0) { ships[j==1?0:j==2?1:2].isReal = true; ships[j==1?0:j==2?1:2].hp++; ships[j==1?0:j==2?1:2].length++; } } } //Calculating attacks for (int[] i : attacks) { int x = i[0]-1; int y = board.length-i[1]; if (board[y][x] != 0) { ships[board[y][x]==1?0:board[y][x]==2?1:2].hp--; } } score.checkShips(ships); //Creating results map.put("sunk", score.sunk); map.put("damaged", score.damaged); map.put("notTouched", score.notTouched); map.put("points", score.points); return map; } }