Implement A* Search

Many changes to improve AI usage

Signed-off-by: Chris Cromer <chris@cromer.cl>
This commit is contained in:
Chris Cromer 2019-10-17 12:27:17 -03:00
parent 1ac56b3b39
commit cbcb6d0d01
19 changed files with 1214 additions and 913 deletions

View File

@ -2,6 +2,7 @@
<dictionary name="cromer"> <dictionary name="cromer">
<words> <words>
<w>appname</w> <w>appname</w>
<w>astar</w>
<w>aventura</w> <w>aventura</w>
<w>azaraka</w> <w>azaraka</w>
<w>celda</w> <w>celda</w>

View File

@ -23,12 +23,9 @@ plugins {
group 'cl.cromer.azaraka' group 'cl.cromer.azaraka'
version '1.0.0' version '1.0.0'
//noinspection GroovyUnusedAssignment
sourceCompatibility = 1.8 sourceCompatibility = 1.8
//noinspection GroovyUnusedAssignment
targetCompatibility = 1.8 targetCompatibility = 1.8
//noinspection GroovyUnusedAssignment
applicationName = 'Azaraka' applicationName = 'Azaraka'
mainClassName = 'cl.cromer.azaraka.Azaraka' mainClassName = 'cl.cromer.azaraka.Azaraka'
@ -48,9 +45,7 @@ dependencies {
//testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.+' //testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.+'
} }
//noinspection GrUnresolvedAccess
ext.sharedManifest = manifest { ext.sharedManifest = manifest {
//noinspection GrUnresolvedAccess
attributes 'Main-Class': "$mainClassName", attributes 'Main-Class': "$mainClassName",
'Class-Path': configurations.default.files.collect { "$it.name" }.join(' '), 'Class-Path': configurations.default.files.collect { "$it.name" }.join(' '),
'Implementation-Title': 'Gradle', 'Implementation-Title': 'Gradle',
@ -59,12 +54,10 @@ ext.sharedManifest = manifest {
jar { jar {
manifest = project.manifest { manifest = project.manifest {
//noinspection GroovyAssignabilityCheck
from sharedManifest from sharedManifest
} }
if (project.uberJar == "true") { if (project.uberJar == "true") {
//noinspection GroovyAssignabilityCheck
from sourceSets.main.output from sourceSets.main.output
dependsOn configurations.runtimeClasspath dependsOn configurations.runtimeClasspath
@ -84,7 +77,6 @@ task copyDependencies(type: Copy) {
plugins.withType(DistributionPlugin) { plugins.withType(DistributionPlugin) {
distTar { distTar {
//noinspection GroovyAssignabilityCheck, GroovyAccessibility
archiveExtension = 'tar.gz' archiveExtension = 'tar.gz'
compression = Compression.GZIP compression = Compression.GZIP
} }
@ -96,13 +88,9 @@ task createDocs {
} }
distributions { distributions {
//noinspection GroovyAssignabilityCheck
main { main {
//noinspection GrUnresolvedAccess
contents { contents {
//noinspection GrUnresolvedAccess
from(createDocs) { from(createDocs) {
//noinspection GrUnresolvedAccess
into 'docs' into 'docs'
} }
} }

View File

@ -15,7 +15,8 @@
package cl.cromer.azaraka; package cl.cromer.azaraka;
import cl.cromer.azaraka.ai.SearchAI; import cl.cromer.azaraka.ai.AI;
import cl.cromer.azaraka.ai.AIException;
import cl.cromer.azaraka.ai.State; import cl.cromer.azaraka.ai.State;
import cl.cromer.azaraka.object.Chest; import cl.cromer.azaraka.object.Chest;
import cl.cromer.azaraka.object.Enemy; import cl.cromer.azaraka.object.Enemy;
@ -41,6 +42,7 @@ import java.awt.event.KeyListener;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -60,19 +62,19 @@ public class Canvas extends java.awt.Canvas implements Constants {
/** /**
* The threads for the objects * The threads for the objects
*/ */
private final HashMap<Object, Thread> threads = new HashMap<>(); private final Map<Object, Thread> threads = new HashMap<>();
/** /**
* The enemies * The enemies
*/ */
private final ArrayList<Enemy> enemies = new ArrayList<>(); private final List<Enemy> enemies = new ArrayList<>();
/** /**
* The keys * The keys
*/ */
private final ArrayList<Key> keys = new ArrayList<>(); private final List<Key> keys = new ArrayList<>();
/** /**
* The chests * The chests
*/ */
private final ArrayList<Chest> chests = new ArrayList<>(); private final List<Chest> chests = new ArrayList<>();
/** /**
* The logger * The logger
*/ */
@ -92,7 +94,7 @@ public class Canvas extends java.awt.Canvas implements Constants {
/** /**
* The threads that control AI * The threads that control AI
*/ */
private final HashMap<SearchAI, Thread> aiThreads = new HashMap<>(); private final Map<AI, Thread> aiThreads = new HashMap<>();
/** /**
* The graphics buffer * The graphics buffer
*/ */
@ -207,7 +209,7 @@ public class Canvas extends java.awt.Canvas implements Constants {
scene = new Scene(this); scene = new Scene(this);
ArrayList<Object> objectList = scene.generateRandomObjects(); List<Object> objectList = scene.generateRandomObjects();
while (objectList == null) { while (objectList == null) {
scene = new Scene(this); scene = new Scene(this);
objectList = scene.generateRandomObjects(); objectList = scene.generateRandomObjects();
@ -289,7 +291,7 @@ public class Canvas extends java.awt.Canvas implements Constants {
thread.start(); thread.start();
} }
if (PLAYER_AI) { if (PLAYER_AI != PlayerAIType.HUMAN) {
setupPlayerAI(); setupPlayerAI();
} }
else { else {
@ -306,6 +308,7 @@ public class Canvas extends java.awt.Canvas implements Constants {
* Setup the player AI * Setup the player AI
*/ */
private void setupPlayerAI() { private void setupPlayerAI() {
try {
player.getAi().addDestination(new State(2, 0, State.Type.EXIT, null, 3)); player.getAi().addDestination(new State(2, 0, State.Type.EXIT, null, 3));
// Shuffle the chests so that the AI doesn't open the correct chests on the first go // Shuffle the chests so that the AI doesn't open the correct chests on the first go
@ -319,6 +322,10 @@ public class Canvas extends java.awt.Canvas implements Constants {
} }
player.getAi().sortDestinations(); player.getAi().sortDestinations();
}
catch (AIException e) {
logger.warning(e.getMessage());
}
Thread thread = new Thread(player.getAi()); Thread thread = new Thread(player.getAi());
thread.start(); thread.start();
@ -369,7 +376,7 @@ public class Canvas extends java.awt.Canvas implements Constants {
} }
} }
ArrayList<Gem> gems = player.getInventoryGems(false); List<Gem> gems = player.getInventoryGems(false);
for (Gem gem : gems) { for (Gem gem : gems) {
gem.drawAnimation(graphicBuffer, xPixels, 8); gem.drawAnimation(graphicBuffer, xPixels, 8);
xPixels = xPixels + 3 + (gem.getAnimationWidth()); xPixels = xPixels + 3 + (gem.getAnimationWidth());
@ -488,10 +495,10 @@ public class Canvas extends java.awt.Canvas implements Constants {
} }
// Stop AI threads // Stop AI threads
for (Map.Entry<SearchAI, Thread> entry : aiThreads.entrySet()) { for (Map.Entry<AI, Thread> entry : aiThreads.entrySet()) {
Thread thread = entry.getValue(); Thread thread = entry.getValue();
if (thread.isAlive()) { if (thread.isAlive()) {
SearchAI ai = entry.getKey(); AI ai = entry.getKey();
ai.setActive(false); ai.setActive(false);
thread.interrupt(); thread.interrupt();
} }
@ -584,7 +591,7 @@ public class Canvas extends java.awt.Canvas implements Constants {
* *
* @return Returns all the keys that are in the game * @return Returns all the keys that are in the game
*/ */
public ArrayList<Key> getKeys() { public List<Key> getKeys() {
return keys; return keys;
} }
@ -593,7 +600,7 @@ public class Canvas extends java.awt.Canvas implements Constants {
* *
* @return Returns all the chests that are in the game * @return Returns all the chests that are in the game
*/ */
public ArrayList<Chest> getChests() { public List<Chest> getChests() {
return chests; return chests;
} }

View File

@ -47,7 +47,7 @@ public class Cell extends JComponent implements Constants {
/** /**
* A map containing the textures used in the cell, LinkedHashMap is used to maintain the order of images * A map containing the textures used in the cell, LinkedHashMap is used to maintain the order of images
*/ */
private final LinkedHashMap<Integer, BufferedImage> textures = new LinkedHashMap<>(); private final Map<Integer, BufferedImage> textures = new LinkedHashMap<>();
/** /**
* The object in the cell * The object in the cell
*/ */

View File

@ -35,9 +35,9 @@ public interface Constants {
*/ */
String TITLE = "La Aventura de Azaraka"; String TITLE = "La Aventura de Azaraka";
/** /**
* Whether or not the player should be controlled by AI * Which type of AI to use
*/ */
boolean PLAYER_AI = false; PlayerAIType PLAYER_AI = PlayerAIType.ASTAR;
/** /**
* Whether or not the enemies should be controlled by AI * Whether or not the enemies should be controlled by AI
*/ */
@ -81,7 +81,7 @@ public interface Constants {
/** /**
* The default volume between 0 and 100 * The default volume between 0 and 100
*/ */
int VOLUME = 100; int VOLUME = 0;
/** /**
* Generates the scene manually instead of from the JSON file if true * Generates the scene manually instead of from the JSON file if true
*/ */
@ -186,6 +186,24 @@ public interface Constants {
} }
} }
/**
* The different AI that can be used by the player
*/
enum PlayerAIType {
/**
* Human player
*/
HUMAN,
/**
* Breadth-First Search
*/
BFS,
/**
* A* Search
*/
ASTAR
}
/** /**
* This enum contains all the levels used for logging * This enum contains all the levels used for logging
*/ */

View File

@ -17,6 +17,7 @@ package cl.cromer.azaraka;
import cl.cromer.azaraka.ai.EnemyAI; import cl.cromer.azaraka.ai.EnemyAI;
import cl.cromer.azaraka.ai.PlayerAI; import cl.cromer.azaraka.ai.PlayerAI;
import cl.cromer.azaraka.ai.PlayerBreadthFirstAI;
import cl.cromer.azaraka.ai.State; import cl.cromer.azaraka.ai.State;
import cl.cromer.azaraka.json.Json; import cl.cromer.azaraka.json.Json;
import cl.cromer.azaraka.json.JsonCell; import cl.cromer.azaraka.json.JsonCell;
@ -42,6 +43,7 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -166,9 +168,9 @@ public class Scene extends JComponent implements Constants {
* *
* @return Returns a list of objects that where generated * @return Returns a list of objects that where generated
*/ */
public ArrayList<Object> generateRandomObjects() { public List<Object> generateRandomObjects() {
int[] random; int[] random;
ArrayList<Object> objectArrayList = new ArrayList<>(); List<Object> objectArrayList = new ArrayList<>();
// The player has a fixed position // The player has a fixed position
cells[2][1].setObject(new Player(this, cells[2][1])); cells[2][1].setObject(new Player(this, cells[2][1]));
@ -253,7 +255,7 @@ public class Scene extends JComponent implements Constants {
* @return Returns true if valid or false otherwise * @return Returns true if valid or false otherwise
*/ */
private boolean pathInvalid(int x, int y) { private boolean pathInvalid(int x, int y) {
PlayerAI playerAI = new PlayerAI(this, null); PlayerAI playerAI = new PlayerBreadthFirstAI(this, null);
State playerState = new State(2, 1, State.Type.PLAYER, null, 0); State playerState = new State(2, 1, State.Type.PLAYER, null, 0);
State objectiveState = new State(x, y, State.Type.EXIT, null, 0); State objectiveState = new State(x, y, State.Type.EXIT, null, 0);
return !playerAI.search(playerState, objectiveState); return !playerAI.search(playerState, objectiveState);

View File

@ -0,0 +1,95 @@
/*
* Copyright 2019 Chris Cromer
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package cl.cromer.azaraka.ai;
import java.util.logging.Logger;
/**
* AI algorithms extends this class
*/
public class AI implements Runnable {
/**
* The logger
*/
private Logger logger;
/**
* Whether or not the AI is active
*/
private boolean active = true;
/**
* Get the active state of the AI
*
* @return Returns true if the AI is active or false otherwise
*/
protected boolean getActive() {
return active;
}
/**
* Set the active state for the AI loop
*
* @param active Set to true to have the run method loop run indefinitely or false to stop the loop
*/
public void setActive(boolean active) {
this.active = active;
}
/**
* Get the logger being used by the AI
*
* @return Returns the logger
*/
protected Logger getLogger() {
return logger;
}
/**
* Set the logger that the AI should use
*
* @param logger The logger to use
*/
protected void setLogger(Logger logger) {
this.logger = logger;
}
/**
* Add a destination to the list of destinations
*
* @param destination The destination
* @throws AIException Thrown when the parent method is called directly
*/
public void addDestination(State destination) throws AIException {
throw new AIException("The addDestination method should be run by the child only!");
}
/**
* Sort the destinations
*
* @throws AIException Thrown when the parent method is called directly
*/
public void sortDestinations() throws AIException {
throw new AIException("The addDestination method should be run by the child only!");
}
/**
* The AI should run in a loop
*/
@Override
public void run() {
}
}

View File

@ -16,13 +16,13 @@
package cl.cromer.azaraka.ai; package cl.cromer.azaraka.ai;
/** /**
* This class handles exceptions thrown by the AI * This exception is thrown when there are problems with the AI
*/ */
public class AIException extends Exception { public class AIException extends Exception {
/** /**
* Initialize the AI exception * Throw an error with a message
* *
* @param errorMessage The message thrown * @param errorMessage The message
*/ */
public AIException(String errorMessage) { public AIException(String errorMessage) {
super(errorMessage); super(errorMessage);

View File

@ -1,239 +0,0 @@
/*
* Copyright 2019 Chris Cromer
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package cl.cromer.azaraka.ai;
import java.awt.geom.Point2D;
import java.util.ArrayList;
/**
* This is an implementation of the Breadth-First search algorithm with multiple objectives
*/
public class BreadthFirstSearch extends SearchAI {
/**
* The steps to get to the objective
*/
private final ArrayList<State.Type> steps = new ArrayList<>();
/**
* The destinations to visit
*/
private final ArrayList<State> destinations = new ArrayList<>();
/**
* The subInitial point to start searching from
*/
private State initial;
/**
* Initialize the algorithm
*/
protected BreadthFirstSearch() {
}
/**
* Calculate the route to the object
*/
@Override
protected void calculateRoute() {
getLogger().info("Calculate the route!");
State predecessor = getSearchObjective();
do {
steps.add(0, predecessor.getOperation());
predecessor = predecessor.getPredecessor();
}
while (predecessor != null);
}
/**
* Add a destination to the AI
*
* @param state The new state to add
*/
public void addDestination(State state) {
destinations.add(state);
}
/**
* Sort the destinations by importance, if the importance is the same then sort them by distance
*/
public void sortDestinations() {
destinations.sort((state1, state2) -> {
if (state1.getImportance() > state2.getImportance()) {
// The first state is more important
return -1;
}
else if (state1.getImportance() < state2.getImportance()) {
// The second state is more important
return 1;
}
else {
// The states have equal importance, so let's compare distances between them
if (initial != null) {
double state1Distance = Point2D.distance(initial.getX(), initial.getY(), state1.getX(), state1.getY());
double state2Distance = Point2D.distance(initial.getX(), initial.getY(), state2.getX(), state2.getY());
return Double.compare(state1Distance, state2Distance);
}
else {
return 0;
}
}
});
}
/**
* This method is called when the player arrives at a destination
*
* @param objective The objective the player arrived at
* @return Returns true if the destination condition is valid or false otherwise
* @throws AIException Thrown if the method is called via super
*/
protected boolean destinationArrived(State objective) throws AIException {
String methodName = new Throwable().getStackTrace()[0].getMethodName();
throw new AIException("Do not call " + methodName + "using super!");
}
/**
* If the condition is true go to the objective
*
* @param subObjective The objective to check
* @return Returns true or false based on whether the objective can be obtained
* @throws AIException Thrown if the method is called via super
*/
protected boolean checkCondition(State subObjective) throws AIException {
String methodName = new Throwable().getStackTrace()[0].getMethodName();
throw new AIException("Do not call " + methodName + "using super!");
}
/**
* Get the steps needed to arrive at the objective
*
* @return Returns an array of steps
*/
protected ArrayList<State.Type> getSteps() {
return steps;
}
/**
* The child class should call this to set a new initial point
*
* @param initial The new state to start from
*/
protected void setInitial(State initial) {
this.initial = initial;
}
/**
* The child class should override this to trigger a new initial state
*
* @throws AIException Thrown if the method is called via super
*/
protected void getNewInitial() throws AIException {
String methodName = new Throwable().getStackTrace()[0].getMethodName();
throw new AIException("Do not call " + methodName + "using super!");
}
/**
* The child class should override this to do actions
*
* @throws AIException Thrown if the method is called via super
*/
protected void doAction() throws AIException {
String methodName = new Throwable().getStackTrace()[0].getMethodName();
throw new AIException("Do not call " + methodName + "using super!");
}
// TODO: set the speed of the enemy and player outside of the algorithm
/**
* Run the steps in a loop, then launch the next objective when finished
*/
@Override
public void run() {
super.run();
while (getActive()) {
try {
Thread.sleep(400);
}
catch (InterruptedException e) {
getLogger().info(e.getMessage());
}
synchronized (this) {
getQueuedStates().clear();
getHistory().clear();
steps.clear();
State objective;
boolean found = false;
int destinationIndex = 0;
do {
try {
getNewInitial();
}
catch (AIException e) {
getLogger().warning(e.getMessage());
}
objective = destinations.get(destinationIndex);
try {
if (checkCondition(objective)) {
found = search(initial, objective);
}
}
catch (AIException e) {
getLogger().warning(e.getMessage());
}
if (initial.equals(objective)) {
try {
if (destinationArrived(objective)) {
destinations.remove(objective);
destinationIndex = 0;
}
}
catch (AIException e) {
getLogger().warning(e.getMessage());
}
}
else {
if (!found) {
getQueuedStates().clear();
getHistory().clear();
steps.clear();
// Don't run this because the destination might return to be available again at some point
//destinationArrived(subObjective);
}
}
if (destinations.isEmpty()) {
getLogger().info("No more destinations!");
setActive(false);
}
destinationIndex++;
if (destinationIndex >= destinations.size()) {
destinationIndex = 0;
}
}
while (!found && !destinations.isEmpty());
try {
doAction();
}
catch (AIException e) {
getLogger().warning(e.getMessage());
}
}
}
}
}

View File

@ -1,151 +0,0 @@
/*
* Copyright 2019 Chris Cromer
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package cl.cromer.azaraka.ai;
import java.util.ArrayList;
/**
* This is an implementation of the Breadth-First search algorithm with multiple objectives
*/
public class DepthFirstSearch extends SearchAI {
/**
* The steps to get to the objective
*/
private final ArrayList<State.Type> steps = new ArrayList<>();
/**
* The initial point to start searching from
*/
private State initial;
/**
* The objective point to search for
*/
private State objective;
/**
* Initialize the algorithm
*/
protected DepthFirstSearch() {
}
/**
* Calculate the route to the object
*/
@Override
protected void calculateRoute() {
getLogger().info("Calculate the route!");
State predecessor = getSearchObjective();
do {
steps.add(0, predecessor.getOperation());
predecessor = predecessor.getPredecessor();
}
while (predecessor != null);
}
/**
* Get the steps needed to arrive at the objective
*
* @return Returns an array of steps
*/
protected ArrayList<State.Type> getSteps() {
return steps;
}
/**
* The child class should call this to set a new initial point
*
* @param initial The new state to start from
*/
protected void setInitial(State initial) {
this.initial = initial;
}
/**
* The child class should call this to set a new objective point
*
* @param objective The new state to search for
*/
protected void setObjective(State objective) {
this.objective = objective;
}
/**
* The child class should override this to trigger a new initial state
*
* @throws AIException Thrown if the method is called via super
*/
protected void getNewInitial() throws AIException {
String methodName = new Throwable().getStackTrace()[0].getMethodName();
throw new AIException("Do not call " + methodName + "using super!");
}
/**
* The child class should override this to trigger a new objective state
*
* @throws AIException Thrown if the method is called via super
*/
protected void getNewObjective() throws AIException {
String methodName = new Throwable().getStackTrace()[0].getMethodName();
throw new AIException("Do not call " + methodName + "using super!");
}
/**
* The child class should override this to do actions
*
* @throws AIException Thrown if the method is called via super
*/
protected void doAction() throws AIException {
String methodName = new Throwable().getStackTrace()[0].getMethodName();
throw new AIException("Do not call " + methodName + "using super!");
}
/**
* Run the steps in a loop, then launch the next objective when finished
*/
@Override
public void run() {
super.run();
while (getActive()) {
try {
Thread.sleep(700);
}
catch (InterruptedException e) {
getLogger().info(e.getMessage());
}
synchronized (this) {
getQueuedStates().clear();
getHistory().clear();
steps.clear();
try {
getNewInitial();
getNewObjective();
}
catch (AIException e) {
getLogger().warning(e.getMessage());
}
search(initial, objective);
try {
doAction();
}
catch (AIException e) {
getLogger().warning(e.getMessage());
}
}
}
}
}

View File

@ -21,10 +21,18 @@ import cl.cromer.azaraka.object.Enemy;
import cl.cromer.azaraka.object.Object; import cl.cromer.azaraka.object.Object;
import cl.cromer.azaraka.object.Player; import cl.cromer.azaraka.object.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/** /**
* This class handles player based interactions mixed with AI * This is an implementation of the Depth-First search algorithm
*/ */
public class EnemyAI extends DepthFirstSearch implements Constants { public class EnemyAI extends AI implements Runnable, Constants {
/**
* The logger
*/
private final Logger logger;
/** /**
* The player * The player
*/ */
@ -33,27 +41,195 @@ public class EnemyAI extends DepthFirstSearch implements Constants {
* The scene the AI is in * The scene the AI is in
*/ */
private final Scene scene; private final Scene scene;
/**
* The queued states to check
*/
private final List<State> queuedStates = new ArrayList<>();
/**
* The history of states that have been checked
*/
private final List<State> history = new ArrayList<>();
/**
* The steps to get to the goal
*/
private final List<State.Type> steps = new ArrayList<>();
/**
* The goal point to search for
*/
private State searchGoal;
/**
* If the search was successful or not
*/
private boolean success = false;
/** /**
* Initialize the algorithm * Initialize the algorithm
* *
* @param scene The scene the AI is in * @param scene The scene the AI is in
* @param enemy The player controlled by the AI * @param enemy The enemy the AI is controlling
*/ */
public EnemyAI(Scene scene, Enemy enemy) { public EnemyAI(Scene scene, Enemy enemy) {
super(); logger = getLogger(this.getClass(), Constants.LogLevel.AI);
setLogger(getLogger(this.getClass(), LogLevel.AI));
this.scene = scene; this.scene = scene;
this.enemy = enemy; this.enemy = enemy;
} }
/** /**
* Handle actions based on the states * Find a path to the objective
*
* @param searchInitial The start point
* @param searchGoal The goal
* @return Returns true if a path to the goal is found or false otherwise
*/
public boolean search(State searchInitial, State searchGoal) {
queuedStates.add(searchInitial);
history.add(searchInitial);
this.searchGoal = searchGoal;
success = searchInitial.equals(searchGoal);
while (!queuedStates.isEmpty() && !success) {
State current = queuedStates.get(0);
queuedStates.remove(0);
moveUp(current);
moveDown(current);
moveLeft(current);
moveRight(current);
}
if (success) {
logger.info("Route to objective found!");
calculateRoute();
return true;
}
else {
logger.info("Route to objective not found!");
return false;
}
}
/**
* Move to the next state
*
* @param next The next state
*/
private void move(State next) {
if (!history.contains(next)) {
queuedStates.add(next);
history.add(next);
if (next.equals(searchGoal)) {
searchGoal = next;
success = true;
}
}
}
/**
* Move up
*
* @param current The current state
*/
private void moveUp(State current) {
if (current.getY() > 0) {
Object object = scene.getCells()[current.getX()][current.getY() - 1].getObject();
if (object == null || object instanceof Player) {
State next = new State(current.getX(), current.getY() - 1, State.Type.UP, current, current.getImportance());
move(next);
}
}
}
/**
* Move down
*
* @param current The current state
*/
private void moveDown(State current) {
if (current.getY() < VERTICAL_CELLS - 1) {
Object object = scene.getCells()[current.getX()][current.getY() + 1].getObject();
if (object == null || object instanceof Player) {
State next = new State(current.getX(), current.getY() + 1, State.Type.DOWN, current, current.getImportance());
move(next);
}
}
}
/**
* Move left
*
* @param current The current state
*/
private void moveLeft(State current) {
if (current.getX() > 0) {
Object object = scene.getCells()[current.getX() - 1][current.getY()].getObject();
if (object == null || object instanceof Player) {
State next = new State(current.getX() - 1, current.getY(), State.Type.LEFT, current, current.getImportance());
move(next);
}
}
}
/**
* Move right
*
* @param current The current state
*/
private void moveRight(State current) {
if (current.getX() < HORIZONTAL_CELLS - 1) {
Object object = scene.getCells()[current.getX() + 1][current.getY()].getObject();
if (object == null || object instanceof Player) {
State next = new State(current.getX() + 1, current.getY(), State.Type.RIGHT, current, current.getImportance());
move(next);
}
}
}
/**
* Calculate the route to the goal
*/
private void calculateRoute() {
logger.info("Calculate the route!");
State predecessor = searchGoal;
do {
steps.add(0, predecessor.getOperation());
predecessor = predecessor.getPredecessor();
}
while (predecessor != null);
}
/**
* Clear the states to start a new search
*/
private void clearStates() {
queuedStates.clear();
history.clear();
steps.clear();
}
/**
* Run the steps in a loop
*/ */
@Override @Override
public void doAction() { public void run() {
if (getSteps().size() > 1) { while (getActive()) {
switch (getSteps().get(1)) { try {
Thread.sleep(600);
}
catch (InterruptedException e) {
logger.info(e.getMessage());
}
synchronized (this) {
clearStates();
State initial = new State(enemy.getCell().getX(), enemy.getCell().getY(), State.Type.ENEMY, null, 0);
State objective = new State(scene.getCanvas().getPlayer().getCell().getX(), scene.getCanvas().getPlayer().getCell().getY(), State.Type.PLAYER, null, 0);
search(initial, objective);
if (steps.size() > 1) {
switch (steps.get(1)) {
case UP: case UP:
enemy.moveUp(); enemy.moveUp();
break; break;
@ -70,82 +246,6 @@ public class EnemyAI extends DepthFirstSearch implements Constants {
scene.getCanvas().repaint(); scene.getCanvas().repaint();
} }
} }
/**
* Move up
*
* @param state The previous state
*/
@Override
public void moveUp(State state) {
if (state.getY() > 0) {
Object object = scene.getCells()[state.getX()][state.getY() - 1].getObject();
if (object == null || object instanceof Player) {
super.moveUp(state);
} }
} }
}
/**
* Move down
*
* @param state The previous state
*/
@Override
public void moveDown(State state) {
if (state.getY() < VERTICAL_CELLS - 1) {
Object object = scene.getCells()[state.getX()][state.getY() + 1].getObject();
if (object == null || object instanceof Player) {
super.moveDown(state);
}
}
}
/**
* Move left
*
* @param state The previous state
*/
@Override
public void moveLeft(State state) {
if (state.getX() > 0) {
Object object = scene.getCells()[state.getX() - 1][state.getY()].getObject();
if (object == null || object instanceof Player) {
super.moveLeft(state);
}
}
}
/**
* Move right
*
* @param state The previous state
*/
@Override
public void moveRight(State state) {
if (state.getX() < HORIZONTAL_CELLS - 1) {
Object object = scene.getCells()[state.getX() + 1][state.getY()].getObject();
if (object == null || object instanceof Player) {
super.moveRight(state);
}
}
}
/**
* This method is called when the algorithm wants to know where the enemy is located at now
*/
@Override
public void getNewInitial() {
setInitial(new State(enemy.getCell().getX(), enemy.getCell().getY(), State.Type.ENEMY, null, 0));
}
/**
* The method is called when the algorithm wants to know where the player is located at now
*/
@Override
public void getNewObjective() {
setObjective(new State(scene.getCanvas().getPlayer().getCell().getX(), scene.getCanvas().getPlayer().getCell().getY(), State.Type.PLAYER, null, 0));
}
} }

View File

@ -22,41 +22,107 @@ import cl.cromer.azaraka.object.Portal;
import cl.cromer.azaraka.sprite.Animation; import cl.cromer.azaraka.sprite.Animation;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
/** /**
* This class handles player based interactions mixed with AI * This interface has Player specific AI code that is shared between AI implementations
*/ */
public class PlayerAI extends BreadthFirstSearch implements Constants { public interface PlayerAI extends Runnable, Constants {
/** /**
* The player * Search for the goal from a starting state
*
* @param start The start state
* @param goal The goal state
* @return Return true if there is a path or false otherwise
*/ */
private final Player player; boolean search(State start, State goal);
/**
* The scene the AI is in
*/
private final Scene scene;
/** /**
* Initialize the algorithm * Add a destination to the list of destinations
* *
* @param scene The scene the AI is in * @param destination The new destination
* @param player The player controlled by the AI
*/ */
public PlayerAI(Scene scene, Player player) { void addDestination(State destination);
super();
setLogger(getLogger(this.getClass(), LogLevel.AI)); /**
this.scene = scene; * Sor the destinations based on importance and distance
this.player = player; */
void sortDestinations();
/**
* The heuristic to get the distance between the start state and the end state
*
* @param start The start state
* @param goal The goal state
* @return Returns the distance between the states
*/
default double heuristic(State start, State goal) {
// Manhattan Distance
// Used for 4 direction movements
/*
h = abs (current_cell.x goal.x) +
abs (current_cell.y goal.y)
*/
// Diagonal Distance
// Used for 8 direction movements
/*
h = max { abs(current_cell.x goal.x),
abs(current_cell.y goal.y) }
*/
// Euclidean Distance
// Used for distance between 2 points
/*
h = sqrt ( (current_cell.x goal.x)2 +
(current_cell.y goal.y)2 )
*/
return Math.abs(start.getX() - goal.getX()) + Math.abs(start.getY() - goal.getY());
} }
/** /**
* This handles what to do when the player arrives at a destination * Sort the destinations based on importance and distance
* *
* @param objective The objective the player arrived at * @param destinations The destinations to sort
* @param initial The initial state of the player
* @return Returns the new sorted destinations
*/ */
@Override default List<State> sortDestinations(List<State> destinations, State initial) {
public boolean destinationArrived(State objective) { destinations.sort((state1, state2) -> {
switch (objective.getOperation()) { if (state1.getImportance() > state2.getImportance()) {
// The first state is more important
return -1;
}
else if (state1.getImportance() < state2.getImportance()) {
// The second state is more important
return 1;
}
else {
// The states have equal importance, so let's compare distances between them
if (initial != null) {
double state1Distance = heuristic(initial, state1);
double state2Distance = heuristic(initial, state2);
return Double.compare(state1Distance, state2Distance);
}
else {
return 0;
}
}
});
return destinations;
}
/**
* If the player arrived at a a goal this should be called
*
* @param scene The scene
* @param goal The goal
* @return Returns true if the goal is in a certain state or false if the goal is not truly reachable or usable
*/
default boolean destinationArrived(Scene scene, State goal) {
Player player = scene.getCanvas().getPlayer();
switch (goal.getOperation()) {
case CHEST: case CHEST:
if (player.hasKey()) { if (player.hasKey()) {
if (player.getAnimation().getCurrentDirection() != Animation.Direction.UP) { if (player.getAnimation().getCurrentDirection() != Animation.Direction.UP) {
@ -66,8 +132,8 @@ public class PlayerAI extends BreadthFirstSearch implements Constants {
Portal portal = scene.getCanvas().getPortal(); Portal portal = scene.getCanvas().getPortal();
if (portal.getState() == Portal.State.ACTIVE) { if (portal.getState() == Portal.State.ACTIVE) {
addDestination(new State(portal.getCell().getX(), portal.getCell().getY(), State.Type.PORTAL, null, 2)); addDestination(new State(portal.getCell().getX(), portal.getCell().getY(), State.Type.PORTAL, null, 2));
sortDestinations();
} }
sortDestinations();
return true; return true;
} }
break; break;
@ -75,6 +141,7 @@ public class PlayerAI extends BreadthFirstSearch implements Constants {
player.keyPressed(KeyEvent.VK_UP); player.keyPressed(KeyEvent.VK_UP);
return true; return true;
case KEY: case KEY:
sortDestinations();
return true; return true;
case PORTAL: case PORTAL:
if (player.hasTaintedGem() && scene.getCanvas().getPortal().getState() == Portal.State.ACTIVE) { if (player.hasTaintedGem() && scene.getCanvas().getPortal().getState() == Portal.State.ACTIVE) {
@ -83,19 +150,19 @@ public class PlayerAI extends BreadthFirstSearch implements Constants {
} }
break; break;
} }
sortDestinations();
return false; return false;
} }
/** /**
* Check conditions to to make sure that the AI doesn't go after unobtainable objectives * Check conditions for the goal, if they are not met don't go after that goal yet
* *
* @param objective The objective to check * @param scene The scene
* @return Returns true if the objective is obtainable * @param goal The goal
* @return Returns true if the goal is obtainable or false otherwise
*/ */
@Override default boolean checkCondition(Scene scene, State goal) {
public boolean checkCondition(State objective) { Player player = scene.getCanvas().getPlayer();
switch (objective.getOperation()) { switch (goal.getOperation()) {
case KEY: case KEY:
// If the player doesn't have the gems yet, get keys // If the player doesn't have the gems yet, get keys
if (player.getGemCount() < 2) { if (player.getGemCount() < 2) {
@ -125,12 +192,40 @@ public class PlayerAI extends BreadthFirstSearch implements Constants {
} }
/** /**
* Handle actions based on the states * Check if the spaces around the player are ope or not and return one of them randomly
*
* @param scene The scene
* @return Returns a random direction to go
*/ */
@Override default State.Type getOpenSpaceAroundPlayer(Scene scene) {
public void doAction() { Player player = scene.getCanvas().getPlayer();
if (getSteps().size() > 1) { List<State.Type> openSpaces = new ArrayList<>();
switch (getSteps().get(1)) { if (player.getCell().getX() > 0 && scene.getCells()[player.getCell().getX() - 1][player.getCell().getY()].getObject() == null) {
openSpaces.add(State.Type.LEFT);
}
if (player.getCell().getX() < HORIZONTAL_CELLS - 1 && scene.getCells()[player.getCell().getX() + 1][player.getCell().getY()].getObject() == null) {
openSpaces.add(State.Type.RIGHT);
}
if (player.getCell().getY() > 0 && scene.getCells()[player.getCell().getX()][player.getCell().getY() - 1].getObject() == null) {
openSpaces.add(State.Type.UP);
}
if (player.getCell().getY() < VERTICAL_CELLS - 1 && scene.getCells()[player.getCell().getX()][player.getCell().getY() + 1].getObject() == null) {
openSpaces.add(State.Type.DOWN);
}
int random = random(0, openSpaces.size() - 1);
return openSpaces.get(random);
}
/**
* Do the player control actions
*
* @param scene The scene
* @param steps The steps to follow
*/
default void doAction(Scene scene, List<State.Type> steps) {
Player player = scene.getCanvas().getPlayer();
if (steps.size() > 1) {
switch (steps.get(1)) {
case UP: case UP:
player.keyPressed(KeyEvent.VK_UP); player.keyPressed(KeyEvent.VK_UP);
break; break;
@ -144,72 +239,7 @@ public class PlayerAI extends BreadthFirstSearch implements Constants {
player.keyPressed(KeyEvent.VK_RIGHT); player.keyPressed(KeyEvent.VK_RIGHT);
break; break;
} }
}
scene.getCanvas().repaint(); scene.getCanvas().repaint();
} }
/**
* Move up
*
* @param state The previous state
*/
@Override
public void moveUp(State state) {
if (state.getY() > 0) {
if (scene.getCells()[state.getX()][state.getY() - 1].getObject() == null) {
super.moveUp(state);
}
}
}
/**
* Move down
*
* @param state The previous state
*/
@Override
public void moveDown(State state) {
if (state.getY() < VERTICAL_CELLS - 1) {
if (scene.getCells()[state.getX()][state.getY() + 1].getObject() == null) {
super.moveDown(state);
}
}
}
/**
* Move left
*
* @param state The previous state
*/
@Override
public void moveLeft(State state) {
if (state.getX() > 0) {
if (scene.getCells()[state.getX() - 1][state.getY()].getObject() == null) {
super.moveLeft(state);
}
}
}
/**
* Move right
*
* @param state The previous state
*/
@Override
public void moveRight(State state) {
if (state.getX() < HORIZONTAL_CELLS - 1) {
if (scene.getCells()[state.getX() + 1][state.getY()].getObject() == null) {
super.moveRight(state);
}
}
}
/**
* This method is called when the algorithm wants to know where the player is located at now
*/
@Override
public void getNewInitial() {
setInitial(new State(player.getCell().getX(), player.getCell().getY(), State.Type.PLAYER, null, 0));
} }
} }

View File

@ -0,0 +1,351 @@
/*
* Copyright 2019 Chris Cromer
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package cl.cromer.azaraka.ai;
import cl.cromer.azaraka.Constants;
import cl.cromer.azaraka.Scene;
import cl.cromer.azaraka.object.Enemy;
import cl.cromer.azaraka.object.Player;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* The class implements the A* search AI algorithm for the player
*/
public class PlayerAStarAI extends AI implements PlayerAI, Constants {
/**
* The player
*/
private final Player player;
/**
* The scene the AI is in
*/
private final Scene scene;
/**
* The queue of states being visited
*/
private final Queue<State> frontier = new PriorityQueue<>();
/**
* A hash map containing the states that have been visited
*/
private final Map<State, State> cameFrom = new HashMap<>();
/**
* A hash map containing the cost of the specific states
*/
private final Map<State, Double> costSoFar = new HashMap<>();
/**
* The steps to follow to get to the objective
*/
private final List<State.Type> steps = new ArrayList<>();
/**
* The destinations the player needs to visit
*/
private List<State> destinations = new ArrayList<>();
/**
* The objective that was found
*/
private State foundObjective;
/**
* The initial state to start searching from
*/
private State initial;
/**
* Initialize the A* algorithm
*
* @param scene The scene the algorithm is in
* @param player The player being controlled by AI
*/
public PlayerAStarAI(Scene scene, Player player) {
setLogger(getLogger(this.getClass(), Constants.LogLevel.AI));
this.scene = scene;
this.player = player;
}
/**
* Search for a path between the start point and the goal
*
* @param start The start point
* @param goal The goal
* @return Returns true if a path to the goal exists or false otherwise
*/
@Override
public boolean search(State start, State goal) {
start.setPriority(0);
frontier.add(start);
cameFrom.put(start, start);
costSoFar.put(start, 0.0);
while (frontier.size() > 0) {
State current = frontier.poll();
if (current.equals(goal)) {
foundObjective = current;
cameFrom.put(goal, current);
calculateRoute();
return true;
}
moveUp(current, goal);
moveDown(current, goal);
moveLeft(current, goal);
moveRight(current, goal);
}
return false;
}
/**
* Move to the next state using A* algorithm
*
* @param current The current state
* @param next The next state
* @param goal The goal state
*/
private void move(State current, State next, State goal) {
double newCost = costSoFar.get(current) + getCost(current);
if (!costSoFar.containsKey(next) || newCost < costSoFar.get(next)) {
costSoFar.put(next, newCost);
double priority = newCost + heuristic(next, goal);
next.setPriority(priority);
frontier.add(next);
cameFrom.put(next, current);
}
}
/**
* Check the state up from the current state
*
* @param current The current state
* @param goal The goal
*/
private void moveUp(State current, State goal) {
if (current.getY() > 0) {
if (scene.getCells()[current.getX()][current.getY() - 1].getObject() == null) {
State next = new State(current.getX(), current.getY() - 1, State.Type.UP, current, 0);
move(current, next, goal);
}
}
}
/**
* Check the state down from the current state
*
* @param current The current state
* @param goal The goal
*/
private void moveDown(State current, State goal) {
if (current.getY() < VERTICAL_CELLS - 1) {
if (scene.getCells()[current.getX()][current.getY() + 1].getObject() == null) {
State next = new State(current.getX(), current.getY() + 1, State.Type.DOWN, current, 0);
move(current, next, goal);
}
}
}
/**
* Check the state left from the current state
*
* @param current The current state
* @param goal The goal
*/
private void moveLeft(State current, State goal) {
if (current.getX() > 0) {
if (scene.getCells()[current.getX() - 1][current.getY()].getObject() == null) {
State next = new State(current.getX() - 1, current.getY(), State.Type.LEFT, current, 0);
move(current, next, goal);
}
}
}
/**
* Check the state right from the current state
*
* @param current The current state
* @param goal The goal
*/
private void moveRight(State current, State goal) {
if (current.getX() < HORIZONTAL_CELLS - 1) {
if (scene.getCells()[current.getX() + 1][current.getY()].getObject() == null) {
State next = new State(current.getX() + 1, current.getY(), State.Type.RIGHT, current, 0);
move(current, next, goal);
}
}
}
/**
* Calculate the cost of the state
*
* @param state The state to calculate
* @return Returns the cost
*/
private double getCost(State state) {
// The cost increases based on how close the enemy is
/*
2
444
24842
444
2
*/
if (state.getOperation() == State.Type.ENEMY) {
return 8;
}
else if (state.getX() > 0 && scene.getCells()[state.getX() - 1][state.getY()].getObject() instanceof Enemy) {
return 4;
}
else if (state.getX() < HORIZONTAL_CELLS - 1 && scene.getCells()[state.getX() + 1][state.getY()].getObject() instanceof Enemy) {
return 4;
}
else if (state.getY() > 0 && scene.getCells()[state.getX()][state.getY() - 1].getObject() instanceof Enemy) {
return 4;
}
else if (state.getY() < VERTICAL_CELLS - 1 && scene.getCells()[state.getX()][state.getY() + 1].getObject() instanceof Enemy) {
return 4;
}
else if (state.getX() > 1 && scene.getCells()[state.getX() - 2][state.getY()].getObject() instanceof Enemy) {
return 2;
}
else if (state.getX() < HORIZONTAL_CELLS - 2 && scene.getCells()[state.getX() + 2][state.getY()].getObject() instanceof Enemy) {
return 2;
}
else if (state.getY() > 1 && scene.getCells()[state.getX()][state.getY() - 2].getObject() instanceof Enemy) {
return 2;
}
else if (state.getY() < VERTICAL_CELLS - 2 && scene.getCells()[state.getX()][state.getY() + 2].getObject() instanceof Enemy) {
return 2;
}
else if (state.getX() > 0 && state.getY() > 0 && scene.getCells()[state.getX() - 1][state.getY() - 1].getObject() instanceof Enemy) {
return 4;
}
else if (state.getX() < HORIZONTAL_CELLS - 1 && state.getY() > 0 && scene.getCells()[state.getX() + 1][state.getY() - 1].getObject() instanceof Enemy) {
return 4;
}
else if (state.getX() > 0 && state.getY() < VERTICAL_CELLS - 1 && scene.getCells()[state.getX() - 1][state.getY() + 1].getObject() instanceof Enemy) {
return 4;
}
else if (state.getX() < HORIZONTAL_CELLS - 1 && state.getY() < VERTICAL_CELLS - 1 && scene.getCells()[state.getX() + 1][state.getY() + 1].getObject() instanceof Enemy) {
return 4;
}
return 1;
}
/**
* Add a destination to visit
*
* @param destination The destination to visit
*/
public void addDestination(State destination) {
destinations.add(destination);
}
/**
* Calculate the route from the objective to the player
*/
private void calculateRoute() {
getLogger().info("Calculate the route!");
State predecessor = foundObjective;
do {
steps.add(0, predecessor.getOperation());
predecessor = predecessor.getPredecessor();
}
while (predecessor != null);
}
/**
* Sort the destinations by importance, if the importance is the same then sort them by distance
*/
@Override
public void sortDestinations() {
destinations = sortDestinations(destinations, initial);
}
/**
* Clear the states to be ready for a new search
*/
private void clearStates() {
frontier.clear();
cameFrom.clear();
costSoFar.clear();
steps.clear();
}
/**
* Run this in a loop
*/
@Override
public void run() {
while (getActive()) {
try {
Thread.sleep(400);
}
catch (InterruptedException e) {
getLogger().info(e.getMessage());
}
clearStates();
int destinationIndex = 0;
boolean found = false;
do {
initial = new State(player.getCell().getX(), player.getCell().getY(), State.Type.PLAYER, null, 0);
State destination = destinations.get(destinationIndex);
if (checkCondition(scene, destination)) {
getLogger().info("Check A* Search goal!");
found = search(initial, destination);
}
if (initial.equals(destination)) {
if (destinationArrived(scene, destination)) {
destinations.remove(destination);
destinationIndex = 0;
}
}
else {
if (!found) {
clearStates();
// Don't run this because the destination might return to be available again at some point
//destinationArrived(objective);
}
}
if (destinations.isEmpty()) {
getLogger().info("No more destinations for A* Search!");
setActive(false);
}
destinationIndex++;
if (destinationIndex >= destinations.size()) {
destinationIndex = 0;
// No destinations are reachable, make the player move around at random to help move the enemies
if (steps.size() > 0) {
steps.add(1, getOpenSpaceAroundPlayer(scene));
}
}
}
while (!found && !destinations.isEmpty());
if (found) {
doAction(scene, steps);
}
}
}
}

View File

@ -0,0 +1,301 @@
/*
* Copyright 2019 Chris Cromer
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package cl.cromer.azaraka.ai;
import cl.cromer.azaraka.Constants;
import cl.cromer.azaraka.Scene;
import cl.cromer.azaraka.object.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* This is an implementation of the Breadth-First search algorithm with multiple objectives
*/
public class PlayerBreadthFirstAI extends AI implements PlayerAI, Constants {
/**
* The player
*/
private final Player player;
/**
* The scene the AI is in
*/
private final Scene scene;
/**
* The queued states to check
*/
private final Queue<State> queuedStates = new PriorityQueue<>();
/**
* The history of states that have been checked
*/
private final List<State> history = new ArrayList<>();
/**
* The steps to get to the objective
*/
private final List<State.Type> steps = new ArrayList<>();
/**
* If the search was successful or not
*/
private boolean success = false;
/**
* The state of the search objective
*/
private State searchGoal;
/**
* The destinations to visit
*/
private List<State> destinations = new ArrayList<>();
/**
* The initial point to start searching from
*/
private State initial;
/**
* Initialize the algorithm
*
* @param scene The scene the AI is in
* @param player The player being controlled by AI
*/
public PlayerBreadthFirstAI(Scene scene, Player player) {
setLogger(getLogger(this.getClass(), Constants.LogLevel.AI));
this.scene = scene;
this.player = player;
}
/**
* Find a path to the goal
*
* @param searchInitial The start point
* @param searchGoal The goal
* @return Returns true if a path to the goal is found or false otherwise
*/
public boolean search(State searchInitial, State searchGoal) {
this.searchGoal = searchGoal;
searchInitial.setPriority(getPriority(searchInitial));
queuedStates.add(searchInitial);
history.add(searchInitial);
success = searchInitial.equals(searchGoal);
while (!queuedStates.isEmpty() && !success) {
State current = queuedStates.poll();
moveUp(current);
moveDown(current);
moveLeft(current);
moveRight(current);
}
if (success) {
getLogger().info("Route to objective found!");
calculateRoute();
return true;
}
else {
getLogger().info("Route to objective not found!");
return false;
}
}
/**
* Add the next move to the queue
*
* @param next The next state
*/
private void move(State next) {
next.setPriority(getPriority(next));
if (!history.contains(next)) {
queuedStates.add(next);
history.add(next);
if (next.equals(searchGoal)) {
searchGoal = next;
success = true;
}
}
}
/**
* Move up
*
* @param current The current state
*/
private void moveUp(State current) {
if (current.getY() > 0) {
if (scene.getCells()[current.getX()][current.getY() - 1].getObject() == null) {
State next = new State(current.getX(), current.getY() - 1, State.Type.UP, current, -1);
move(next);
}
}
}
/**
* Move down
*
* @param current The current state
*/
private void moveDown(State current) {
if (current.getY() < VERTICAL_CELLS - 1) {
if (scene.getCells()[current.getX()][current.getY() + 1].getObject() == null) {
State next = new State(current.getX(), current.getY() + 1, State.Type.DOWN, current, -1);
move(next);
}
}
}
/**
* Move left
*
* @param current The current state
*/
private void moveLeft(State current) {
if (current.getX() > 0) {
if (scene.getCells()[current.getX() - 1][current.getY()].getObject() == null) {
State next = new State(current.getX() - 1, current.getY(), State.Type.LEFT, current, -1);
move(next);
}
}
}
/**
* Move right
*
* @param current The current state
*/
private void moveRight(State current) {
if (current.getX() < HORIZONTAL_CELLS - 1) {
if (scene.getCells()[current.getX() + 1][current.getY()].getObject() == null) {
State next = new State(current.getX() + 1, current.getY(), State.Type.RIGHT, current, -1);
move(next);
}
}
}
/**
* Calculate the route to the object
*/
private void calculateRoute() {
getLogger().info("Calculate the route!");
State predecessor = searchGoal;
do {
steps.add(0, predecessor.getOperation());
predecessor = predecessor.getPredecessor();
}
while (predecessor != null);
}
/**
* Get priority based on distance from the search objective
*
* @param state The state to get the priority for
* @return Returns the priority based on distance
*/
private double getPriority(State state) {
double goalDistance = Math.pow(Math.abs(state.getX() - searchGoal.getX()), 2) + Math.pow(Math.abs(state.getY() - searchGoal.getY()), 2);
goalDistance = Math.sqrt(goalDistance);
return goalDistance;
}
/**
* Add a destination to the AI
*
* @param destination The state containing the destination
*/
public void addDestination(State destination) {
destinations.add(destination);
}
/**
* Sort the destinations by importance, if the importance is the same then sort them by distance
*/
public void sortDestinations() {
destinations = sortDestinations(destinations, initial);
}
/**
* Clear the states to be ready for a new search
*/
private void clearStates() {
queuedStates.clear();
history.clear();
steps.clear();
}
/**
* Run the steps in a loop
*/
@Override
public void run() {
while (getActive()) {
try {
Thread.sleep(400);
}
catch (InterruptedException e) {
getLogger().info(e.getMessage());
}
synchronized (this) {
clearStates();
State destination;
boolean found = false;
int destinationIndex = 0;
do {
initial = new State(player.getCell().getX(), player.getCell().getY(), State.Type.PLAYER, null, 0);
destination = destinations.get(destinationIndex);
if (checkCondition(scene, destination)) {
getLogger().info("Check Breadth-First Search goal!");
found = search(initial, destination);
}
if (initial.equals(destination)) {
if (destinationArrived(scene, destination)) {
destinations.remove(destination);
destinationIndex = 0;
}
}
else {
if (!found) {
clearStates();
// Don't run this because the destination might return to be available again at some point
//destinationArrived(objective);
}
}
if (destinations.isEmpty()) {
getLogger().info("No more destinations for Breadth-First Search!");
setActive(false);
}
destinationIndex++;
if (destinationIndex >= destinations.size()) {
destinationIndex = 0;
if (steps.size() > 0) {
steps.add(1, getOpenSpaceAroundPlayer(scene));
}
}
}
while (!found && !destinations.isEmpty());
if (found) {
doAction(scene, steps);
}
}
}
}
}

View File

@ -1,257 +0,0 @@
/*
* Copyright 2019 Chris Cromer
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package cl.cromer.azaraka.ai;
import java.util.ArrayList;
import java.util.logging.Logger;
/**
* AI algorithms extends this class
*/
public class SearchAI implements Runnable {
/**
* The queued states to check
*/
private final ArrayList<State> queuedStates = new ArrayList<>();
/**
* The history of states that have been checked
*/
private final ArrayList<State> history = new ArrayList<>();
/**
* The logger
*/
private Logger logger;
/**
* Whether or not the run loop of the AI is active
*/
private boolean active;
/**
* If the search was successful or not
*/
private boolean success = false;
/**
* The state of the search objective
*/
private State searchObjective;
/**
* Initialize the AI
*/
protected SearchAI() {
}
/**
* Find a path to the objective
*
* @param searchInitial The start point
* @param searchObjective The objective
* @return Returns true if a path to the objective is found or false otherwise
*/
public boolean search(State searchInitial, State searchObjective) {
getQueuedStates().add(searchInitial);
getHistory().add(searchInitial);
setSearchObjective(searchObjective);
success = searchInitial.equals(searchObjective);
while (!getQueuedStates().isEmpty() && !success) {
State temp = getQueuedStates().get(0);
getQueuedStates().remove(0);
moveUp(temp);
moveDown(temp);
moveLeft(temp);
moveRight(temp);
}
if (success) {
getLogger().info("Route to objective found!");
try {
calculateRoute();
}
catch (AIException e) {
getLogger().warning(e.getMessage());
}
return true;
}
else {
getLogger().info("Route to objective not found!");
return false;
}
}
/**
* Calculate the route to the objective
*
* @throws AIException Thrown if called via super
*/
protected void calculateRoute() throws AIException {
String methodName = new Throwable().getStackTrace()[0].getMethodName();
throw new AIException("Do not call " + methodName + "using super!");
}
/**
* Get the active state of the AI
*
* @return Returns true if the AI is active or false otherwise
*/
protected boolean getActive() {
return active;
}
/**
* Set the active state for the AI loop
*
* @param active Set to true to have the run method loop run indefinitely or false to stop the loop
*/
public void setActive(boolean active) {
this.active = active;
}
/**
* Get the logger
*
* @return Returns a logger
*/
protected Logger getLogger() {
return logger;
}
/**
* Set the logger
*
* @param logger The logger to set
*/
protected void setLogger(Logger logger) {
this.logger = logger;
}
/**
* Get queued states
*
* @return Returns the history of checked states
*/
protected ArrayList<State> getQueuedStates() {
return queuedStates;
}
/**
* Get the history
*
* @return Returns the history of checked states
*/
protected ArrayList<State> getHistory() {
return history;
}
/**
* Get the search objective
*
* @return Returns the search objective state
*/
protected State getSearchObjective() {
return searchObjective;
}
/**
* Set the search objective
*
* @param searchObjective The search objective state
*/
private void setSearchObjective(State searchObjective) {
this.searchObjective = searchObjective;
}
/**
* Move up if possible
*
* @param state The previous state
*/
protected void moveUp(State state) {
State up = new State(state.getX(), state.getY() - 1, State.Type.UP, state, state.getImportance());
if (!history.contains(up)) {
queuedStates.add(up);
history.add(up);
if (up.equals(searchObjective)) {
searchObjective = up;
success = true;
}
}
}
/**
* Move down if possible
*
* @param state The previous state
*/
protected void moveDown(State state) {
State down = new State(state.getX(), state.getY() + 1, State.Type.DOWN, state, state.getImportance());
if (!history.contains(down)) {
queuedStates.add(down);
history.add(down);
if (down.equals(searchObjective)) {
searchObjective = down;
success = true;
}
}
}
/**
* Move left if possible
*
* @param state The previous state
*/
protected void moveLeft(State state) {
State left = new State(state.getX() - 1, state.getY(), State.Type.LEFT, state, state.getImportance());
if (!history.contains(left)) {
queuedStates.add(left);
history.add(left);
if (left.equals(searchObjective)) {
searchObjective = left;
success = true;
}
}
}
/**
* Move right if possible
*
* @param state The previous state
*/
protected void moveRight(State state) {
State right = new State(state.getX() + 1, state.getY(), State.Type.RIGHT, state, state.getImportance());
if (!history.contains(right)) {
queuedStates.add(right);
history.add(right);
if (right.equals(searchObjective)) {
searchObjective = right;
success = true;
}
}
}
/**
* The run method
*/
@Override
public void run() {
setActive(true);
}
}

View File

@ -16,9 +16,9 @@
package cl.cromer.azaraka.ai; package cl.cromer.azaraka.ai;
/** /**
* The state of the Breadth-First Search algorithm * The states used in the AI algorithms
*/ */
public class State { public class State implements Comparable {
/** /**
* The x position being checked * The x position being checked
*/ */
@ -39,6 +39,10 @@ public class State {
* The importance of the objective, higher is more important * The importance of the objective, higher is more important
*/ */
private final int importance; private final int importance;
/**
* This handles the priority based on enemy distance
*/
private double priority;
/** /**
* Initialize the state * Initialize the state
@ -102,6 +106,24 @@ public class State {
return importance; return importance;
} }
/**
* Get the priority of the state
*
* @return The priority
*/
private double getPriority() {
return priority;
}
/**
* Set the priority of a given state
*
* @param priority The priority value
*/
public void setPriority(double priority) {
this.priority = priority;
}
/** /**
* Overridden equals to compare the x and y coordinates * Overridden equals to compare the x and y coordinates
* *
@ -119,7 +141,27 @@ public class State {
} }
State that = (State) object; State that = (State) object;
return (this.x == that.getX() && this.y == that.getY()); return (this.getX() == that.getX() && this.getY() == that.getY());
}
/**
* This is used to compare priorities in a priority queue
*
* @param object The object to compare
* @return Returns the value of Double.compare()
*/
@Override
public int compareTo(Object object) {
State that = (State) object;
return Double.compare(this.getPriority(), that.getPriority());
}
@Override
public int hashCode() {
int result = 23;
result = result * 23 + x;
result = result * 23 + y;
return result;
} }
/** /**

View File

@ -18,12 +18,15 @@ package cl.cromer.azaraka.object;
import cl.cromer.azaraka.Cell; import cl.cromer.azaraka.Cell;
import cl.cromer.azaraka.Constants; import cl.cromer.azaraka.Constants;
import cl.cromer.azaraka.Scene; import cl.cromer.azaraka.Scene;
import cl.cromer.azaraka.ai.PlayerAI; import cl.cromer.azaraka.ai.AI;
import cl.cromer.azaraka.ai.PlayerAStarAI;
import cl.cromer.azaraka.ai.PlayerBreadthFirstAI;
import cl.cromer.azaraka.sprite.Animation; import cl.cromer.azaraka.sprite.Animation;
import cl.cromer.azaraka.sprite.AnimationException; import cl.cromer.azaraka.sprite.AnimationException;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
/** /**
* This class contains the player * This class contains the player
@ -36,11 +39,11 @@ public class Player extends Object implements Constants {
/** /**
* Objects that the player is carrying * Objects that the player is carrying
*/ */
private final ArrayList<Object> carrying = new ArrayList<>(); private final List<Object> carrying = new ArrayList<>();
/** /**
* The artificial intelligence of the player * The artificial intelligence of the player
*/ */
private final PlayerAI ai; private final AI ai;
/** /**
* The current health of the player * The current health of the player
*/ */
@ -56,7 +59,15 @@ public class Player extends Object implements Constants {
super(scene, cell); super(scene, cell);
setLogger(getLogger(this.getClass(), LogLevel.PLAYER)); setLogger(getLogger(this.getClass(), LogLevel.PLAYER));
loadPlayerAnimation(); loadPlayerAnimation();
ai = new PlayerAI(scene, this); if (PLAYER_AI == PlayerAIType.ASTAR) {
ai = new PlayerAStarAI(scene, this);
}
else if (PLAYER_AI == PlayerAIType.BFS) {
ai = new PlayerBreadthFirstAI(scene, this);
}
else {
ai = null;
}
} }
/** /**
@ -82,7 +93,7 @@ public class Player extends Object implements Constants {
*/ */
public void keyPressed(int keyCode) { public void keyPressed(int keyCode) {
if (getScene().isDoorOpen()) { if (getScene().isDoorOpen()) {
ArrayList<Gem> gems = getInventoryGems(true); List<Gem> gems = getInventoryGems(true);
if (gems.size() < 2) { if (gems.size() < 2) {
getScene().openDoor(false); getScene().openDoor(false);
} }
@ -478,7 +489,7 @@ public class Player extends Object implements Constants {
* *
* @return Returns the current AI in use * @return Returns the current AI in use
*/ */
public PlayerAI getAi() { public AI getAi() {
return ai; return ai;
} }
@ -488,8 +499,8 @@ public class Player extends Object implements Constants {
* @param all Whether or not to return the gems that are still in transition to inventory * @param all Whether or not to return the gems that are still in transition to inventory
* @return Returns an array of the gems the player is carrying * @return Returns an array of the gems the player is carrying
*/ */
public ArrayList<Gem> getInventoryGems(boolean all) { public List<Gem> getInventoryGems(boolean all) {
ArrayList<Gem> gems = new ArrayList<>(); List<Gem> gems = new ArrayList<>();
for (Object object : carrying) { for (Object object : carrying) {
if (object instanceof Gem) { if (object instanceof Gem) {
if (!all && object.getCell().getObjectOnTop() != null) { if (!all && object.getCell().getObjectOnTop() != null) {

View File

@ -23,7 +23,7 @@ import cl.cromer.azaraka.sound.SoundException;
import cl.cromer.azaraka.sprite.Animation; import cl.cromer.azaraka.sprite.Animation;
import cl.cromer.azaraka.sprite.AnimationException; import cl.cromer.azaraka.sprite.AnimationException;
import java.util.ArrayList; import java.util.List;
/** /**
* This class handles the portal functionality * This class handles the portal functionality
@ -92,7 +92,7 @@ public class Portal extends Object implements Constants {
*/ */
public void purifyGems() { public void purifyGems() {
if (state == State.ACTIVE) { if (state == State.ACTIVE) {
ArrayList<Gem> gems = getScene().getCanvas().getPlayer().getInventoryGems(true); List<Gem> gems = getScene().getCanvas().getPlayer().getInventoryGems(true);
boolean purified = false; boolean purified = false;
for (Gem gem : gems) { for (Gem gem : gems) {
if (gem.getState() == Gem.State.TAINTED) { if (gem.getState() == Gem.State.TAINTED) {

View File

@ -24,6 +24,8 @@ import java.awt.image.BufferedImage;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger; import java.util.logging.Logger;
/** /**
@ -33,7 +35,7 @@ public class Animation implements Cloneable, Constants {
/** /**
* The collection of all the images that make up the object * The collection of all the images that make up the object
*/ */
private final HashMap<Direction, ArrayList<BufferedImage>> imageHash; private final Map<Direction, List<BufferedImage>> imageHash;
/** /**
* The logger * The logger
*/ */
@ -175,7 +177,7 @@ public class Animation implements Cloneable, Constants {
calculateXOffset(bufferedImage.getWidth()); calculateXOffset(bufferedImage.getWidth());
calculateYOffset(bufferedImage.getHeight()); calculateYOffset(bufferedImage.getHeight());
ArrayList<BufferedImage> images; List<BufferedImage> images;
if (imageHash.containsKey(direction)) { if (imageHash.containsKey(direction)) {
images = imageHash.get(direction); images = imageHash.get(direction);
} }
@ -193,7 +195,7 @@ public class Animation implements Cloneable, Constants {
* @throws AnimationException Thrown when there are no images in the sprite * @throws AnimationException Thrown when there are no images in the sprite
*/ */
public BufferedImage getFrame() throws AnimationException { public BufferedImage getFrame() throws AnimationException {
ArrayList<BufferedImage> images = getImagesFromHash(); List<BufferedImage> images = getImagesFromHash();
if (currentFrame >= images.size()) { if (currentFrame >= images.size()) {
throw new AnimationException("Animation does not have frame: " + currentFrame); throw new AnimationException("Animation does not have frame: " + currentFrame);
} }
@ -217,7 +219,7 @@ public class Animation implements Cloneable, Constants {
* @throws AnimationException Thrown if there are no frame in the current animation * @throws AnimationException Thrown if there are no frame in the current animation
*/ */
public int getCurrentFrame() throws AnimationException { public int getCurrentFrame() throws AnimationException {
ArrayList<BufferedImage> images; List<BufferedImage> images;
if (imageHash.containsKey(currentDirection)) { if (imageHash.containsKey(currentDirection)) {
images = imageHash.get(currentDirection); images = imageHash.get(currentDirection);
if (images.size() == 0) { if (images.size() == 0) {
@ -238,7 +240,7 @@ public class Animation implements Cloneable, Constants {
* @throws AnimationException Thrown if the frame number does not exist * @throws AnimationException Thrown if the frame number does not exist
*/ */
public void setCurrentFrame(int frame) throws AnimationException { public void setCurrentFrame(int frame) throws AnimationException {
ArrayList<BufferedImage> images; List<BufferedImage> images;
if (imageHash.containsKey(currentDirection)) { if (imageHash.containsKey(currentDirection)) {
images = imageHash.get(currentDirection); images = imageHash.get(currentDirection);
} }
@ -261,7 +263,7 @@ public class Animation implements Cloneable, Constants {
* @throws AnimationException Thrown when there are no images in the sprite * @throws AnimationException Thrown when there are no images in the sprite
*/ */
public void getNextFrame() throws AnimationException { public void getNextFrame() throws AnimationException {
ArrayList<BufferedImage> images = getImagesFromHash(); List<BufferedImage> images = getImagesFromHash();
currentFrame++; currentFrame++;
if (currentFrame >= images.size()) { if (currentFrame >= images.size()) {
currentFrame = 0; currentFrame = 0;
@ -274,8 +276,8 @@ public class Animation implements Cloneable, Constants {
* @return The images for the specific direction * @return The images for the specific direction
* @throws AnimationException Thrown if there are no images in the hash or no images in the sprite * @throws AnimationException Thrown if there are no images in the hash or no images in the sprite
*/ */
private ArrayList<BufferedImage> getImagesFromHash() throws AnimationException { private List<BufferedImage> getImagesFromHash() throws AnimationException {
ArrayList<BufferedImage> images; List<BufferedImage> images;
if (imageHash.containsKey(currentDirection)) { if (imageHash.containsKey(currentDirection)) {
images = imageHash.get(currentDirection); images = imageHash.get(currentDirection);
} }