package example7_2.game; import example7_2.game.characters.Flower; import java.util.List; /** * Moves toward the closest flower with at least 3 points * @author macavaneys * */ public class SmartMoveBehavior implements MoveBehavior { /** * The minimum number of points required to target a flower */ private static int MINIMUM_TARGET_FLOWER_POINTS = 3; /** * The character associated with this behavior */ private GameCharacter gc; /** * Creates a new SmartMoveBehavior for the specified character */ public SmartMoveBehavior(GameCharacter character) { this.gc = character; } /** * Moves to the closest flower with at least 3 points */ @Override public void planMove(List list) { // Find the closest flower with at least 3 points. GameCharacter targetCharacter = null; double targetCharacterDistance = Double.MAX_VALUE; for (GameCharacter character : list) { if (character instanceof Flower && character.getScore() >= MINIMUM_TARGET_FLOWER_POINTS) { // Target this flower if it is closer than the current target double distance = gc.distanceTo(character); if (distance < targetCharacterDistance) { targetCharacter = character; targetCharacterDistance = distance; } } } if (targetCharacter != null) { // Move to this flower gc.setTargetPosition(targetCharacter.getCurrentRow(), targetCharacter.getCurrentColumn()); // set the new target position; the Game framework will do the actual move } else { // targetCharacter == null // There's no acceptable flower, so don't move anywhere. gc.setTargetPosition(gc.getCurrentRow(), gc.getCurrentColumn()); } Game.validateMove(gc); } }