A* algorithm current node spreading outwards instead of one direction - java

The yellow circle indicates the starting node and the red circle is indicating the goal node. I can't understand why my current node is spreading outwards instead of the image below where the node is just going straight into the goal.
I'm currently following this guide Link
I just can't get this part into my head on how should I choose a better path using G cost. It says that a lower G cost means a better path. but what node should I compare to that lower G cost?
If it is on the open list already, check to see if this path to that square is better, using G cost as the measure. A lower G cost means that this is a better path. If so, change the parent of the square to the current square, and recalculate the G and F scores of the square.
My desired output should be like this.
public class AStar {
private List<Node> open = new ArrayList<Node>();
private List<Node> close = new ArrayList<Node>();
private Node[][] nodes;
private GIS gis;
private MapListener mapListener;
private Arrow arrow;
public AStar(GIS gis) {
this.gis = gis;
mapListener = new MapListener(this);
createMapNodes();
}
private void createMapNodes() {
nodes = new Node[gis.getUslMap().getTileWidth()][gis.getUslMap().getTileHeight()];
for (int x = 0; x < gis.getUslMap().getTileWidth(); x++) {
for (int y = 0; y < gis.getUslMap().getTileHeight(); y++) {
TiledMapTileLayer.Cell cell = gis.getUslMap().getPathLayer().getCell(x, y);
arrow = new Arrow();
nodes[x][y] = new Node(cell, arrow, x, y);
if (cell != null) {
nodes[x][y].setBounds(x * Map.TILE.getSize(), y * Map.TILE.getSize(), Map.TILE.getSize(), Map.TILE.getSize());
nodes[x][y].getLabel().setBounds(x * Map.TILE.getSize(), y * Map.TILE.getSize(), Map.TILE.getSize(), Map.TILE.getSize());
nodes[x][y].getArrow().getImage().setBounds(x * Map.TILE.getSize(), y * Map.TILE.getSize(), Map.TILE.getSize(), Map.TILE.getSize());
mapListener = new MapListener(this);
nodes[x][y].addListener(mapListener);
gis.getUslMap().getStage().getActors().add(nodes[x][y].getLabel());
gis.getUslMap().getStage().getActors().add(nodes[x][y].getArrow().getImage());
gis.getUslMap().getStage().addActor(nodes[x][y]);
nodes[x][y].debug();
}
}
}
}
private void clearNodes() {
for (int x = 0; x < gis.getUslMap().getTileWidth(); x++) {
for (int y = 0; y < gis.getUslMap().getTileHeight(); y++) {
nodes[x][y].gCost = 0;
nodes[x][y].hCost = 0;
nodes[x][y].fCost = 0;
nodes[x][y].getLabel().setText("");
nodes[x][y].getArrow().setDrawable("blank");
}
}
close.clear();
open.clear();
}
public void search(Vector2 start, Node goal) {
clearNodes();
Node current = nodes[(int) start.x][(int) start.y];
open.add(current);
while (!open.isEmpty()) {
current = getLowestFCost(open);
if (current == goal)
return;
open.remove(current);
close.add(current);
// Prints the Fcost.
current.getLabel().setText(current.fCost + "");
// Detect the adjacent tiles or nodes of the current node
// and calculate the G, H and F cost
for (int x = -1; x < 2; x++) {
for (int y = -1; y < 2; y++) {
int dx = current.x + x;
int dy = current.y + y;
if (isValidLocation(dx, dy)) {
if (isWalkable(x, y, nodes[dx][dy]))
continue;
if (!open.contains(nodes[dx][dy])) {
open.add(nodes[dx][dy]);
nodes[dx][dy].parent = current;
if (isDiagonal(x, y))
nodes[dx][dy].gCost = current.gCost + 14;
else
nodes[dx][dy].gCost = current.gCost + 10;
nodes[dx][dy].fCost = nodes[dx][dy].gCost + heuristic(nodes[dx][dy], goal);
} else if (open.contains(nodes[dx][dy])&&) {
}
}
}
}
}
}
private boolean isWalkable(int x, int y, Node node) {
return x == 0 && y == 0 || node.getCell() == null || close.contains(node);
}
private boolean isValidLocation(int dx, int dy) {
return dx > 0 && dx < gis.getUslMap().getTileWidth() &&
dy > 0 && dy < gis.getUslMap().getTileHeight();
}
private boolean isDiagonal(int x, int y) {
return x == -1 && y == 1 || x == 1 && y == 1 ||
x == -1 && y == -1 || y == -1 && x == 1;
}
private Node getLowestFCost(List<Node> open) {
int lowestCost = 0;
int index = 0;
for (int i = 0; i < open.size(); i++) {
if (open.get(i).fCost <= lowestCost) {
lowestCost = open.get(i).fCost;
index = i;
}
}
return open.get(index);
}
private int heuristic(Node start, Node goal) {
int dx = Math.abs(start.x - goal.x);
int dy = Math.abs(start.y - goal.y);
start.hCost = 10 * (dx + dy);
return start.hCost;
}
}
My node.class
private TiledMapTileLayer.Cell cell;
private Label label;
private Arrow arrow;
boolean diagonal;
Node parent;
int x;
int y;
int hCost;
int gCost;
int fCost;
public Node(TiledMapTileLayer.Cell cell, Arrow arrow, int x, int y) {
this.cell = cell;
this.x = x;
this.y = y;
this.arrow = arrow;
label = new Label("", Assets.getInstance().getMapAsset().getAssetSkin(), "default");
label.setPosition(this.getX(), this.getY());
}
TiledMapTileLayer.Cell getCell() {
return cell;
}
Label getLabel() {
return label;
}
public Arrow getArrow() {
return arrow;
}

I think you have a problem to get the lowestcost:
private Node getLowestFCost(List<Node> open) {
int lowestCost = 0;
int index = 0;
for (int i = 0; i < open.size(); i++) {
if (open.get(i).fCost <= lowestCost) {
lowestCost = open.get(i).fCost;
index = i;
}
}
return open.get(index);
}
you initiate lowestCost = 0 but fCost always more than 0, so this function is not really work. It makes the lowest cost obtained from initial lowestCost, not from fCost open list. Try to initiate lowestCost with big number or first value in open list.

Related

Intersection of Rectangles for Java (Freeze Tag)

**Edited still not getting the right response **
I am not quite understanding how to figure out the intersection aspect of my project. So far I have determined the top, bottom, left and right but I am not sure where to go from there.
The main driver should call to check if my moving rectangles are intersecting and if the rectangle is froze the moving one intersecting with it should unfreeze it and change its color. I understand how to unfreeze it and change the color but for whatever the reason it isn't returning the value as true when they are intersecting and I know this code is wrong. Any helpful tips are appreciated.
*CLASS CODE*
import edu.princeton.cs.introcs.StdDraw;
import java.util.Random;
import java.awt.Color;
public class MovingRectangle {
Random rnd = new Random();
private int xCoord;
private int yCoord;
private int width;
private int height;
private int xVelocity;
private int yVelocity;
private Color color;
private boolean frozen;
private int canvas;
public MovingRectangle(int x, int y, int w, int h, int xv, int yv, int canvasSize) {
canvas = canvasSize;
xCoord = x;
yCoord = y;
width = w;
height = h;
xVelocity = xv;
yVelocity = yv;
frozen = false;
int c = rnd.nextInt(5);
if (c == 0) {
color = StdDraw.MAGENTA;
}
if (c == 1) {
color = StdDraw.BLUE;
}
if (c == 2) {
color = StdDraw.CYAN;
}
if (c == 3) {
color = StdDraw.ORANGE;
}
if (c == 4) {
color = StdDraw.GREEN;
}
}
public void draw() {
StdDraw.setPenColor(color);
StdDraw.filledRectangle(xCoord, yCoord, width, height);
}
public void move() {
if (frozen == false) {
xCoord = xCoord + xVelocity;
yCoord = yCoord + yVelocity;
}
else {
xCoord +=0;
yCoord +=0;
}
if (xCoord >= canvas || xCoord < 0) {
xVelocity *= -1;
this.setRandomColor();
}
if (yCoord >= canvas || yCoord < 0) {
yVelocity *= -1;
this.setRandomColor();
}
}
public void setColor(Color c) {
StdDraw.setPenColor(color);
}
public void setRandomColor() {
int c = rnd.nextInt(5);
if (c == 0) {
color = StdDraw.MAGENTA;
}
if (c == 1) {
color = StdDraw.BLUE;
}
if (c == 2) {
color = StdDraw.CYAN;
}
if (c == 3) {
color = StdDraw.ORANGE;
}
if (c == 4) {
color = StdDraw.GREEN;
}
}
public boolean containsPoint(double x, double y) {
int bottom = yCoord - height / 2;
int top = yCoord + height / 2;
int left = xCoord - width / 2;
int right = xCoord + width / 2;
if (x > left && x < right && y > bottom && y < top) {
color = StdDraw.RED;
return true;
} else {
return false;
}
}
public boolean isFrozen() {
if (frozen) {
return true;
} else {
return false;
}
}
public void setFrozen(boolean val) {
frozen = val;
}
public boolean isIntersecting(MovingRectangle r) {
int top = xCoord + height/2;
int bottom = xCoord - height/2;
int right = yCoord + width/2;
int left = yCoord - width/2;
int rTop = r.xCoord + r.height/2;
int rBottom = r.xCoord - r.height/2;
int rRight = r.yCoord + r.width/2;
int rLeft = r.yCoord - r.width/2;
if(right <= rRight && right >= rLeft || bottom <= rBottom && bottom
>= rTop){
return true;
} else {
return false;
}
}
}
Here is my main driver as well, because I might be doing something wrong here too.
import edu.princeton.cs.introcs.StdDraw;
import java.util.Random;
public class FreezeTagDriver {
public static final int CANVAS_SIZE = 800;
public static void main(String[] args) {
StdDraw.setCanvasSize(CANVAS_SIZE, CANVAS_SIZE);
StdDraw.setXscale(0, CANVAS_SIZE);
StdDraw.setYscale(0, CANVAS_SIZE);
Random rnd = new Random();
MovingRectangle[] recs;
recs = new MovingRectangle[5];
boolean frozen = false;
for (int i = 0; i < recs.length; i++) {
int xv = rnd.nextInt(4);
int yv = rnd.nextInt(4);
int x = rnd.nextInt(400);
int y = rnd.nextInt(400);
int h = rnd.nextInt(100) + 10;
int w = rnd.nextInt(100) + 10;
recs[i] = new MovingRectangle(x, y, w, h, xv, yv, CANVAS_SIZE);
}
while (true) {
StdDraw.clear();
for (int i = 0; i < recs.length; i++) {
recs[i].draw();
recs[i].move();
}
if (StdDraw.mousePressed()) {
for (int i = 0; i < recs.length; i++) {
double x = StdDraw.mouseX();
double y = StdDraw.mouseY();
if (recs[i].containsPoint(x, y)) {
recs[i].setFrozen(true);
}
}
}
for (int i = 0; i < recs.length; i++) {
//for 0
if(recs[0].isFrozen() && recs[0].isIntersecting(recs[1])){
recs[0].setFrozen(false);
}
if(recs[0].isFrozen() && recs[0].isIntersecting(recs[2])){
recs[0].setFrozen(false);
}
if(recs[0].isFrozen() && recs[0].isIntersecting(recs[3])){
recs[0].setFrozen(false);
}
//for 1
if(recs[1].isFrozen() && recs[1].isIntersecting(recs[2])){
recs[1].setFrozen(false);
}
if(recs[1].isFrozen() && recs[1].isIntersecting(recs[3])){
recs[1].setFrozen(false);
}
if(recs[1].isFrozen() && recs[1].isIntersecting(recs[4])){
recs[1].setFrozen(false);
}
//for 2
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[0])){
recs[2].setFrozen(false);
}
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[1])){
recs[2].setFrozen(false);
}
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[3])){
recs[2].setFrozen(false);
}
if(recs[2].isFrozen() && recs[2].isIntersecting(recs[4])){
recs[2].setFrozen(false);
}
//for 3
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[0])){
recs[3].setFrozen(false);
}
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[1])){
recs[3].setFrozen(false);
}
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[2])){
recs[3].setFrozen(false);
}
if(recs[3].isFrozen() && recs[3].isIntersecting(recs[4])){
recs[3].setFrozen(false);
}
//for 4
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[0])){
recs[4].setFrozen(false);
}
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[1])){
recs[4].setFrozen(false);
}
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[3])){
recs[4].setFrozen(false);
}
if(recs[4].isFrozen() && recs[4].isIntersecting(recs[2]))
recs[4].setFrozen(false);
}
if (recs[0].isFrozen() && recs[1].isFrozen() &&
recs[2].isFrozen() && recs[3].isFrozen()
&& recs[4].isFrozen()) {
StdDraw.text(400, 400, "YOU WIN");
}
StdDraw.show(20);
}
}
}
Keep in mind you're using the OR operator here. So if right is less than rLeft, your intersector will return true. This isn't how it should work.
You need to check if right is INSIDE the rectangles bounds so to speak.
if(right <= rRight && right >= rLeft || the other checks here)
The above code checks if right is less than the rectangle's right, but also that the right is bigger than rectangle's left, which means it's somewhere in middle of the rectangle's left and right.
If this becomes too complicated you can simply use java's rectangle class, as it has the methods contains and intersects

honeycomb layout in javafx (with flowpane?)

I'm trying to make a honeycomb flow with buttons in JavaFX with so far a FlowPane
So far I got it half working by using a negative VGap on my FlowPane, but as soon as I resize it and make the 3-4 row go to 3-3-1 it obviously goes wrong
I'm trying to find a solution that will keep the honeycomb layout with variable amounts of buttons, but so far I havent had much success. So I was wondering if anyone knows a solution for this.
edit: here is the basic code I have at the moment
FlowPane root = new FlowPane();
root.setHgap(3.0); root.setVgap(-23.0);
root.setAlignment(Pos.CENTER);
Button[] array = new Button[7];
for(int i = 0; i <= 6; i++){
Button button = new Button();
button.setShape(polygon); (made a polygon in the same of a hexagon)
array[i] = button;
}
root.getChildren().addAll(array);
Predetermined columns/ rows
This is a bit more convenient than using a FlowPane to place the fields.
You can observe that using column spans you can place the Buttons in a GridPane: Every field fills 2 columns of sqrt(3/4) times the field height; the odd/even rows start at column 0/1 respectively. Every field fills 3 rows and the size of the column constraints alternate between one quarter and one half of the field height.
Example
public static GridPane createHoneyComb(int rows, int columns, double size) {
double[] points = new double[12];
for (int i = 0; i < 12; i += 2) {
double angle = Math.PI * (0.5 + i / 6d);
points[i] = Math.cos(angle);
points[i + 1] = Math.sin(angle);
}
Polygon polygon = new Polygon(points);
GridPane result = new GridPane();
RowConstraints rc1 = new RowConstraints(size / 4);
rc1.setFillHeight(true);
RowConstraints rc2 = new RowConstraints(size / 2);
rc2.setFillHeight(true);
double width = Math.sqrt(0.75) * size;
ColumnConstraints cc = new ColumnConstraints(width/2);
cc.setFillWidth(true);
for (int i = 0; i < columns; i++) {
result.getColumnConstraints().addAll(cc, cc);
}
for (int r = 0; r < rows; r++) {
result.getRowConstraints().addAll(rc1, rc2);
int offset = r % 2;
int count = columns - offset;
for (int c = 0; c < count; c++) {
Button b = new Button();
b.setPrefSize(width, size);
b.setShape(polygon);
result.add(b, 2 * c + offset, 2 * r, 2, 3);
}
}
result.getRowConstraints().add(rc1);
return result;
}
FlowPane-like behavior
Making the x position depend on the row the child is added is not a good idea in a FlowPane. Instead I recommend extending Pane and overriding layoutChildren method place the children at custom positions.
In your case the following class could be used:
public class OffsetPane extends Pane {
public interface PositionFunction {
public Point2D getNextPosition(int index, double x, double y, double width, double height);
}
private static final PositionFunction DEFAULT_FUNCTION = new PositionFunction() {
#Override
public Point2D getNextPosition(int index, double x, double y, double width, double height) {
return new Point2D(x, y);
}
};
private final ObjectProperty<PositionFunction> hPositionFunction;
private final ObjectProperty<PositionFunction> vPositionFunction;
private ObjectProperty<PositionFunction> createPosProperty(String name) {
return new SimpleObjectProperty<PositionFunction>(this, name, DEFAULT_FUNCTION) {
#Override
public void set(PositionFunction newValue) {
if (newValue == null) {
throw new IllegalArgumentException();
} else if (get() != newValue) {
super.set(newValue);
requestLayout();
}
}
};
}
public OffsetPane() {
this.hPositionFunction = createPosProperty("hPositionFunction");
this.vPositionFunction = createPosProperty("vPositionFunction");
}
#Override
protected void layoutChildren() {
super.layoutChildren();
double width = getWidth();
List<Node> children = getManagedChildren();
final int childSize = children.size();
if (childSize > 0) {
int row = 0;
Node lastRowStart = children.get(0);
Node lastNode = lastRowStart;
lastRowStart.relocate(0, 0);
PositionFunction hFunc = getHPositionFunction();
PositionFunction vFunc = getVPositionFunction();
int index = 1;
int columnIndex = 0;
while (index < childSize) {
Node child = children.get(index);
Bounds lastBounds = lastNode.getLayoutBounds();
Bounds bounds = child.getLayoutBounds();
Point2D pt = hFunc.getNextPosition(columnIndex, lastNode.getLayoutX(), lastNode.getLayoutY(), lastBounds.getWidth(), lastBounds.getHeight());
if (pt.getX() + bounds.getWidth() > width) {
// break row
lastBounds = lastRowStart.getLayoutBounds();
pt = vFunc.getNextPosition(row, lastRowStart.getLayoutX(), lastRowStart.getLayoutY(), lastBounds.getWidth(), lastBounds.getHeight());
child.relocate(pt.getX(), pt.getY());
lastRowStart = child;
row++;
columnIndex = 0;
} else {
child.relocate(pt.getX(), pt.getY());
columnIndex++;
}
lastNode = child;
index++;
}
}
}
public final PositionFunction getHPositionFunction() {
return this.hPositionFunction.get();
}
public final void setHPositionFunction(PositionFunction value) {
this.hPositionFunction.set(value);
}
public final ObjectProperty<PositionFunction> hPositionFunctionProperty() {
return this.hPositionFunction;
}
public final PositionFunction getVPositionFunction() {
return this.vPositionFunction.get();
}
public final void setVPositionFunction(PositionFunction value) {
this.vPositionFunction.set(value);
}
public final ObjectProperty<PositionFunction> vPositionFunctionProperty() {
return this.vPositionFunction;
}
}
double[] points = new double[12];
for (int i = 0; i < 12; i += 2) {
double angle = Math.PI * (0.5 + i / 6d);
points[i] = Math.cos(angle);
points[i + 1] = Math.sin(angle);
}
Polygon polygon = new Polygon(points);
OffsetPane op = new OffsetPane();
double fieldHeight = 100;
double fieldWidth = Math.sqrt(0.75) * fieldHeight;
for (int i = 0; i < 23; i++) {
Button button = new Button();
button.setShape(polygon);
button.setPrefSize(fieldWidth, fieldHeight);
op.getChildren().add(button);
}
// horizontal placement just right of the last element
op.setHPositionFunction((int index, double x, double y, double width, double height) -> new Point2D(x + width, y));
// vertical position half the size left/right depending on index and
// 1/4 the node height above the bottom of the last node
op.setVPositionFunction((int index, double x, double y, double width, double height) -> new Point2D(x + (index % 2 == 0 ? width : -width) / 2, y + height * 0.75));

Grid line collision checking

Lately I've been working on a grid line detection system, I know that there was an algorithm out there that did excactly what I wanted it to do, but I'm that kind of person who wants to make stuff themselves. ;)
So I've had some succes when checking with 1 line, but now that I use a grid of 20x20 to check the lines it doesn't work anymore.
The problem is found somewhere in the collision class I made for this system.
Somehow the numbers get out of the grid array and I don't know why
here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/**
*
* beschrijving
*
* #version 1.0 van 22-6-2016
* #author
*/
public class gridline extends JApplet {
// Begin variabelen
int[][] grid = new int[20][20];
int[] light = new int[2];
int[][] line = new int[2][2];
// Einde variabelen
public void init() {
Container cp = getContentPane();
cp.setLayout(null);
cp.setBounds(0, 0, 600, 600);
// Begin componenten
for (int a=0; a<20; a++) {
for (int b=0; b<20; b++) {
grid[a][b] = (int) (Math.random()*10);
} // end of for
} // end of for
line[0][0] = (int) (Math.random()*20);
line[0][1] = (int) (Math.random()*20);
line[1][0] = (int) (Math.random()*20);
line[1][1] = (int) (Math.random()*20);
light[0] = (int) (Math.random()*20);
light[1] = (int) (Math.random()*20);
// Einde componenten
} // end of init
//Custom classes
private boolean collide(int x1, int y1,int x2, int y2) {
boolean collide = true;
int tempx = x1 - x2;
int tempy = y1 - y2;
int sx = 0;
int sy = 0;
int x = 0;
int y = 0;
if (tempx == 0) {
tempx = 1;
sx = 1;
} // end of if
if (tempy == 0) {
tempy = 1;
sy = 1;
} // end of if
if (sx == 0) {
x = tempx + tempx/Math.abs(tempx);
} // end of if
else {
x = tempx;
} // end of if-else
if (sy == 0) {
y = tempy + tempy/Math.abs(tempy);
} // end of if
else {
y = tempy;
} // end of if-else
int absx = Math.abs(x);
int absy = Math.abs(y);
int nex = x/absx;
int ney = y/absy;
int off = 0;
float count = 0;
float step = 0;
if (absx != absy) {
if (absx == Math.min(absx,absy)) {
step = (float) absx/absy;
calc1: for (int a=0; a<absy; a++) {
count += step;
if (count > 1 && x1+off != x2) {
count -= 1;
off += nex;
} // end of if
if (grid[x1+off][y1+a*ney] == 9) {
collide = false;
break calc1;
} // end of if
} // end of for
} // end of if
else{
step = (float) absy/absx;
calc2: for (int a=0; a<absx; a++) {
count += step;
if (count > 1 && y1+off != y2) {
count -= 1;
off += ney;
} // end of if
if (grid[x1+a*nex][y1+off] == 9) {
collide = false;
break calc2;
} // end of if
} // end of for
}
} // end of if
else {
calc3: for (int a=0; a<absx; a++) {
if (grid[x1+a*nex][y1+a*ney] == 9) {
collide = false;
break calc3;
} // end of if
} // end of for
} // end of if-else
return collide;
}
private int length(int x1, int y1, int x2, int y2) {
double distance = Math.sqrt(Math.pow(x1-x2,2)+Math.pow(y1-y2,2));
return (int) distance;
}
// Begin eventmethoden
public void paint (Graphics g){
boolean draw = true;
Color col;
for (int a=0; a<20; a++) {
for (int b=0; b<20; b++) {
draw = collide(a,b,light[0],light[1]);
if (draw) {
int len = Math.max(255-length(a*30+15,b*30+15,light[0]*30+15,light[1]*30+15),0);
col = new Color(len,len,len);
g.setColor(col);
g.fillRect(a*30,b*30,30,30);
} // end of if
else{
col = new Color(0,0,0);
g.setColor(col);
g.fillRect(a*30,b*30,30,30);
}
} // end of for
} // end of for
}
// Einde eventmethoden
} // end of class gridline
I'll understand it if nobody wants to look through a code as big as this, but it could be helpful for your own projects and I'm completely okay with it if you copy and paste my code for your projects.
Many thanks in advace.

Exception in thread "AWT-EventQueue-0" java.lang.IllegalAccessError

I have a small game project where I have to use RMI to create a multiplayer game. I'm getting the following error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalAccessError: tried to
access class PlayArea from class com.sun.proxy.$Proxy1
at com.sun.proxy.$Proxy1.getPlayArea(Unknown Source)
at GameClient.getPlayArea(GameClient.java:100)
at PlayBoard.paintComponent(GUI.java:264)
Now those references are as follows:
Part of GameClient.java
public PlayArea getPlayArea() {
PlayArea result = null;
try {
result = myServer.getPlayArea(clientID); // line 100 of GameClient.java
} catch (Exception e) {
System.out.println("Error: " + e);
System.exit(1);
}
return result;
}
And this is part of GUI.java
public void paintComponent(Graphics g) {
PlayArea playArea = gui.getGameEngine().getPlayArea(); // line 264 of GUI.java
super.paintComponent(g);
LinkedList bricks = new LinkedList();
int pixCoeff = brickSize - 1;
for (int y = 0; y < bricksPerSide; y++) {
int pixY = y * pixCoeff;
for (int x = 0; x < bricksPerSide; x++) {
int brick = playArea.getBrick(x, y);
if (Colour.isBase(brick))
continue;
if (gui.displayMode == GUI.NOMARKED && Colour.isMarked(brick)) {
continue;
}
int pixX = x * pixCoeff;
bricks.add(new BoardBrick(pixX, pixY,
gui.displayMode == GUI.MARKEDASORIGINAL ? ColourMapper
.map(Colour.original(brick)) : (Colour
.isMarked(brick) ? Color.WHITE : ColourMapper
.map(brick))));
}
}
g.setColor(ColourMapper.map(Colour.BASE));
g.fillRect(0, 0, (brickSize - 1) * bricksPerSide + 1, (brickSize - 1)
* bricksPerSide + 1);
while (bricks.size() > 0) {
BoardBrick brick = (BoardBrick) (bricks.removeFirst());
brick.drawBrick(g);
}
if (gui.getGameEngine().isGameOver())
gameOver(g);
}
And this is PlayArea.java
import java.util.Random;
class PlayArea implements java.io.Serializable {
public static final int NORTHSIDE = 0;
public static final int SOUTHSIDE = 1;
public static final int EASTSIDE = 2;
public static final int WESTSIDE = 3;
private int[][] grid;
public PlayArea(int size) {
grid = new int[size][size];
}
public static int randomSide(Random rng) {
return rng.nextInt(4);
}
public int getSize() {
return grid.length;
}
public int getBrick(int x, int y) {
return grid[x][y];
}
public int getBrick(Coord c) {
return getBrick(c.getX(), c.getY());
}
public void setBrick(int x, int y, int val) {
grid[x][y] = val;
}
public void setBrick(Coord c, int val) {
setBrick(c.getX(), c.getY(), val);
}
// --> play_area_init_collision_flipDraw
public void init() {
int size = getSize();
for (int x = 0; x < size; x++)
for (int y = 0; y < size; y++)
if (x == 0 || y == 0 || x == size - 1 || y == size - 1)
setBrick(x, y, Colour.WALL);
else
setBrick(x, y, Colour.BASE);
setBrick(size / 2, size / 2, Colour.WALL);
setBrick(size / 2 - 2, size / 2 - 2, Colour.WALL);
setBrick(size / 2 - 2, size / 2 + 2, Colour.WALL);
setBrick(size / 2 + 2, size / 2 - 2, Colour.WALL);
setBrick(size / 2 + 2, size / 2 + 2, Colour.WALL);
}
public boolean collision(PlayingBlock block) {
int topLeftX = block.getPosition().getX();
int topLeftY = block.getPosition().getY();
int height = block.getHeight();
int length = block.getLength();
for (int x = 0; x < length; x++)
for (int y = 0; y < height; y++)
if (!Colour.isBase(getBrick(topLeftX + x, topLeftY + y)))
return true;
return false;
}
public void flipDraw(PlayingBlock block) {
int topLeftX = block.getPosition().getX();
int topLeftY = block.getPosition().getY();
int height = block.getHeight();
int length = block.getLength();
for (int x = 0; x < length; x++)
for (int y = 0; y < height; y++)
setBrick(topLeftX + x, topLeftY + y, getBrick(topLeftX + x,
topLeftY + y)
^ block.getColour());
}
// --<
// --> play_area_getSquareColour_mark
public int getSquareColour(int topLeftX, int topLeftY, int size) {
// return 0 if no square found
// square colour otherwise
if (topLeftX + size > getSize() || topLeftY + size > getSize())
return 0;
int colour = getBrick(topLeftX, topLeftY);
if (!Colour.isPlayBrick(colour))
return 0;
for (int x = topLeftX; x < topLeftX + size; x++)
for (int y = topLeftY; y < topLeftY + size; y++)
if (!Colour.isSameColour(colour, getBrick(x, y)))
return 0;
return colour;
}
public void mark(int topLeftX, int topLeftY, int size) {
for (int x = topLeftX; x < topLeftX + size; x++)
for (int y = topLeftY; y < topLeftY + size; y++)
setBrick(x, y, Colour.mark(getBrick(x, y)));
}
// --<
}
Now, what's weird is, this runs in Windows using Java 1.6, but on OS X it doesn't and I don't have access to a Windows machine right now. I'm using 1.6.0_65 on OS X 10.9.
I have found many errors on the web regarding AWT-EventQueue-0 but most of them are NullPointerException errors, not IllegalAccessError. I would appreciate any help, I'm quite new to Java.
UPDATE: The code most definitely works in 1.5 and 1.6. This is most likely related to the included libraries. I will keep looking and edit this post accordingly.

Bounding box doesn't work properly - /withkinect

I am trying to make a bounding box over the blue-colored pixels (from Kinect v1 camera, using Processing). Y-axis of bounding box works perfectly but x-axis is very off.
void display() {
PImage img = kinect.getDepthImage();
float maxValue = 0;
float minValue = kinect.width*kinect.height ;
float maxValueX = 0;
float maxValueY = 0;
float minValueX = kinect.width;
float minValueY = kinect.height;
// Being overly cautious here
if (depth == null || img == null) return;
display.loadPixels();
for (int x = 0; x < kinect.width; x++) { //goes through all the window
for (int y = 0; y < kinect.height; y++) {
int offset = x + y * kinect.width;
// Raw depth
int rawDepth = depth[offset];
int pix = x + y * display.width; //why is it y*width
if (rawDepth < threshold) {
// A blue color instead
display.pixels[pix] = color(0, 0, 255); //set correct pixels to blue
if(pix > maxValue){
maxValue = pix;
maxValueX = x;
maxValueY = y;
}
if(pix < minValue){
minValue = pix;
minValueX = x;
minValueY = y;
}
} else {
display.pixels[pix] = img.pixels[offset];
}
}
}
display.updatePixels();
image(display, 0, 0);
rect(minValueX, minValueY, maxValueX-minValueX, maxValueY-minValueY);
}
You have to calculate the minimum and maximum values for each index or coordinate separately. Use the min respectively max function for this:
maxValue = max(maxValue, pix);
minValue = min(minValue, pix);
maxValueX = max(maxValueX, x);
minValueX = min(minValueX, x);
maxValueY = max(maxValueY, y);
minValueY = min(minValueY, y);
or with an ifstatement:
if (pix > maxValue) { maxValue = pix; }
if (pix < minValue) { minValue = pix; }
if (x > maxValueX) { maxValueX = x; }
if (x < minValueX) { minValueX = x; }
if (y > maxValueY) { maxValueY = y; }
if (y < minValueY) { minValueY = y; }

Categories