Related
Note: the code below now reflects a working solution to the problem, I figured out the error.
I am trying to solve the simple problem of seeing if two nodes are connected. There are many solutions available that use a stack, and I can find much DFS code that is recursive, but non that use recursion and actually search for something and return true/ false. Any help would be appreciated. Thanks!
public static boolean routeBetween(int[][] graph, int startNode, int targetNode){
//where we can keep track of the visited vertices
int numberOfVertices = graph[0].length;
boolean[] visited = new boolean[numberOfVerticies];
//set all verticies to not visited
for(int i=0; i<visited.length; i++){
visited[i] = false;
}
return dfs(graph, visited, startNode, targetNode);
}
//where the actual dfs / recursion will happen, need this to keep track of
//visited
public static boolean dfs(int[][] graph, boolean[] visited, int startNode, int targetNode){
if(startNode == targetNode){
return true;
}
boolean foundNode = false;
if(!visited[startNode]){
visited[startNode] = true;
for(int i=0; i<graph[startNode].length;i++){
if(graph[startNode][i] ==1){
boolean currentChild = dfs(graph, visited, i, targetNode);
foundNode = currentChild || foundNode;
}
}
}
return foundNode;
}
Here is some code that I was using to test the above code:
int [][] matrix = {
{0, 1, 0, 0, 1, 1, 0, 0},
{1, 0, 0, 0, 0, 1, 1, 0},
{0, 0, 0, 1, 0, 0, 1, 0},
{0, 0, 1, 0, 0, 0, 0, 1},
{1, 0, 0, 0, 0, 1, 0, 0},
{1, 1, 0, 0, 1, 0, 0, 0},
{0, 1, 1, 0, 0, 0, 0, 1},
{0, 0, 0, 1, 0, 0, 1, 0}
};
System.out.println(GraphTools.routeBetween(matrix,0,1));
System.out.println(GraphTools.routeBetween(matrix,0,2));
I know that you have already figured out your issue, but sometimes it's worthwhile to see things worked out differently.
Since you are already keeping track of all the nodes that you visit in a boolean array, much of the work you do in your dfs method turns out to be redundant.
Another way to do it is as follows:
public static boolean dfs2(int[][] graph, boolean[] visited, int startNode, int targetNode) {
// if you have not visited the current node or the target node
// then visit this node and recursively explore its unvisited
//neighbors
if (!visited[startNode] && !visited[targetNode]) {
// visit the start node
visited[startNode] = true;
for (int i = 0; i < graph[startNode].length; i++) {
if (graph[startNode][i] == 1) {
return dfs(graph, visited, i, targetNode);
}
}
}
// otherwise we just return whether or not we have visited the
// target node and continue... If we have visited the target node
//we never go into the if-statement and we always return true
return visited[targetNode];
}
Your way is perfectly fine, I just wanted to offer an alternative solution. Hope this is helpful.
Quick question about Java 2D arrays; For my tile-based, top-down, 2D game (using swing) I use
a 2D array to create a map, like this
public int[][] createMap(){
return new int[][]{
{0, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0}};
}
I then use this in my gameComponents class where I draw the individual tiles unto the map, like this
protected void paintComponent(Graphics g){
super.paintComponent(g);
for (int row = 0; row < game.getMap().getWidth(); row++) {
for (int col = 0; col < game.getMap().getHeight(); col++) {
g.drawImage(tile.getTileImage().get(values()[game.getMap().getMapArray()[col][row]]), row * SIZE,
col * SIZE, this);
}
} }
(where size is the size of a tile)
This works, and it correctly draws each tile to the map as expected, however
this also causes a problem for collision detection. As you may have noted, while I do define the size between the tiles in draw method, it is not defined in the array at all. Which, as you'd imagine, raises issues when checking for collision as the drawn tile is not where the tile is in the 2D array (due to size offset).
This is the code I use for checking collision (of course, not working due to ArrayIndexOutofbounds).
public boolean collisionDetected(int xDirection, int yDirection, Game game, Player player){
for (int row = 0; row < game.getMap().getHeight() * 16; row ++){
for (int col = 0; col < game.getMap().getWidth() * 16; col++) {
System.out.println(col + xDirection + player.getPositionX());
if(game.getMap().getTile(col + xDirection + player.getPositionX() ,
row + yDirection + player.getPositionY()) == Tiles.GRASS ){
System.out.println("COLLISION DETECTED");
return true;
}
}
}
return false;
}
This method uses a method within the map class that returns the tile on that
specific coordinate, like this
public Tiles getTile(int col,int row){
return Tiles.values()[mapArray[col][row]];
}
And, of course, as the 2D array doesn't know of the size offset, it just throws
an arrayindexoutofbound.
My question is, is it possible to define a 2D map array with the size of a tile in-mind? I appreciate any help & input I can get, after-all I am here to learn!
Extra clarification: All the tiles are in an enum class (i.e AIR, GRASS, STONE...). Also worth noting that the player position is not bound by an array, I merely move it the amount of pixels I want it to move.
Thanks in advance!
This method uses a method within the map class that returns the tile on that specific coordinate, like this
public Tiles getTile(int col,int row){
return Tiles.values()[mapArray[col][row]];
}
So if you have a "coordinate", why do you call the parameters col/row?
If you have a 10x10 grid and each tile is 20 pixels then the grid size is 200x200 so you could have x/y values in the range 0-199
So if you have a coordinate of 25x35 you would simply calculate the row/col values as:
int row = 35 / 20;
int column = 25 / 20;
So your method would be something like :
public Tiles getTile(int x, int y)
{
int row = y / 20;
int column = x / 20;
return Tiles.values()[mapArray[row][column]];
}
I've been trying to implement an A* algorithm in a tower defense style game and after hours of trying I thought I'd ask for some insight in my logic flaws.
I've been trying to create it via http://web.mit.edu/eranki/www/tutorials/search/ & https://stackoverflow.com/a/5602061/1550619
But and infinite problem occurs when trying to generate the successors/neighbors to an AStarNode(I think) - First time implementing A* and still learning.
private ArrayList<AStarNode> aStaring(Object o, AStarNode start, AStarNode goal) {
ArrayList<AStarNode> closed = new ArrayList();
ArrayList<AStarNode> open = new ArrayList();
start.g = 0;
start.h = estimateDistance(start, goal);
start.f = 0;
open.add(start);
while(!open.isEmpty()){
AStarNode q = null;
for(AStarNode asn : open){
if(q == null || asn.f < q.f){
q = asn;
}
}
open.remove(q);
closed.add(q);
for(AStarNode succesor : q.generateSuccesors()){
if(closed.contains(succesor)){
System.out.println("Closed contained succesor");
//TODO Check if walkable
}else{
if(!open.contains(succesor)){
succesor.g = q.g+1;
succesor.h = estimateDistance(succesor, goal);
succesor.f = succesor.g + succesor.h;
succesor.parent = q;
open.add(succesor);
}else{
float nextG = q.g + succesor.cost;
if(nextG < succesor.g){
open.remove(succesor);
closed.add(succesor);
}
}
if(succesor.x == goal.x && succesor.y == goal.y){ //path found
System.out.println("hurray");
return reconstructPath(succesor);
}
}
}
}
return null;
}
public class AStarNode {
private MapDimension md = new MapDimension();
public AStarNode parent;
public int x,y;
public int f,g,h;
public int cost = 1;
public AStarNode(int x, int y){
this.x = x;
this.y = y;
}
//Looking up 4 neighbors and adding to node;
public ArrayList<AStarNode> generateSuccesors(){
ArrayList<AStarNode> neighbors = new ArrayList<>();
if(x+1 < md.getWidth()){
AStarNode temp = new AStarNode(x+1,y);
temp.parent = this;
neighbors.add(temp);
}
if(x-1 > 0){
AStarNode temp = new AStarNode(x-1,y);
temp.parent = this;
neighbors.add(temp);
}
if(y+1 < md.getHeight()){
AStarNode temp = new AStarNode(x,y+1);
temp.parent = this;
neighbors.add(temp);
}
if(y-1 > 0){
AStarNode temp = new AStarNode(x,y-1);
temp.parent = this;
neighbors.add(temp);
}
return neighbors;
}
}
Map:
public static final int[][] MAP = {
{1, 1, 1, 1, 2, 2},
{1, 1, 1, 0, 0, 2},
{2, 0, 1, 0, 0, 0},
{2, 0, 1, 0, 1, 1},
{2, 2, 1, 1, 1, 1},
{2, 2, 0, 0, 0, 1},
{2, 1, 1, 1, 1, 1},
{0, 1, 0, 0, 2, 2},
{2, 1, 0, 2, 2, 2},
{0, 1, 0, 0, 2, 2},
};
Any pointers towards the right direction would be fantastic :]
Everytime you run generateSuccessors, you create 4 (or less) NEW instances of AStarNode objects. This is not a problem per se, but AStarNode does not define hashCode and equals. So two nodes with the same coordinates are not considered equals, so closed.contains(successor) will NEVER return true.
Implement hashCode and equals on AStarNode (or get your IDE to do it for you). Something as simple as:
public int hashCode(){
return x*y;
}
public boolean equals(Object o){
if (o instanceof AStarNode){
return x==((AStarNode)o).x && y==((AStarNode)o).y;
}
return false;
}
I apologize for the somewhat vague title, I'm unsure what you would call this puzzle.
I'm making a path finding method to find the route with the least moves, not the distance traveled.
The rules of the game are simple, you must traverse from the orange square to the green square, but you can only move in a straight line, and cannot stop moving in that direction until you hit a boundary (either the wall of the arena or an obstacle), as if they were sliding across ice.
Example map, and unless I'm mistaken, the desired path (8 moves)
Arena.java: https://gist.github.com/CalebWhiting/3a6680d40610829b1b6d
ArenaTest.java: https://gist.github.com/CalebWhiting/9a4767508831ea5dc0da
I'm assuming this would be best handled with a Dijkstras or A* path finding algorithm, however I'm not only not very experienced with these algorithms, but also don't know how I would go about defining the path rules.
Thank you for any help in advance.
Here's my solution (Java) in case someone is still interested. As #tobias_k suggested in his comment above, indeed BFS is the way to go:
import java.util.LinkedList;
public class PokemonIceCave {
public static void main(String[] args) {
int[][] iceCave1 = {
{0, 0, 0, 1, 0},
{0, 0, 0, 0, 1},
{0, 1, 1, 0, 0},
{0, 1, 0, 0, 1},
{0, 0, 0, 1, 0}
};
System.out.println(solve(iceCave1, 0, 0, 2, 4));
System.out.println();
int[][] iceCave2 = {
{0, 0, 0, 1, 0},
{0, 0, 0, 0, 1},
{0, 1, 1, 0, 0},
{0, 1, 0, 0, 1},
{0, 0, 0, 1, 0},
{0, 0, 0, 0, 0}
};
System.out.println(solve(iceCave2, 0, 0, 2, 5));
}
public static int solve(int[][] iceCave, int startX, int startY, int endX, int endY) {
Point startPoint = new Point(startX, startY);
LinkedList<Point> queue = new LinkedList<>();
Point[][] iceCaveColors = new Point[iceCave.length][iceCave[0].length];
queue.addLast(new Point(0, 0));
iceCaveColors[startY][startX] = startPoint;
while (queue.size() != 0) {
Point currPos = queue.pollFirst();
System.out.println(currPos);
// traverse adjacent nodes while sliding on the ice
for (Direction dir : Direction.values()) {
Point nextPos = move(iceCave, iceCaveColors, currPos, dir);
System.out.println("\t" + nextPos);
if (nextPos != null) {
queue.addLast(nextPos);
iceCaveColors[nextPos.getY()][nextPos.getX()] = new Point(currPos.getX(), currPos.getY());
if (nextPos.getY() == endY && nextPos.getX() == endX) {
// we found the end point
Point tmp = currPos; // if we start from nextPos we will count one too many edges
int count = 0;
while (tmp != startPoint) {
count++;
tmp = iceCaveColors[tmp.getY()][tmp.getX()];
}
return count;
}
}
}
System.out.println();
}
return -1;
}
public static Point move(int[][] iceCave, Point[][] iceCaveColors, Point currPos, Direction dir) {
int x = currPos.getX();
int y = currPos.getY();
int diffX = (dir == Direction.LEFT ? -1 : (dir == Direction.RIGHT ? 1 : 0));
int diffY = (dir == Direction.UP ? -1 : (dir == Direction.DOWN ? 1 : 0));
int i = 1;
while (x + i * diffX >= 0
&& x + i * diffX < iceCave[0].length
&& y + i * diffY >= 0
&& y + i * diffY < iceCave.length
&& iceCave[y + i * diffY][x + i * diffX] != 1) {
i++;
}
i--; // reverse the last step
if (iceCaveColors[y + i * diffY][x + i * diffX] != null) {
// we've already seen this point
return null;
}
return new Point(x + i * diffX, y + i * diffY);
}
public static class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
#Override
public String toString() {
return "Point{" +
"x=" + x +
", y=" + y +
'}';
}
}
public enum Direction {
LEFT,
RIGHT,
UP,
DOWN
}
}
I think the best solution would probably be the BFS, where you represent the state of the board with a "State" object with the following parameters: number of moves made so far, and coordinates. It should also have a method to find the next states attainable (which should be fairly easy to code, just go N, S, E, W and return an array of the first blocking spots).
Create initial state (0 moves with initial coordinates)
Put in a priority queue (sorting by number moves)
while(priority queue has more states):
Remove node
if it is a goal state:
return the state
Find all neighbors of current state
Add them to priority queue (remembering to increment number of moves by 1)
This uses an implicit graph representation. Optimality is guaranteed because of the priority queue; when the goal state is found, it will have been reached with the fewest moves. If the whole priority queue is exhausted and no state is returned, then no solution exists. This solution takes O(V^2logV) time because of the priority queue, but I think this is the simplest to code. A straight up O(V) BFS solution is possible but you'll have to keep track of what states you have or have not visited yet and the fewest number of moves to reach them, which would take O(V) memory.
I am making a small class for a little project. It's a text based RPG game and I am trying to create a drop class for when NPC's die. I have create a couple Math.random methods (which are exactly the same, just differently named for my convenience.) to drop random amounts for an item id (name) and to get the rarity of the item dropped. It all works fine, but it only randomizes one time (on startup or run) and it won't randomize the amounts after that. I am also randomizing it between 2 numbers, for example, 25 and 50, the random not going lower then 25 or higher then 50.
My question is: How can I randomize a integer in a 2D Array or a general array after each time a NPC dies, so the random number that is first obtained changes and doesn't stay the same. Because right now, it stays at the number choose. if the number is 25, then the next npc I kill, the amount would still be 25.. and 25.. and 25.. and so on. I need it to randomize or change.
Please help, thank you.
public class DropConfig {
private static final int
ALWAYS = 0,
VERY_COMMON = rate(1, 9),
COMMON = rate(10, 20),
UNCOMMON = rate(30, 40),
RARE = rate(50, 60),
VERY_RARE = rate(70, 80),
SUPER_RARE = rate(90, 100);
public static final int[][] NPC_DROPS = {
// Normal NPC's
{1, 526, 1, ALWAYS},
{2, 526, 1, ALWAYS},
{3, 526, 1, ALWAYS},
{1, 995, drop(1, 50), ALWAYS},
{2, 995, drop(1, 50), ALWAYS},
{3, 995, drop(1, 50), ALWAYS},
// Moderate NPC's
{9, 526, 1, ALWAYS},
{9, 995, drop(250, 500), UNCOMMON},
{9, 555, drop(2, 7), VERY_COMMON},
{9, 995, drop(5, 50), VERY_COMMON},
{9, 1050, 1, RARE},
};
public static int rate(int min, int max) {
return 1 + (int)(Math.random() * ((max - min) + 1));
}
//Same as rate, different name for looks.
public static int drop(int min, int max) {
return 1 + (int)(Math.random() * ((max - min) + 1));
}
Heres where I call the drops method
public void npcDeath() {
int npc = 0;
if (npc == null)
return;
for(npc = 0; npc < DropConfig.NPC_DROPS.length; npc++) {
if(npc == DropConfig.NPC_DROPS[npc][0]) {
if(Misc.random(DropConfig.NPC_DROPS[npc][3]) == 0) { //Drops ALWAYS item
Item(DropConfig.NPC_DROPS[npc][1], DropConfig.NPC_DROPS[npc][2]);
}
}
}
}
If I understand correctly, you would like the elements of the NPC_DROPS array initialized with a call to drop() to be reinitialized each time this NPC_DROPS array is used.
Well, NPC_DROPS is a constant, so it can't change. Generate it each time it's accessed, using a method:
public static int[][] generateNpcDrops(){
return new int[][] {
// Normal NPC's
{1, 526, 1, ALWAYS},
{2, 526, 1, ALWAYS},
{3, 526, 1, ALWAYS},
{1, 995, drop(1, 50), ALWAYS},
{2, 995, drop(1, 50), ALWAYS},
{3, 995, drop(1, 50), ALWAYS},
// Moderate NPC's
{9, 526, 1, ALWAYS},
{9, 995, drop(250, 500), UNCOMMON},
{9, 555, drop(2, 7), VERY_COMMON},
{9, 995, drop(5, 50), VERY_COMMON},
{9, 1050, 1, RARE},
}
}
...
public void npcDeath() {
int npc = 0;
if (npc == null)
return;
int[][] npcDrops = DropConfig.generateNpcDrops();
for(npc = 0; npc < npcDrops.length; npc++) {
if(npc == npcDrops[npc][0]) {
if(Misc.random(npcDrops[npc][3]) == 0) { //Drops ALWAYS item
Item(c, npcDrops[npc][1], npcDrops[npc][2]);
}
}
}
}
You want to place functions as constants. You can do this in a language like Scala naturally, but in Java you have to work a little harder.
In every case, you need to call a function to get the actual value.
You can use enum and anonymous methods, but the simplest way/hack is to encode your ranges.
public static int rate(int min, int max) { // same for drop.
int range = max - min;
return (range << 16) | (min & 0xFFFF);
}
public static int eval(int minMax) {
int min = (short) minMax;
int range = (short) (minMax >> 16);
if (range == 0)
return min; // plain number.
else
return min + (int) (Math.random() * (range + 1));
}
You need to call eval() to turn your encoded range into a random number.
Creating an instance of Random with the same seed you will get the same 'random' number. Have you considered using SecureRandom? The difference between SecureRandom and Random is that SecureRandom produces non-deterministic output on each call.