package lect78_impl.model; import java.util.ArrayList; import java.util.List; import lect78_impl.model.Position; /** * @overview A collection class that manages a set of tanks for a player * * @attributes * tanks List List of tanks in the set * currentIndex Integer Index of the currently active tank * maxTanks Integer Maximum number of tanks allowed * owner Player The player who owns this tank set */ public class TankSet { private List tanks; private int currentIndex; private int maxTanks; private Player owner; /** * @effects Creates an empty tank set with specified maximum capacity */ public TankSet(Player owner, int maxTanks) { this.owner = owner; this.maxTanks = maxTanks; this.tanks = new ArrayList<>(); this.currentIndex = 0; } /** * @effects Adds a tank to the set if space available * @return true if added successfully, false otherwise */ public boolean addTank(Tank tank) { if (tanks.size() >= maxTanks) { return false; } tanks.add(tank); tank.setOwner(owner); return true; } /** * @effects Removes a tank from the set * @return true if removed successfully, false if tank not found */ public boolean removeTank(Tank tank) { if (!tanks.contains(tank)) { return false; } int index = tanks.indexOf(tank); tanks.remove(tank); // Adjust current index if needed if (tanks.isEmpty()) { currentIndex = 0; } else if (currentIndex >= tanks.size()) { currentIndex = 0; } else if (index < currentIndex) { currentIndex--; } return true; } /** * @effects Removes a tank by its ID * @return true if removed successfully, false if ID not found */ public boolean removeTankById(int tankId) { for (Tank tank : tanks) { if (tank.getId() == tankId) { return removeTank(tank); } } return false; } /** * @effects Gets the currently active tank * @return The active tank or null if set is empty */ public Tank getActiveTank() { if (tanks.isEmpty()) { return null; } return tanks.get(currentIndex); } /** * @effects Switches to the next available tank * @return true if switched successfully, false if no other tanks */ public boolean nextTank() { if (tanks.size() <= 1) { return false; } currentIndex = (currentIndex + 1) % tanks.size(); return true; } /** * @effects Gets a tank by its ID * @return The tank or null if not found */ public Tank getTankById(int id) { for (Tank tank : tanks) { if (tank.getId() == id) { return tank; } } return null; } /** * @effects Gets the number of tanks in the set */ public int size() { return tanks.size(); } /** * @effects Checks if the set is empty */ public boolean isEmpty() { return tanks.isEmpty(); } /** * @effects Gets all tanks in the set */ public List getAllTanks() { return new ArrayList<>(tanks); // Return a copy to prevent external modification } /** * @effects Gets all tanks at a specific position */ public List getTanksAt(Position pos) { List result = new ArrayList<>(); for (Tank tank : tanks) { if (tank.getPosition().equals(pos)) { result.add(tank); } } return result; } }