Implement A* Search

Many changes to improve AI usage

Signed-off-by: Chris Cromer <chris@cromer.cl>
master
Chris Cromer 3 years ago
parent 1ac56b3b39
commit cbcb6d0d01
  1. 1
      .idea/dictionaries/cromer.xml
  2. 102
      build.gradle
  3. 53
      src/main/java/cl/cromer/azaraka/Canvas.java
  4. 2
      src/main/java/cl/cromer/azaraka/Cell.java
  5. 24
      src/main/java/cl/cromer/azaraka/Constants.java
  6. 8
      src/main/java/cl/cromer/azaraka/Scene.java
  7. 95
      src/main/java/cl/cromer/azaraka/ai/AI.java
  8. 6
      src/main/java/cl/cromer/azaraka/ai/AIException.java
  9. 239
      src/main/java/cl/cromer/azaraka/ai/BreadthFirstSearch.java
  10. 151
      src/main/java/cl/cromer/azaraka/ai/DepthFirstSearch.java
  11. 212
      src/main/java/cl/cromer/azaraka/ai/EnemyAI.java
  12. 226
      src/main/java/cl/cromer/azaraka/ai/PlayerAI.java
  13. 351
      src/main/java/cl/cromer/azaraka/ai/PlayerAStarAI.java
  14. 301
      src/main/java/cl/cromer/azaraka/ai/PlayerBreadthFirstAI.java
  15. 257
      src/main/java/cl/cromer/azaraka/ai/SearchAI.java
  16. 48
      src/main/java/cl/cromer/azaraka/ai/State.java
  17. 27
      src/main/java/cl/cromer/azaraka/object/Player.java
  18. 4
      src/main/java/cl/cromer/azaraka/object/Portal.java
  19. 18
      src/main/java/cl/cromer/azaraka/sprite/Animation.java

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

@ -14,101 +14,89 @@
*/
plugins {
id 'idea'
id 'java'
id 'application'
id 'distribution'
id 'idea'
id 'java'
id 'application'
id 'distribution'
}
group 'cl.cromer.azaraka'
version '1.0.0'
//noinspection GroovyUnusedAssignment
sourceCompatibility = 1.8
//noinspection GroovyUnusedAssignment
targetCompatibility = 1.8
//noinspection GroovyUnusedAssignment
applicationName = 'Azaraka'
mainClassName = 'cl.cromer.azaraka.Azaraka'
idea {
module {
downloadJavadoc = true
downloadSources = true
}
module {
downloadJavadoc = true
downloadSources = true
}
}
repositories {
mavenCentral()
mavenCentral()
}
dependencies {
implementation group: 'com.google.code.gson', name: 'gson', version: '2.+'
//testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.+'
implementation group: 'com.google.code.gson', name: 'gson', version: '2.+'
//testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.+'
}
//noinspection GrUnresolvedAccess
ext.sharedManifest = manifest {
//noinspection GrUnresolvedAccess
attributes 'Main-Class': "$mainClassName",
'Class-Path': configurations.default.files.collect { "$it.name" }.join(' '),
'Implementation-Title': 'Gradle',
'Implementation-Version': "$gradle.gradleVersion"
attributes 'Main-Class': "$mainClassName",
'Class-Path': configurations.default.files.collect { "$it.name" }.join(' '),
'Implementation-Title': 'Gradle',
'Implementation-Version': "$gradle.gradleVersion"
}
jar {
manifest = project.manifest {
//noinspection GroovyAssignabilityCheck
from sharedManifest
}
if (project.uberJar == "true") {
//noinspection GroovyAssignabilityCheck
from sourceSets.main.output
dependsOn configurations.runtimeClasspath
from {
configurations.runtimeClasspath.findAll { it.name.endsWith('jar') }.collect { zipTree(it) }
}
}
manifest = project.manifest {
from sharedManifest
}
if (project.uberJar == "true") {
from sourceSets.main.output
dependsOn configurations.runtimeClasspath
from {
configurations.runtimeClasspath.findAll { it.name.endsWith('jar') }.collect { zipTree(it) }
}
}
else {
dependsOn tasks.withType(Copy)
}
dependsOn tasks.withType(Copy)
}
}
task copyDependencies(type: Copy) {
from configurations.default
into "$buildDir/libs"
from configurations.default
into "$buildDir/libs"
}
plugins.withType(DistributionPlugin) {
distTar {
//noinspection GroovyAssignabilityCheck, GroovyAccessibility
archiveExtension = 'tar.gz'
compression = Compression.GZIP
}
distTar {
archiveExtension = 'tar.gz'
compression = Compression.GZIP
}
}
task createDocs {
def docs = file("$buildDir/docs")
outputs.dir docs
def docs = file("$buildDir/docs")
outputs.dir docs
}
distributions {
//noinspection GroovyAssignabilityCheck
main {
//noinspection GrUnresolvedAccess
contents {
//noinspection GrUnresolvedAccess
from(createDocs) {
//noinspection GrUnresolvedAccess
into 'docs'
}
}
}
main {
contents {
from(createDocs) {
into 'docs'
}
}
}
}
wrapper {
gradleVersion = '5.6.2'
gradleVersion = '5.6.2'
}

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

@ -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
*/
private final LinkedHashMap<Integer, BufferedImage> textures = new LinkedHashMap<>();
private final Map<Integer, BufferedImage> textures = new LinkedHashMap<>();
/**
* The object in the cell
*/

@ -35,9 +35,9 @@ public interface Constants {
*/
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
*/
@ -81,7 +81,7 @@ public interface Constants {
/**
* 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
*/
@ -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
*/

@ -17,6 +17,7 @@ package cl.cromer.azaraka;
import cl.cromer.azaraka.ai.EnemyAI;
import cl.cromer.azaraka.ai.PlayerAI;
import cl.cromer.azaraka.ai.PlayerBreadthFirstAI;
import cl.cromer.azaraka.ai.State;
import cl.cromer.azaraka.json.Json;
import cl.cromer.azaraka.json.JsonCell;
@ -42,6 +43,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
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
*/
public ArrayList<Object> generateRandomObjects() {
public List<Object> generateRandomObjects() {
int[] random;
ArrayList<Object> objectArrayList = new ArrayList<>();
List<Object> objectArrayList = new ArrayList<>();
// The player has a fixed position
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
*/
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 objectiveState = new State(x, y, State.Type.EXIT, null, 0);
return !playerAI.search(playerState, objectiveState);

@ -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() {
}
}

@ -16,13 +16,13 @@
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 {
/**
* Initialize the AI exception
* Throw an error with a message
*
* @param errorMessage The message thrown
* @param errorMessage The message
*/
public AIException(String errorMessage) {
super(errorMessage);

@ -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());
}
}
}
}
}

@ -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());
}
}
}
}
}

@ -21,10 +21,18 @@ import cl.cromer.azaraka.object.Enemy;
import cl.cromer.azaraka.object.Object;
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
*/
@ -33,56 +41,102 @@ public class EnemyAI extends DepthFirstSearch implements Constants {
* The scene the AI is in
*/
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
*
* @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) {
super();
setLogger(getLogger(this.getClass(), LogLevel.AI));
logger = getLogger(this.getClass(), Constants.LogLevel.AI);
this.scene = scene;
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
*/
@Override
public void doAction() {
if (getSteps().size() > 1) {
switch (getSteps().get(1)) {
case UP:
enemy.moveUp();
break;
case DOWN:
enemy.moveDown();
break;
case LEFT:
enemy.moveLeft();
break;
case RIGHT:
enemy.moveRight();
break;
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;
}
scene.getCanvas().repaint();
}
}
/**
* Move up
*
* @param state The previous state
* @param current The current state
*/
@Override
public void moveUp(State state) {
if (state.getY() > 0) {
Object object = scene.getCells()[state.getX()][state.getY() - 1].getObject();
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) {
super.moveUp(state);
State next = new State(current.getX(), current.getY() - 1, State.Type.UP, current, current.getImportance());
move(next);
}
}
}
@ -90,14 +144,14 @@ public class EnemyAI extends DepthFirstSearch implements Constants {
/**
* Move down
*
* @param state The previous state
* @param current The current state
*/
@Override
public void moveDown(State state) {
if (state.getY() < VERTICAL_CELLS - 1) {
Object object = scene.getCells()[state.getX()][state.getY() + 1].getObject();
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) {
super.moveDown(state);
State next = new State(current.getX(), current.getY() + 1, State.Type.DOWN, current, current.getImportance());
move(next);
}
}
}
@ -105,14 +159,14 @@ public class EnemyAI extends DepthFirstSearch implements Constants {
/**
* Move left
*
* @param state The previous state
* @param current The current state
*/
@Override
public void moveLeft(State state) {
if (state.getX() > 0) {
Object object = scene.getCells()[state.getX() - 1][state.getY()].getObject();
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) {
super.moveLeft(state);
State next = new State(current.getX() - 1, current.getY(), State.Type.LEFT, current, current.getImportance());
move(next);
}
}
}
@ -120,32 +174,78 @@ public class EnemyAI extends DepthFirstSearch implements Constants {
/**
* Move right
*
* @param state The previous state
* @param current The current state
*/
@Override
public void moveRight(State state) {
if (state.getX() < HORIZONTAL_CELLS - 1) {
Object object = scene.getCells()[state.getX() + 1][state.getY()].getObject();
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) {
super.moveRight(state);
State next = new State(current.getX() + 1, current.getY(), State.Type.RIGHT, current, current.getImportance());
move(next);
}
}
}
/**
* This method is called when the algorithm wants to know where the enemy is located at now
* Calculate the route to the goal
*/
@Override
public void getNewInitial() {
setInitial(new State(enemy.getCell().getX(), enemy.getCell().getY(), State.Type.ENEMY, null, 0));
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();
}
/**
* The method is called when the algorithm wants to know where the player is located at now
* Run the steps in a loop
*/
@Override
public void getNewObjective() {
setObjective(new State(scene.getCanvas().getPlayer().getCell().getX(), scene.getCanvas().getPlayer().getCell().getY(), State.Type.PLAYER, null, 0));
public void run() {
while (getActive()) {
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:
enemy.moveUp();
break;
case DOWN:
enemy.moveDown();
break;
case LEFT:
enemy.moveLeft();
break;
case RIGHT:
enemy.moveRight();
break;
}
scene.getCanvas().repaint();
}
}
}
}
}
}

@ -22,41 +22,107 @@ import cl.cromer.azaraka.object.Portal;
import cl.cromer.azaraka.sprite.Animation;
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
*/
boolean search(State start, State goal);
/**
* Add a destination to the list of destinations
*
* @param destination The new destination
*/
private final Player player;
void addDestination(State destination);
/**
* The scene the AI is in
* Sor the destinations based on importance and distance
*/
private final Scene scene;
void sortDestinations();
/**
* Initialize the algorithm
* The heuristic to get the distance between the start state and the end state
*
* @param scene The scene the AI is in
* @param player The player controlled by the AI
* @param start The start state
* @param goal The goal state
* @return Returns the distance between the states
*/
public PlayerAI(Scene scene, Player player) {
super();
setLogger(getLogger(this.getClass(), LogLevel.AI));
this.scene = scene;
this.player = player;
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
public boolean destinationArrived(State objective) {
switch (objective.getOperation()) {
default List<State> sortDestinations(List<State> destinations, State initial) {
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 = heuristic(initial, state1);
double state2Distance = heuristic(initial, state2);