Search in sources :

Example 1 with AbstractActionableObject

use of spacesettlers.objects.AbstractActionableObject in project spacesettlers by amymcgovern.

the class AggressiveFlagCollectorTeamClient method getTeamPurchases.

@Override
public /**
 * If there is enough resourcesAvailable, buy a base.  Place it by finding a ship that is sufficiently
 * far away from the existing bases
 */
Map<UUID, PurchaseTypes> getTeamPurchases(Toroidal2DPhysics space, Set<AbstractActionableObject> actionableObjects, ResourcePile resourcesAvailable, PurchaseCosts purchaseCosts) {
    HashMap<UUID, PurchaseTypes> purchases = new HashMap<UUID, PurchaseTypes>();
    double BASE_BUYING_DISTANCE = 200;
    boolean bought_base = false;
    int numBases, numShips;
    // count the number of ships for the base/ship buying algorithm
    numShips = 0;
    for (AbstractActionableObject actionableObject : actionableObjects) {
        if (actionableObject instanceof Ship) {
            numShips++;
        }
    }
    // try to balance
    if (purchaseCosts.canAfford(PurchaseTypes.BASE, resourcesAvailable)) {
        for (AbstractActionableObject actionableObject : actionableObjects) {
            if (actionableObject instanceof Ship) {
                Ship ship = (Ship) actionableObject;
                Set<Base> bases = space.getBases();
                // how far away is this ship to a base of my team?
                boolean buyBase = true;
                numBases = 0;
                for (Base base : bases) {
                    if (base.getTeamName().equalsIgnoreCase(getTeamName())) {
                        numBases++;
                        double distance = space.findShortestDistance(ship.getPosition(), base.getPosition());
                        if (distance < BASE_BUYING_DISTANCE) {
                            buyBase = false;
                        }
                    }
                }
                if (buyBase && numBases < numShips) {
                    purchases.put(ship.getId(), PurchaseTypes.BASE);
                    bought_base = true;
                    System.out.println("Aggressive Flag Collector is buying a base!");
                    break;
                }
            }
        }
    }
    // can I buy a ship?
    if (purchaseCosts.canAfford(PurchaseTypes.SHIP, resourcesAvailable) && bought_base == false) {
        for (AbstractActionableObject actionableObject : actionableObjects) {
            if (actionableObject instanceof Base) {
                Base base = (Base) actionableObject;
                purchases.put(base.getId(), PurchaseTypes.SHIP);
                System.out.println("Aggressive Flag Collector is buying a ship!");
                break;
            }
        }
    }
    return purchases;
}
Also used : AbstractActionableObject(spacesettlers.objects.AbstractActionableObject) HashMap(java.util.HashMap) PurchaseTypes(spacesettlers.actions.PurchaseTypes) Ship(spacesettlers.objects.Ship) UUID(java.util.UUID) Base(spacesettlers.objects.Base)

Example 2 with AbstractActionableObject

use of spacesettlers.objects.AbstractActionableObject in project spacesettlers by amymcgovern.

the class AggressiveHeuristicAsteroidCollectorTeamClient method getTeamPurchases.

@Override
public /**
 * If there is enough resourcesAvailable, buy a base.  Place it by finding a ship that is sufficiently
 * far away from the existing bases
 */
Map<UUID, PurchaseTypes> getTeamPurchases(Toroidal2DPhysics space, Set<AbstractActionableObject> actionableObjects, ResourcePile resourcesAvailable, PurchaseCosts purchaseCosts) {
    HashMap<UUID, PurchaseTypes> purchases = new HashMap<UUID, PurchaseTypes>();
    double BASE_BUYING_DISTANCE = 200;
    boolean bought_base = false;
    if (purchaseCosts.canAfford(PurchaseTypes.BASE, resourcesAvailable)) {
        for (AbstractActionableObject actionableObject : actionableObjects) {
            if (actionableObject instanceof Ship) {
                Ship ship = (Ship) actionableObject;
                Set<Base> bases = space.getBases();
                // how far away is this ship to a base of my team?
                double maxDistance = Double.MIN_VALUE;
                for (Base base : bases) {
                    if (base.getTeamName().equalsIgnoreCase(getTeamName())) {
                        double distance = space.findShortestDistance(ship.getPosition(), base.getPosition());
                        if (distance > maxDistance) {
                            maxDistance = distance;
                        }
                    }
                }
                if (maxDistance > BASE_BUYING_DISTANCE) {
                    purchases.put(ship.getId(), PurchaseTypes.BASE);
                    bought_base = true;
                    // System.out.println("Buying a base!!");
                    break;
                }
            }
        }
    }
    // see if you can buy EMPs
    if (purchaseCosts.canAfford(PurchaseTypes.POWERUP_EMP_LAUNCHER, resourcesAvailable)) {
        for (AbstractActionableObject actionableObject : actionableObjects) {
            if (actionableObject instanceof Ship) {
                Ship ship = (Ship) actionableObject;
                if (!ship.getId().equals(asteroidCollectorID) && !ship.isValidPowerup(PurchaseTypes.POWERUP_EMP_LAUNCHER.getPowerupMap())) {
                    purchases.put(ship.getId(), PurchaseTypes.POWERUP_EMP_LAUNCHER);
                }
            }
        }
    }
    // can I buy a ship?
    if (purchaseCosts.canAfford(PurchaseTypes.SHIP, resourcesAvailable) && bought_base == false) {
        for (AbstractActionableObject actionableObject : actionableObjects) {
            if (actionableObject instanceof Base) {
                Base base = (Base) actionableObject;
                purchases.put(base.getId(), PurchaseTypes.SHIP);
                break;
            }
        }
    }
    return purchases;
}
Also used : AbstractActionableObject(spacesettlers.objects.AbstractActionableObject) HashMap(java.util.HashMap) PurchaseTypes(spacesettlers.actions.PurchaseTypes) Ship(spacesettlers.objects.Ship) UUID(java.util.UUID) Base(spacesettlers.objects.Base)

Example 3 with AbstractActionableObject

use of spacesettlers.objects.AbstractActionableObject in project spacesettlers by amymcgovern.

the class Team method getTeamPurchases.

/**
 * Ask the team if they want to purchase anything this turn.  You can only
 * purchase one item per turn and only if you have enough resourcesAvailable.
 *
 * @param space
 * @return
 */
public Map<UUID, PurchaseTypes> getTeamPurchases(Toroidal2DPhysics space) {
    Map<UUID, PurchaseTypes> purchase = new HashMap<UUID, PurchaseTypes>();
    final Toroidal2DPhysics clonedSpace = space.deepClone();
    final Set<AbstractActionableObject> clonedActionableObjects = getTeamActionableObjectsClone(space);
    final PurchaseCosts clonedPurchaseCost = getPurchaseCostClone();
    final ResourcePile clonedResources = new ResourcePile(availableResources);
    // if the previous thread call hasn't finished, then just return default
    if (executor == null || executor.isTerminated()) {
        executor = Executors.newSingleThreadExecutor();
    } else {
        return purchase;
    }
    // System.out.println("exec " + executor.isTerminated());
    Future<Map<UUID, PurchaseTypes>> future = executor.submit(new Callable<Map<UUID, PurchaseTypes>>() {

        public Map<UUID, PurchaseTypes> call() throws Exception {
            return teamClient.getTeamPurchases(clonedSpace, clonedActionableObjects, clonedResources, clonedPurchaseCost);
        }
    });
    try {
        // start
        purchase = future.get(SpaceSettlersSimulator.TEAM_ACTION_TIMEOUT, TimeUnit.MILLISECONDS);
    // finished in time
    } catch (TimeoutException e) {
        // was terminated
        // return empty map, don't buy anything
        System.out.println(getTeamName() + " timed out in getTeamPurchases");
        purchase = new HashMap<UUID, PurchaseTypes>();
    } catch (InterruptedException e) {
        // we were interrupted (should not happen but lets be good programmers)
        // return empty map, don't buy anything
        purchase = new HashMap<UUID, PurchaseTypes>();
        e.printStackTrace();
    } catch (ExecutionException e) {
        // the executor threw and exception (should not happen but lets be good programmers)
        // return empty map, don't buy anything
        purchase = new HashMap<UUID, PurchaseTypes>();
        e.printStackTrace();
    } catch (RejectedExecutionException e) {
        System.err.println("exec" + executor.isTerminated());
        e.printStackTrace();
    } catch (Exception e) {
        purchase = new HashMap<UUID, PurchaseTypes>();
        e.printStackTrace();
    }
    executor.shutdownNow();
    return purchase;
}
Also used : ResourcePile(spacesettlers.objects.resources.ResourcePile) AbstractActionableObject(spacesettlers.objects.AbstractActionableObject) HashMap(java.util.HashMap) PurchaseTypes(spacesettlers.actions.PurchaseTypes) TimeoutException(java.util.concurrent.TimeoutException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) Toroidal2DPhysics(spacesettlers.simulator.Toroidal2DPhysics) PurchaseCosts(spacesettlers.actions.PurchaseCosts) UUID(java.util.UUID) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) HashMap(java.util.HashMap) Map(java.util.Map) TimeoutException(java.util.concurrent.TimeoutException)

Example 4 with AbstractActionableObject

use of spacesettlers.objects.AbstractActionableObject in project spacesettlers by amymcgovern.

the class SpaceSettlersSimulator method handlePurchases.

/**
 * Handle purchases for a team
 *
 * @param team
 * @param purchases
 */
private void handlePurchases(Team team, Map<UUID, PurchaseTypes> purchases) {
    // handle teams that don't purchase
    if (purchases == null) {
        return;
    }
    for (UUID key : purchases.keySet()) {
        PurchaseTypes purchase = purchases.get(key);
        // skip the purchase if there isn't enough resourcesAvailable
        if (!team.canAfford(purchase)) {
            continue;
        }
        // get the object where the item is to be purchased (on on whom it is to be purchased)
        AbstractActionableObject purchasingObject = (AbstractActionableObject) simulatedSpace.getObjectById(key);
        // can only make purchases for your team
        if (!purchasingObject.getTeamName().equalsIgnoreCase(team.getTeamName())) {
            continue;
        }
        switch(purchase) {
            case BASE:
                // only purchase if this is a ship (can't buy a base next to a base)
                if (purchasingObject instanceof Ship) {
                    Ship ship = (Ship) purchasingObject;
                    // set the base just away from the ship (to avoid a collision)
                    Position newPosition = simulatedSpace.getRandomFreeLocationInRegion(random, Base.BASE_RADIUS, (int) ship.getPosition().getX(), (int) ship.getPosition().getY(), (6 * (ship.getRadius() + Base.BASE_RADIUS)));
                    // make the new base and add it to the lists
                    Base base = new Base(newPosition, team.getTeamName(), team, false);
                    simulatedSpace.addObject(base);
                    team.addBase(base);
                    // charge the team for the purchase
                    team.decrementAvailableResources(team.getCurrentCost(purchase));
                    team.updateCost(purchase);
                }
                break;
            case SHIP:
                // can only buy if there are enough ships
                if (team.getShips().size() >= team.getMaxNumberShips())
                    break;
                // Ships can only be purchased near a base (which launches them)
                if (purchasingObject instanceof Base) {
                    Base base = (Base) purchasingObject;
                    // set the new ship just away from the base (to avoid a collision)
                    Position newPosition = simulatedSpace.getRandomFreeLocationInRegion(random, Ship.SHIP_RADIUS, (int) base.getPosition().getX(), (int) base.getPosition().getY(), (10 * (base.getRadius() + Ship.SHIP_RADIUS)));
                    // make the new ship and add it to the lists
                    Ship ship = new Ship(team.getTeamName(), team.getTeamColor(), newPosition);
                    simulatedSpace.addObject(ship);
                    team.addShip(ship);
                    // charge the team for the purchase
                    team.decrementAvailableResources(team.getCurrentCost(purchase));
                    team.updateCost(purchase);
                }
                break;
            case POWERUP_SHIELD:
                purchasingObject.addPowerup(SpaceSettlersPowerupEnum.TOGGLE_SHIELD);
                // charge the team for the purchase
                team.decrementAvailableResources(team.getCurrentCost(purchase));
                team.updateCost(purchase);
                System.out.println("Buying a shield");
                break;
            case POWERUP_EMP_LAUNCHER:
                // only purchase if this is a ship (can't buy a base next to a base)
                if (purchasingObject instanceof Ship) {
                    purchasingObject.addPowerup(SpaceSettlersPowerupEnum.FIRE_EMP);
                    // charge the team for the purchase
                    team.decrementAvailableResources(team.getCurrentCost(purchase));
                    team.updateCost(purchase);
                    System.out.println("Buying a emp launcher");
                }
                break;
            case POWERUP_DOUBLE_BASE_HEALING_SPEED:
                // this can only be purchased on bases
                if (purchasingObject instanceof Base) {
                    purchasingObject.addPowerup(SpaceSettlersPowerupEnum.DOUBLE_BASE_HEALING_SPEED);
                    // charge the team for the purchase
                    team.decrementAvailableResources(team.getCurrentCost(purchase));
                    team.updateCost(purchase);
                    System.out.println("Buying a healing doubler for a base");
                }
                break;
            case POWERUP_DOUBLE_MAX_ENERGY:
                purchasingObject.addPowerup(SpaceSettlersPowerupEnum.DOUBLE_MAX_ENERGY);
                // charge the team for the purchase
                team.decrementAvailableResources(team.getCurrentCost(purchase));
                team.updateCost(purchase);
                System.out.println("Buying a energy doubler");
                break;
            case POWERUP_DOUBLE_WEAPON_CAPACITY:
                purchasingObject.addPowerup(SpaceSettlersPowerupEnum.DOUBLE_WEAPON_CAPACITY);
                // charge the team for the purchase
                team.decrementAvailableResources(team.getCurrentCost(purchase));
                team.updateCost(purchase);
                System.out.println("Buying a weapons doubler");
                break;
            case NOTHING:
                break;
            default:
                break;
        }
    }
}
Also used : AbstractActionableObject(spacesettlers.objects.AbstractActionableObject) Position(spacesettlers.utilities.Position) PurchaseTypes(spacesettlers.actions.PurchaseTypes) Ship(spacesettlers.objects.Ship) UUID(java.util.UUID) Base(spacesettlers.objects.Base)

Example 5 with AbstractActionableObject

use of spacesettlers.objects.AbstractActionableObject in project spacesettlers by amymcgovern.

the class Toroidal2DPhysics method advanceTime.

/**
 * Move all moveable objects and handle power ups.
 */
public void advanceTime(int currentTimeStep, Map<UUID, SpaceSettlersPowerupEnum> powerups) {
    this.currentTimeStep = currentTimeStep;
    // heal any base injuries
    for (Base base : bases) {
        base.updateEnergy(base.getHealingIncrement());
    }
    // detect collisions across all objects
    detectCollisions();
    // get the power ups and create any objects (weapons) as necessary
    for (UUID key : powerups.keySet()) {
        AbstractObject swobject = getObjectById(key);
        // if the object is not alive or it is not actionable, then ignore this
        if (!swobject.isAlive() || (!(swobject instanceof AbstractActionableObject))) {
            continue;
        }
        // otherwise, handle the power up
        handlePowerup((AbstractActionableObject) swobject, powerups.get(key));
    }
    // now move all objects that are moveable (which may include weapons)
    for (AbstractObject object : allObjects) {
        // skip non-moveable objects or dead object
        if (!object.isMoveable() || !object.isAlive()) {
            continue;
        }
        Position currentPosition = object.getPosition();
        // is it a ship that can be controlled?
        if (object.isControllable()) {
            Ship ship = (Ship) object;
            AbstractAction action = ship.getCurrentAction();
            // handle a null action
            if (action == null) {
                action = new DoNothingAction();
            }
            // need to clone the ship and space because otherwise the ship can affect
            // itself inside AbstractAction
            Movement actionMovement = action.getMovement(this.deepClone(), ship.deepClone());
            Position newPosition = applyMovement(currentPosition, actionMovement, timeStep);
            if (newPosition.isValid()) {
                ship.setPosition(newPosition);
            } else {
                ship.setPosition(currentPosition);
            }
            // spend ship energy proportional to its acceleration (old formula used velocity) and mass (new for space settlers
            // since resources cost mass)
            // double penalty = ENERGY_PENALTY * -Math.abs(ship.getPosition().getTotalTranslationalVelocity());
            double angularAccel = Math.abs(actionMovement.getAngularAccleration());
            double angularInertia = (3.0 * ship.getMass() * ship.getRadius() * angularAccel) / 2.0;
            double linearAccel = actionMovement.getTranslationalAcceleration().getMagnitude();
            double linearInertia = ship.getMass() * linearAccel;
            int penalty = (int) Math.floor(ENERGY_PENALTY * (angularInertia + linearInertia));
            ship.updateEnergy(-penalty);
            // this isn't the most general fix but it will work for now (also has to be done for bases)
            if (ship.isShielded()) {
                ship.updateEnergy(-PowerupToggleShield.SHIELD_STEP_COST);
            }
        // if (!ship.isAlive()) {
        // System.out.println("Ship " + ship.getTeamName() + ship.getId() + " is dead");
        // }
        } else {
            // move all other types of objects
            Position newPosition = moveOneTimestep(currentPosition);
            object.setPosition(newPosition);
        }
        // if any ships or bases are frozen, decrement their frozen count
        if (object instanceof AbstractActionableObject && !object.isControllable()) {
            AbstractActionableObject actionable = (AbstractActionableObject) object;
            actionable.decrementFreezeCount();
        }
    }
    // go through and see if any bases have died
    Set<Base> basesClone = new LinkedHashSet<Base>(bases);
    for (Base base : basesClone) {
        // this isn't the most general fix but it will work for now (also has to be done for bases)
        if (base.isShielded()) {
            base.updateEnergy(-PowerupToggleShield.SHIELD_STEP_COST);
        }
        if (!base.isAlive()) {
            base.setAlive(false);
            removeObject(base);
            base.getTeam().removeBase(base);
        }
    }
    // from when it was called inside updateEnergy
    for (Ship ship : ships) {
        if (ship.getEnergy() <= 0 && ship.isAlive() == true) {
            // drop any resources that the ship was carrying
            ResourcePile resources = ship.getResources();
            // Spawn a new AiCore with the same velocity magnitude and direction as its parent ship.
            // handle dropping the core if the ship died
            Position corePosition = ship.getPosition();
            corePosition.setTranslationalVelocity(ship.getPosition().getTranslationalVelocity());
            corePosition.setAngularVelocity(ship.getPosition().getAngularVelocity());
            AiCore shipCore = new AiCore(corePosition, ship.getTeamName(), ship.getTeamColor());
            this.addObject(shipCore);
            if (resources.getTotal() > 0) {
            // Position newPosition = ship.getPosition();
            // newPosition.setTranslationalVelocity(new Vector2D(0,0));
            // newPosition.setAngularVelocity(0.0);
            // Asteroid newAsteroid = new Asteroid(newPosition, true, ship.getRadius(), true, resources);
            // this.addObject(newAsteroid);
            // distributeResourcesToNearbyAsteroids(ship.getPosition(), resources);
            // System.out.println("Adding a new asteroid with resources " + newAsteroid.getResources().getTotal() +
            // " due to death, total is " + asteroids.size());
            // System.out.println("Ship died and " + resources.getTotal() + " has been added to an asteroid");
            }
            // set the ship to dead last (so we can grab its resources first)
            ship.setAlive(false);
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ResourcePile(spacesettlers.objects.resources.ResourcePile) AbstractActionableObject(spacesettlers.objects.AbstractActionableObject) Movement(spacesettlers.utilities.Movement) Position(spacesettlers.utilities.Position) Base(spacesettlers.objects.Base) AiCore(spacesettlers.objects.AiCore) AbstractObject(spacesettlers.objects.AbstractObject) Ship(spacesettlers.objects.Ship) UUID(java.util.UUID) AbstractAction(spacesettlers.actions.AbstractAction) DoNothingAction(spacesettlers.actions.DoNothingAction)

Aggregations

UUID (java.util.UUID)14 AbstractActionableObject (spacesettlers.objects.AbstractActionableObject)14 HashMap (java.util.HashMap)11 Ship (spacesettlers.objects.Ship)9 PurchaseTypes (spacesettlers.actions.PurchaseTypes)8 Base (spacesettlers.objects.Base)8 ExecutionException (java.util.concurrent.ExecutionException)5 Map (java.util.Map)4 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)4 TimeoutException (java.util.concurrent.TimeoutException)4 SpaceSettlersPowerupEnum (spacesettlers.objects.powerups.SpaceSettlersPowerupEnum)4 Toroidal2DPhysics (spacesettlers.simulator.Toroidal2DPhysics)4 AbstractAction (spacesettlers.actions.AbstractAction)3 DoNothingAction (spacesettlers.actions.DoNothingAction)2 AbstractObject (spacesettlers.objects.AbstractObject)2 ResourcePile (spacesettlers.objects.resources.ResourcePile)2 Position (spacesettlers.utilities.Position)2 LinkedHashSet (java.util.LinkedHashSet)1 ExecutorService (java.util.concurrent.ExecutorService)1 Future (java.util.concurrent.Future)1