Browse Source

Update gradle build file to ignore false positive warnings

Move shared functionality into the SearchAI class
Move shared functionality into the Object class
Add new state enum types
Implement enemy AI
Make player get the gem right away
Fix keyListener still listening after winning or game over
Reduce obstacles to 5%
Make sure all objectives can be reached by player
Make sure all enemies can reach player

Signed-off-by: Chris Cromer <chris@cromer.cl>
master
Chris Cromer 2 years ago
parent
commit
00c54e5e15
  1. 16
      build.gradle
  2. 1
      gradle.properties
  3. 1
      gradle/wrapper/gradle-wrapper.properties
  4. 198
      src/main/java/cl/cromer/azaraka/Canvas.java
  5. 26
      src/main/java/cl/cromer/azaraka/Constants.java
  6. 2
      src/main/java/cl/cromer/azaraka/MainWindow.java
  7. 39
      src/main/java/cl/cromer/azaraka/Scene.java
  8. 82
      src/main/java/cl/cromer/azaraka/ai/AI.java
  9. 144
      src/main/java/cl/cromer/azaraka/ai/BreadthFirstSearch.java
  10. 151
      src/main/java/cl/cromer/azaraka/ai/DepthFirstSearch.java
  11. 151
      src/main/java/cl/cromer/azaraka/ai/EnemyAI.java
  12. 26
      src/main/java/cl/cromer/azaraka/ai/PlayerAI.java
  13. 257
      src/main/java/cl/cromer/azaraka/ai/SearchAI.java
  14. 8
      src/main/java/cl/cromer/azaraka/ai/State.java
  15. 2
      src/main/java/cl/cromer/azaraka/object/Chest.java
  16. 243
      src/main/java/cl/cromer/azaraka/object/Enemy.java
  17. 112
      src/main/java/cl/cromer/azaraka/object/Object.java
  18. 151
      src/main/java/cl/cromer/azaraka/object/Player.java

16
build.gradle

@ -22,9 +22,12 @@ plugins {
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'
@ -37,7 +40,9 @@ dependencies {
//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',
@ -46,18 +51,19 @@ ext.sharedManifest = manifest {
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) }
}
}
else {
} else {
dependsOn tasks.withType(Copy)
}
}
@ -81,15 +87,19 @@ task createDocs {
}
distributions {
//noinspection GroovyAssignabilityCheck
main {
//noinspection GrUnresolvedAccess
contents {
//noinspection GrUnresolvedAccess
from(createDocs) {
//noinspection GrUnresolvedAccess
into 'docs'
}
}
}
}
wrapper{
wrapper {
gradleVersion = '5.6.2'
}

1
gradle.properties

@ -12,7 +12,6 @@
# 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.
#
#
org.gradle.caching=true
org.gradle.parallel=true
uberJar=false

1
gradle/wrapper/gradle-wrapper.properties

@ -12,7 +12,6 @@
# 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.
#
#
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip

198
src/main/java/cl/cromer/azaraka/Canvas.java

@ -15,7 +15,7 @@
package cl.cromer.azaraka;
import cl.cromer.azaraka.ai.AI;
import cl.cromer.azaraka.ai.SearchAI;
import cl.cromer.azaraka.ai.State;
import cl.cromer.azaraka.object.Chest;
import cl.cromer.azaraka.object.Enemy;
@ -37,6 +37,7 @@ import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@ -91,7 +92,7 @@ public class Canvas extends java.awt.Canvas implements Constants {
/**
* The threads that control AI
*/
private final HashMap<AI, Thread> aiThreads = new HashMap<>();
private final HashMap<SearchAI, Thread> aiThreads = new HashMap<>();
/**
* The graphics buffer
*/
@ -148,10 +149,6 @@ public class Canvas extends java.awt.Canvas implements Constants {
* Game over
*/
private boolean gameOver = false;
/**
* If the game over loop has been run at least once
*/
private boolean gameOverRan = false;
/**
* The sound of the door opening or closing
*/
@ -168,6 +165,10 @@ public class Canvas extends java.awt.Canvas implements Constants {
* Has the game been won
*/
private boolean won = false;
/**
* The key listener for the player
*/
private KeyListener playerKeyListener;
/**
* Initialize the canvas
@ -177,7 +178,7 @@ public class Canvas extends java.awt.Canvas implements Constants {
* @param height The width to set the canvas
*/
public Canvas(Azaraka azaraka, int width, int height) {
logger = getLogger(this.getClass(), LogLevel.LIENZO);
logger = getLogger(this.getClass(), LogLevel.CANVAS);
this.azaraka = azaraka;
setSize(width, height);
@ -236,22 +237,24 @@ public class Canvas extends java.awt.Canvas implements Constants {
}
else if (object instanceof Enemy) {
object.getCell().setObject(object);
if (enemyDirection == Enemy.Direction.UP) {
enemyDirection = Enemy.Direction.DOWN;
}
else if (enemyDirection == Enemy.Direction.DOWN) {
enemyDirection = Enemy.Direction.LEFT;
}
else if (enemyDirection == Enemy.Direction.LEFT) {
enemyDirection = Enemy.Direction.RIGHT;
}
else {
enemyDirection = Enemy.Direction.UP;
}
((Enemy) object).setDirection(enemyDirection);
((Enemy) object).setSound(enemyAttackSound);
enemies.add((Enemy) object);
threads.put(object, new Thread(object));
if (!ENEMY_AI) {
if (enemyDirection == Enemy.Direction.UP) {
enemyDirection = Enemy.Direction.DOWN;
}
else if (enemyDirection == Enemy.Direction.DOWN) {
enemyDirection = Enemy.Direction.LEFT;
}
else if (enemyDirection == Enemy.Direction.LEFT) {
enemyDirection = Enemy.Direction.RIGHT;
}
else {
enemyDirection = Enemy.Direction.UP;
}
((Enemy) object).setDirection(enemyDirection);
threads.put(object, new Thread(object));
}
}
else if (object instanceof Chest) {
object.getCell().setObject(object);
@ -290,21 +293,17 @@ public class Canvas extends java.awt.Canvas implements Constants {
setupPlayerAI();
}
else {
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent event) {
super.keyPressed(event);
if (!gameOver) {
player.keyPressed(event);
repaint();
}
}
});
playerKeyListener = getPlayerKeyListener();
addKeyListener(playerKeyListener);
}
if (ENEMY_AI) {
setupEnemyAI();
}
}
/**
* Set up the player AI
* Setup the player AI
*/
private void setupPlayerAI() {
player.getAi().addDestination(new State(2, 0, State.Type.EXIT, null, 3));
@ -312,11 +311,11 @@ public class Canvas extends java.awt.Canvas implements Constants {
// 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, 1));
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, 0));
player.getAi().addDestination(new State(key.getCell().getX(), key.getCell().getY(), State.Type.KEY, null, 2));
}
player.getAi().sortDestinations();
@ -326,6 +325,17 @@ public class Canvas extends java.awt.Canvas implements Constants {
aiThreads.put(player.getAi(), thread);
}
/**
* Setup the enemy AI
*/
private void setupEnemyAI() {
for (Enemy enemy : enemies) {
Thread thread = new Thread(enemy.getAi());
thread.start();
aiThreads.put(enemy.getAi(), thread);
}
}
/**
* Override the paint method of Canvas to paint all the scene components
*
@ -367,9 +377,6 @@ public class Canvas extends java.awt.Canvas implements Constants {
if (player != null) {
int health = player.getHealth();
if (health == 0) {
gameOver = true;
}
int hearts = Player.MAX_HEALTH / 4;
if (heartAnimation == null) {
heartAnimation = new Animation();
@ -396,32 +403,6 @@ public class Canvas extends java.awt.Canvas implements Constants {
}
if (gameOver) {
if (!gameOverRan) {
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent event) {
super.keyPressed(event);
if (event.getKeyCode() == KeyEvent.VK_ENTER) {
azaraka.restart();
}
}
});
stopBackgroundMusic();
try {
gameOverMusic.setVolume(volume);
gameOverMusic.play();
}
catch (SoundException e) {
logger.warning(e.getMessage());
}
stopThreads();
gameOverRan = true;
}
// Place the game over image on the screen
graphicBuffer.setColor(Color.black);
graphicBuffer.drawRect(0, 0, getWidth(), getHeight());
@ -458,16 +439,6 @@ public class Canvas extends java.awt.Canvas implements Constants {
int x = rectangle.x + (rectangle.width - metrics.stringWidth(message)) / 2;
int y = rectangle.y + ((rectangle.height - metrics.getHeight()) / 2) + metrics.getAscent();
graphicBuffer.drawString(message, x, y);
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent event) {
super.keyPressed(event);
if (event.getKeyCode() == KeyEvent.VK_ENTER) {
System.exit(0);
}
}
});
}
}
@ -513,29 +484,44 @@ public class Canvas extends java.awt.Canvas implements Constants {
Object object = entry.getKey();
object.setActive(false);
thread.interrupt();
try {
thread.join();
}
catch (InterruptedException e) {
logger.info(e.getMessage());
}
}
}
// Stop AI threads
for (Map.Entry<AI, Thread> entry : aiThreads.entrySet()) {
for (Map.Entry<SearchAI, Thread> entry : aiThreads.entrySet()) {
Thread thread = entry.getValue();
if (thread.isAlive()) {
AI ai = entry.getKey();
SearchAI ai = entry.getKey();
ai.setActive(false);
thread.interrupt();
try {
thread.join();
}
catch (InterruptedException e) {
logger.info(e.getMessage());
}
}
}
/**
* The player died, game over
*/
public void gameOver() {
gameOver = true;
stopThreads();
stopBackgroundMusic();
removeKeyListener(playerKeyListener);
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent event) {
super.keyPressed(event);
if (event.getKeyCode() == KeyEvent.VK_ENTER) {
azaraka.restart();
}
}
});
try {
gameOverMusic.setVolume(volume);
gameOverMusic.play();
}
catch (SoundException e) {
logger.warning(e.getMessage());
}
}
@ -543,8 +529,19 @@ public class Canvas extends java.awt.Canvas implements Constants {
* Called when the game is won
*/
public void win() {
won = true;
stopThreads();
stopBackgroundMusic();
removeKeyListener(playerKeyListener);
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent event) {
super.keyPressed(event);
if (event.getKeyCode() == KeyEvent.VK_ENTER) {
System.exit(0);
}
}
});
try {
successSound.setVolume(volume);
@ -553,8 +550,6 @@ public class Canvas extends java.awt.Canvas implements Constants {
catch (SoundException e) {
logger.warning(e.getMessage());
}
won = true;
}
/**
@ -619,4 +614,31 @@ public class Canvas extends java.awt.Canvas implements Constants {
public int getTopMargin() {
return topMargin;
}
/**
* Check if the game has ended or not
*
* @return Returns true if the game is still playing or false if game is over
*/
public boolean getGameStatus() {
return (!won && !gameOver);
}
/**
* Get a game over key listener to use
*
* @return Returns a key listener
*/
private KeyListener getPlayerKeyListener() {
return new KeyAdapter() {
@Override
public void keyPressed(KeyEvent event) {
super.keyPressed(event);
if (!gameOver) {
player.keyPressed(event);
repaint();
}
}
};
}
}

26
src/main/java/cl/cromer/azaraka/Constants.java

@ -37,7 +37,11 @@ public interface Constants {
/**
* Whether or not the player should be controlled by AI
*/
boolean PLAYER_AI = true;
boolean PLAYER_AI = false;
/**
* Whether or not the enemies should be controlled by AI
*/
boolean ENEMY_AI = true;
/**
* Make logs
*/
@ -65,7 +69,7 @@ public interface Constants {
/**
* The amount of chests to draw, if less then 2 the game cannot be won
*/
int CHESTS = 4;
int CHESTS = 2;
/**
* The amount of enemies to draw
*/
@ -73,7 +77,7 @@ public interface Constants {
/**
* The amount of obstacles to draw on the screen
*/
int OBSTACLES = (int) Math.floor((double) (HORIZONTAL_CELLS * VERTICAL_CELLS) * 0.10);
int OBSTACLES = (int) Math.floor((double) (HORIZONTAL_CELLS * VERTICAL_CELLS) * 0.05);
/**
* The default volume between 0 and 100
*/
@ -195,17 +199,17 @@ public interface Constants {
*/
MAIN(Level.INFO),
/**
* The ventana principal log level
* The main window log level
*/
VENTANA_PRINCIPAL(Level.INFO),
MAIN_WINDOW(Level.INFO),
/**
* The lienzo log level
* The canvas log level
*/
LIENZO(Level.INFO),
CANVAS(Level.INFO),
/**
* The escenario log level
*/
ESCENARIO(Level.INFO),
SCENE(Level.INFO),
/**
* The player log level
*/
@ -221,15 +225,15 @@ public interface Constants {
/**
* The sound log level
*/
SOUND(Level.INFO),
SOUND(Level.WARNING),
/**
* The animation log level
*/
ANIMATION(Level.INFO),
ANIMATION(Level.WARNING),
/**
* The sheet log level
*/
SHEET(Level.INFO),
SHEET(Level.WARNING),
/**
* The key log level
*/

2
src/main/java/cl/cromer/azaraka/MainWindow.java

@ -35,7 +35,7 @@ public class MainWindow extends JFrame implements Constants {
* @param azaraka The main game class
*/
public MainWindow(Azaraka azaraka) {
Logger logger = getLogger(this.getClass(), LogLevel.VENTANA_PRINCIPAL);
Logger logger = getLogger(this.getClass(), LogLevel.MAIN_WINDOW);
logger.info("Create panels");

39
src/main/java/cl/cromer/azaraka/Scene.java

@ -15,6 +15,7 @@
package cl.cromer.azaraka;
import cl.cromer.azaraka.ai.EnemyAI;
import cl.cromer.azaraka.ai.PlayerAI;
import cl.cromer.azaraka.ai.State;
import cl.cromer.azaraka.json.Json;
@ -80,7 +81,7 @@ public class Scene extends JComponent implements Constants {
* @param canvas The canvas that this scene is in
*/
public Scene(Canvas canvas) {
logger = getLogger(this.getClass(), LogLevel.ESCENARIO);
logger = getLogger(this.getClass(), LogLevel.SCENE);
this.canvas = canvas;
loadTextures();
@ -185,7 +186,7 @@ public class Scene extends JComponent implements Constants {
}
}
final Lock lock = new ReentrantLock(true);
final Lock lock = new ReentrantLock(false);
for (int i = 0; i < ENEMIES; i++) {
random = randomCoordinates();
cells[random[0]][random[1]].setObject(new Enemy(this, cells[random[0]][random[1]], lock));
@ -219,17 +220,23 @@ public class Scene extends JComponent implements Constants {
}
for (Object object : objectArrayList) {
int x = object.getCell().getX();
int y = object.getCell().getY();
if (object instanceof Chest) {
int x = object.getCell().getX();
int y = object.getCell().getY();
if (pathInvalid(x, y + 1)) {
// Chest is unreachable
return null;
}
}
else if (object instanceof Portal || object instanceof Key) {
int x = object.getCell().getX();
int y = object.getCell().getY();
if (pathInvalid(x, y)) {
// Portal or key is unreachable
return null;
}
}
else if (object instanceof Enemy) {
if (enemyPathInvalid(x, y)) {
// Enemy can't reach player
return null;
}
}
@ -246,10 +253,24 @@ public class Scene extends JComponent implements Constants {
* @return Returns true if valid or false otherwise
*/
private boolean pathInvalid(int x, int y) {
PlayerAI breadthFirstSearch = new PlayerAI(this, null);
State playerState = new State(2, 1, State.Type.START, null, 0);
PlayerAI playerAI = new PlayerAI(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 !breadthFirstSearch.search(playerState, objectiveState);
return !playerAI.search(playerState, objectiveState);
}
/**
* Check if the path to the player is valid
*
* @param x The x coordinate of the enemy
* @param y The y coordinate of the enemy
* @return Returns true if valid or false otherwise
*/
private boolean enemyPathInvalid(int x, int y) {
EnemyAI enemyAI = new EnemyAI(this, null);
State playerState = new State(2, 1, State.Type.PLAYER, null, 0);
State enemyState = new State(x, y, State.Type.ENEMY, null, 0);
return !enemyAI.search(enemyState, playerState);
}
/**

82
src/main/java/cl/cromer/azaraka/ai/AI.java

@ -1,82 +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.logging.Logger;
/**
* AI algorithms extends this class
*/
public class AI implements Runnable {
/**
* The logger
*/
private Logger logger;
/**
* Whether or not the run loop of the AI is active
*/
private boolean active;
/**
* Initialize the AI
*/
protected AI() {
}
/**
* 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;
}
/**
* The run method
*/
@Override
public void run() {
setActive(true);
}
}

144
src/main/java/cl/cromer/azaraka/ai/BreadthFirstSearch.java

@ -21,31 +21,15 @@ import java.util.ArrayList;
/**
* This is an implementation of the Breadth-First search algorithm with multiple objectives
*/
public class BreadthFirstSearch extends AI {
/**
* 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<>();
public class BreadthFirstSearch extends SearchAI {
/**
* The steps to get to the objective
*/
private final ArrayList<State.Type> steps = new ArrayList<>();
/**
* The destinations the player should visit
* The destinations to visit
*/
private final ArrayList<State> destinations = new ArrayList<>();
/**
* The state of the search objective
*/
private State searchObjective;
/**
* If the search was successful or not
*/
private boolean success = false;
/**
* The subInitial point to start searching from
*/
@ -57,119 +41,13 @@ public class BreadthFirstSearch extends AI {
protected BreadthFirstSearch() {
}
/**
* Find a path to the objective
*
* @param searchInitial The start point
* @param searchObjective The objective
* @return Returns true if a path was found or false otherwise
*/
public boolean search(State searchInitial, State searchObjective) {
queuedStates.add(searchInitial);
history.add(searchInitial);
this.searchObjective = searchObjective;
success = searchInitial.equals(searchObjective);
while (!queuedStates.isEmpty() && !success) {
State temp = queuedStates.get(0);
queuedStates.remove(0);
moveUp(temp);
moveDown(temp);
moveLeft(temp);
moveRight(temp);
}
if (success) {
getLogger().info("Route to objective found!");
calculateRoute();
return true;
}
else {
getLogger().info("Route to objective not found!");
return false;
}
}
/**
* 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;
}
}
}
/**
* Calculate the route to the object
*/
private void calculateRoute() {
@Override
protected void calculateRoute() {
getLogger().info("Calculate the route!");
State predecessor = searchObjective;
State predecessor = getSearchObjective();
do {
steps.add(0, predecessor.getOperation());
predecessor = predecessor.getPredecessor();
@ -275,6 +153,8 @@ public class BreadthFirstSearch extends AI {
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
*/
@ -283,14 +163,14 @@ public class BreadthFirstSearch extends AI {
super.run();
while (getActive()) {
try {
Thread.sleep(500);
Thread.sleep(400);
}
catch (InterruptedException e) {
getLogger().info(e.getMessage());
}
synchronized (this) {
queuedStates.clear();
history.clear();
getQueuedStates().clear();
getHistory().clear();
steps.clear();
State objective;
@ -328,8 +208,8 @@ public class BreadthFirstSearch extends AI {
}
else {
if (!found) {
queuedStates.clear();
history.clear();
getQueuedStates().clear();
getHistory().clear();
steps.clear();
// Don't run this because the destination might return to be available again at some point
//destinationArrived(subObjective);

151
src/main/java/cl/cromer/azaraka/ai/DepthFirstSearch.java

@ -0,0 +1,151 @@
/*
* 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());
}
}
}
}
}

151
src/main/java/cl/cromer/azaraka/ai/EnemyAI.java

@ -0,0 +1,151 @@
/*
* 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.Object;
import cl.cromer.azaraka.object.Player;
/**
* This class handles player based interactions mixed with AI
*/
public class EnemyAI extends DepthFirstSearch implements Constants {
/**
* The player
*/
private final Enemy enemy;
/**
* The scene the AI is in
*/
private final Scene scene;
/**
* Initialize the algorithm
*
* @param scene The scene the AI is in
* @param enemy The player controlled by the AI
*/
public EnemyAI(Scene scene, Enemy enemy) {
super();
setLogger(getLogger(this.getClass(), LogLevel.AI));
this.scene = scene;
this.enemy = enemy;
}
/**
* Handle actions based on the states
*/
@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;
}
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));
}
}

26
src/main/java/cl/cromer/azaraka/ai/PlayerAI.java

@ -56,7 +56,6 @@ public class PlayerAI extends BreadthFirstSearch implements Constants {
*/
@Override
public boolean destinationArrived(State objective) {
sortDestinations();
switch (objective.getOperation()) {
case CHEST:
if (player.hasKey()) {
@ -67,6 +66,7 @@ public class PlayerAI extends BreadthFirstSearch implements Constants {
Portal portal = scene.getCanvas().getPortal();
if (portal.getState() == Portal.State.ACTIVE) {
addDestination(new State(portal.getCell().getX(), portal.getCell().getY(), State.Type.PORTAL, null, 2));
sortDestinations();
}
return true;
}
@ -78,10 +78,12 @@ public class PlayerAI extends BreadthFirstSearch implements Constants {
return true;
case PORTAL:
if (player.hasTaintedGem() && scene.getCanvas().getPortal().getState() == Portal.State.ACTIVE) {
sortDestinations();
return true;
}
break;
}
sortDestinations();
return false;
}
@ -147,6 +149,11 @@ public class PlayerAI extends BreadthFirstSearch implements Constants {
scene.getCanvas().repaint();
}
/**
* Move up
*
* @param state The previous state
*/
@Override
public void moveUp(State state) {
if (state.getY() > 0) {
@ -156,6 +163,11 @@ public class PlayerAI extends BreadthFirstSearch implements Constants {
}
}
/**
* Move down
*
* @param state The previous state
*/
@Override
public void moveDown(State state) {
if (state.getY() < VERTICAL_CELLS - 1) {
@ -165,6 +177,11 @@ public class PlayerAI extends BreadthFirstSearch implements Constants {
}
}
/**
* Move left
*
* @param state The previous state
*/
@Override
public void moveLeft(State state) {
if (state.getX() > 0) {
@ -174,6 +191,11 @@ public class PlayerAI extends BreadthFirstSearch implements Constants {
}
}
/**
* Move right
*
* @param state The previous state
*/
@Override
public void moveRight(State state) {
if (state.getX() < HORIZONTAL_CELLS - 1) {
@ -188,6 +210,6 @@ public class PlayerAI extends BreadthFirstSearch implements Constants {
*/
@Override
public void getNewInitial() {
setInitial(new State(player.getCell().getX(), player.getCell().getY(), State.Type.START, null, 0));
setInitial(new State(player.getCell().getX(), player.getCell().getY(), State.Type.PLAYER, null, 0));
}
}

257
src/main/java/cl/cromer/azaraka/ai/SearchAI.java

@ -0,0 +1,257 @@
/*
* 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());