I have an if statement that looks like this:
if (pan[x + 1][y + 1].getBackground() == TeamColor &&
pan[x + 1][y].getBackground() == TeamColor &&
pan[x + 1][y -1].getBackground() == TeamColor &&
pan[x][y - 1].getBackground() == TeamColor &&
pan[x - 1][y - 1].getBackground() == TeamColor &&
pan[x - 1][y].getBackground() == TeamColor &&
pan[x - 1][y + 1].getBackground() == TeamColor &&
pan[x][y + 1].getBackground() == TeamColor) {
// do something
}
The goal is to check every item (in a 2d array) around the current x and y values and make sure they are the correct color.
I assume there is a simple way to do such. I would assume creating a for loop would solve the problem by iterating through each item but unfortunately was not able to think of a way to do this because the items are not all in sequence.
NOTE: i found many other posts on stackoverflow that where titled "solution for very long if statement" unfortunately they were in different programing languages (such as python, android and javascript)
NOTE 2: this is Not a duplicate of this post. It was a question of strings and regex and unfortunately not the solution to my problem
Hopefully someone will have an answer!
Try something like this:
boolean match = true;
for (int dx = -1; match && (dx < 2); ++dx) {
for (int dy = -1; match && (dy < 2); ++dy) {
if (dx != 0 || dy != 0) {
match = pan[x+dx][y+dy].getBackground() == TeamColour;
}
}
}
if (match) {
// do something
}
Basically, you want to check offsets -1, 0 and 1 in each direction, so we have two for loops, each producing those offsets in one dimension. We then check the array element corresponding to each offset, and keep track using the match variable.
Note though that, like the original code, this will fail near boundaries (e.g. if x == 0). This can be fixed if necessary.
It is possible, of course, to instead have the loops run over the actual indices to check (e.g. for (int x2 = x-1; x2 < x+2; ++x)). It's much the same in the end.
for (int a = x-1;a <= x+1;a++)
{
if (a < 0 || a >= pan.length) continue;
for (int b = y-1; b <= y+1; b++)
{
if (b < 0 || b >= pan[a].length) continue;
if (a == x && b == y) continue;
if (pan[a][b].getBackground() != TeamColor)
return false;
}
}
return true;
I can propose two ways :
1) Full object way
You could introduce a custom class Coordinate that holds two values : the x and y coordinates.
Create a List of Coordinate where you had the Coordinate element you want to test and iterate on it to achieve your need.
public class Coordinate{
private final int x;
private final int y;
public Coordinate(int x, int y){
this.x = x;
this.y = y;
}
public getX(){
return x;
}
public getY(){
return y;
}
}
And you can use it :
List<Coordinate> coordinates = new ArrayList<>();
coordinates.add(new Coordinate(1,1));
coordinates.add(new Coordinate(1,0));
coordinates.add(new Coordinate(1,-1));
coordinates.add(new Coordinate(0,-1));
coordinates.add(new Coordinate(-1,-1));
coordinates.add(new Coordinate(-1,0));
coordinates.add(new Coordinate(-1,1));
coordinates.add(new Coordinate(0,1));
// you can also init them with a loop
boolean isMatched = true;
for (Coordinate coordinate : coordinates){
if (pan[x + coordinate.getX()][y + coordinate.getY()].getBackground() != TeamColor){
isMatched = false;
break;
}
}
The object way is more verbose but it has the advantage to expose rules.
So you can read and change it easily.
Suppose, the rules to check become more complex, it becomes very valuable.
2) Shorter code way
It is the same logical even by inlining values of Coordinate and by ignoring the specific case that you don't want to test (no change case).
boolean isMatched = true;
for (int xDelta = -1; xDelta <=1; xDelta++){
for (int yDelta = -1; yDelta <=1; yDelta++){
// as you don't want to test if no change
if (yDelta == 0 && xDelta ==0){
continue;
}
if (pan[x + xDelta][y + yDelta ].getBackground() != TeamColor){
isMatched = false;
break;
}
}
Related
I'm programming a little game and I'm having some problems with the intersections. I need an efficient algorithm to check if two objects (which have x and y coords. and also a width and an height) are intersecting.
I tried with the following, but it doesn't always work, sometimes it doesn't recnognize an intersection.
public boolean contains(int x, int y) {
if ((x < this.x + this.width) && (x >= this.x) && (y < this.y + this.height) && (y >= this.y))
return true;
else
return false;
}
I have an ArrayList containing the objects, and I do the following:
private boolean checkIntersection(String pDirection) {
for (int i = 0; i < walls.size(); i++) {
if (pDirection.equalsIgnoreCase("right") && car.contains(walls.get(i).getX() - 1, walls.get(i).getY()))
return true;
if (pDirection.equalsIgnoreCase("left") && car.contains(walls.get(i).getX() + 30, walls.get(i).getY()))
return true;
if (pDirection.equalsIgnoreCase("top") && car.contains(walls.get(i).getX(), walls.get(i).getY() + 30))
return true;
if (pDirection.equalsIgnoreCase("down") && car.contains(walls.get(i).getX(), walls.get(i).getY() - 1))
return true;
}
return false;
}
Note that "-1" and "+30" is to avoid the car enter the "walls", there the walls have a width of 30 and an height of 30. The car also has the same dimensions.
Also note that the x and y are the top-left cords of the rectangles. The car and the walls are rectangles.
I would be thankful for your help.
INFO: It doesn't recnognize an intersection at the beginn of a row of walls if I am above the wall and I change the direction to "down" or viceversa.
See picture
EDIT 1 (I tried inverting the objects, but it also doesn't always work):
private boolean checkIntersection(String pDirection) {
for (int i = 0; i < walls.size(); i++) {
if (pDirection.equals("right") && walls.get(i).contains(car.getX() + 30, car.getY()))
return false;
if (pDirection.equals("left") && walls.get(i).contains(car.getX() - 1, car.getY()))
return false;
if (pDirection.equals("top") && walls.get(i).contains(car.getX(), car.getY() - 1))
return false;
if (pDirection.equals("down") && walls.get(i).contains(car.getX(), car.getY() + 30))
return false;
}
return true;
}
The flaw in your algorithm is, you are always checking the left-top point of the wall whether it is in the car. However, this is not equivalent to having intersection.
Instead, you should check whether any one of the objects contains (at least) one corner (not necessarily the top left one) of the other object.
Note that you should perform this check for both sides, i.e. either the car contains any corner of the wall or the wall contains any corner of the car.
I solved modifying the contains method in the following way, and it now works perfectly:
public boolean contains(int x, int y) {
if ((x < this.x + this.width) && (x > this.x-this.width) && (y < this.y + this.height) && (y > this.y-this.height))
return true;
else
return false;
}
I think that I did it involuntarily (checking for non-intersection instead of intersection), but I can optimize it using the answer/suggestion of #samgak and #Gene. So thanks, problem solved.
I have a problem with array indexing. The code is supposed to move objects of type Ant around a 20x20 grid.
public class Test {
Organism[][] grid = new Organism[20][20];
public static void main(String[] args) {
for (int i = 0; i < 20; i++){
for (int j = 0; j < 20; j++){
if(grid[i][j] instanceof Ant){
int xpos = i;
int ypos = j;
grid[i][j].move(xpos, ypos);
grid[i][j].breed(xpos, ypos);
}
}
}
}
Class Ant extends Organism, class Organism extends Test.
public class Ant extends Organism{
public void move(int xpos, int ypos){
Random rand = new Random();
int direction = rand.nextInt(3);
if(direction == 0){
if(grid[xpos][ypos + 1] == null && xpos <20 && ypos <20)
{
grid[xpos][ypos] = grid[xpos][ypos];
grid[xpos][ypos] = null;
{
}
}
}
The method move is supposed to choose a random direction on the grid and move the Ant there if the adjoining space is empty. It also cannot go outside the 20x20 grid. (There are three more if loops for the other directions).
If I change the sixth line in the move method to:
if(grid[xpos][ypos] == null && xpos <20 && ypos <20)
Then no error is thrown.
I hesitate to post this because its probably a small error on my part but I have been staring at this for several hours.
Assistance is greatly appreciated.
The operands for an && are evaluated from left to right, and the evaluation stops if one of them evaluates to false. So if one or more of the operands are potentially dangerous (such as an array lookup that might go out of bounds), and some of the other operands are supposed to protect against this, the protection operands need to go first. Also, you need to check the indices you're actually using, namely xpos and ypos + 1, and you forgot to use ypos + 1 in the assignment that moves the ant:
if (xpos < 20 && ypos + 1 < 20 && grid[xpos][ypos + 1] == null) {
grid[xpos][ypos + 1] = grid[xpos][ypos];
grid[xpos][ypos] = null;
}
(And, assuming that xpos and ypos are valid indices, you don't need to check xpos.)
I am trying to save the method outOfBounds which is called inside the lengthOfColor method more than once to a local variable, so that less processing power is used. I provided the lengthOfColor method in which I want to store the variable, and I also provided the outOfBounds method. As you can see the outOfBounds method is a boolean and I am not sure how to store it with integer parameters.
private Integer[] lengthOfColor(int col, boolean color, int pattern, int row) {
int x = 0;
int y = 0;
if (pattern == 1) {
// vertical pattern
y = 1;
} else if (pattern == 2) {
// horizontal pattern
x = 1;
} else if (pattern == 3) {
// diagonal slope left pattern
x = 1;
y = 1;
} else {
// diagonal slope right pattern
x = 1;
y = -1;
}
// length = how many neighbor slots are of same color
// possible equals number of slots, that you can play off of.
// whichSide = left or right if horizontal and top or bottom if vertical.
int length = 0;
int possible = 0;
Integer[] whichSide = new Integer[]{1, -1};
for (int side : whichSide) {
int i = 1;
boolean complete = false;
//while complete is false continue the loop
while (!complete) {
//mainX == horizontal pattern distance
//mainY == vertical pattern distance
int mainX = x * i * side;
int mainY = y * i * side;
//if still inbounds and if the same slot is filled and it matches the color, increment length
if (!outOfBounds(col, mainX, mainY, row) && getIsFilled(col, mainX, mainY, row) &&
checkColor(col, mainX, mainY, row) == color)
{
length++;
}
//if still inbounds and if the same slot is empty, increment possible number of spots and change complete to true
else if (!outOfBounds(col, mainX, mainY, row) && !getIsFilled(col, mainX, mainY, row) &&
getLowestEmptyIndex(myGame.getColumn(col + mainX)) == getLowestEmptyIndex(myGame.getColumn(col)) + mainY - row)
{
possible++;
complete = true;
}
//finish the statement to avoid a infinite loop if neither conditions are met.
else
{
complete = true;
}
// If not complete, then check one slot further.
i = i + 1;
}
}
return new Integer[] {length, possible};
}
private boolean outOfBounds(int col, int x , int y, int row)
{
int currentX = col;
int currentY = getLowestEmptyIndex(myGame.getColumn(col)) - row;
return currentX + x >= myGame.getColumnCount() || currentY + y >= myGame.getRowCount() || currentX + x < 0 || currentY + y < 0;
}
I see that mainX and mainY change values so there isn't any real optimization that can be done outside of the for and while loop besides creating a boolean value that holds the result of outOfBounds before the if check is called which would reduce the number of operations you need to do. To be honest, the optimization is so insignificant that it wouldn't really matter but would be good coding practice I suppose (JIT might optimize for you as well depending on your code). More importantly the method reduces the extra lines of code you need to type and does not necessarily mean that there is less computing.
So something like this before any outOfBounds call but inside the while loop,
boolean outOfBounds = outOfBounds(col, mainX, mainY, row);
and change your current if(!outOfBounds(col, mainX, mainY, row) && ....) into if (!outOfBounds && ...)
Also the #1 rule to optimization is to not optimize until you are done with your project and notice a significant performance dip. In which case you would start with the biggest bottleneck until the optimal performance is gained. Of course this does not mean coding in an incorrect way which would of course create unnecessary performance losses. In those cases it would also be wise to consider whether or not you are looking at the problem the right way rather than micro-optimizing.
Here's a snippet of what I would do to micro-optimize the code shown.
private Integer[] lengthOfColor(int col, boolean color, int pattern, int row) { // consider changing Integer[] into
// int[] if you don't need a boxed integer. It will increase performance
int x = 0;
int y = 0;
// length = how many neighbor slots are of same color
// possible equals number of slots, that you can play off of.
// whichSide = left or right if horizontal and top or bottom if vertical.
int length = 0;
int possible = 0;
switch (pattern) { // switch may be a tad faster but insignificant. More importantly it provides clarity.
case 1:
y = 1;
break;
case 2:
x = 1;
break;
case 3:
x = 1;
y = 1;
break;
default:
x = 1;
y = -1;
break;
}
//int[] whichSide = new int[]{1, -1}; // changed to int[] because you don't need a boxed primitive from what is
// shown
// nevermind, this line isn't needed and you will be able to avoid an instantiation.
for (int i = 1; i != -3; i-=2) {
int count = 1;
int mainX; // bring this to a higher scope. (honestly this is micro optimization but a habit of mine if this is
// can be considered in scope)
int mainY;
boolean outOfBounds = false;
//boolean complete = false; // removed as its unnecessary to break out of the while loop.
//while complete is false continue the loop
while (true) {
//mainX == horizontal pattern distance
//mainY == vertical pattern distance
mainX = x * count * i;
mainY = y * count * i;
outOfBounds = outOfBounds(col, mainX, mainY, row);
//if still inbounds and if the same slot is filled and it matches the color, increment length
if (!outOfBounds && getIsFilled(col, mainX, mainY, row) &&
checkColor(col, mainX, mainY, row) == color) {
length++;
}
//if still inbounds and if the same slot is empty, increment possible number of spots and change complete to
// true
else if (!outOfBounds && !getIsFilled(col, mainX, mainY, row) &&
getLowestEmptyIndex(myGame.getColumn(col + mainX)) == getLowestEmptyIndex(myGame.getColumn(col)) + mainY -
row) {
possible++;
break;
}
//finish the statement to avoid a infinite loop if neither conditions are met.
else {
break;
}
// If not complete, then check one slot further.
count++;
}
}
return new Integer[]{length, possible}; // once again consider whether or not you need a boxed integer
}
private boolean outOfBounds(int col, int x, int y, int row) {
//int currentX = col; this is an unnecessary line
int currentY = getLowestEmptyIndex(myGame.getColumn(col)) - row;
return col + x >= myGame.getColumnCount() || currentY + y >= myGame.getRowCount() || col + x < 0 ||
currentY + y < 0;
}
I am making game, where I need to check if object`s coordinates meets requirements (Destination coordinates) with permitted +- difference.
Example:
int x; //current object X coordinate
int y; //current object Y coordinate
int destinationX = 50; //example X destination value
int destinationY = 0; //example Y destination value
int permittedDiference = 5;
boolean xCorrect = false;
boolean yCorrect = false;
I am trying to create algorithm, checking
if (x == destinationX + permittedDifference || x == destinationX - permittedDifference)
{
xCorrect = true;
}
if (y == destinationY + permittedDifference || y == destinationY - permittedDifference)
{
yCorrect = true;
}
It sounds like most simply way, but maybe there is better one? Will be grateful for some tips.
You can make use of Math.abs() method here. Get the absolute difference between x and destinationX, and check whether it's less than or equal to permittedDifference:
xCorrect = Math.abs(x - destinationX) <= permittedDifference;
yCorrect = Math.abs(y - destinationY) <= permittedDifference;
Here are my for() loops :
public void showMovementCase(){
int movePlusAttack = moveAllowed+attackDistance;
int twiceMoveAllowed = (moveAllowed)*2;
for(int i = 0; i <= movePlusAttack*2; i++){
for(int j = 0; j <= movePlusAttack*2;j++){
boolean a = movePlusAttack <= j+i && movePlusAttack >= j-i && i <= movePlusAttack;
boolean b = movePlusAttack <= j+i && movePlusAttack >= i-j && i > movePlusAttack && j <= movePlusAttack;
boolean c = movePlusAttack*3 >= j+i && movePlusAttack >= j-i && i > movePlusAttack && j >= movePlusAttack;
if(a || b || c){
try{
actionSquare[i][j] = new JLabel();
actionSquare[i][j].setIcon(redsquare);
actionSquare[i][j].setBounds(sprite.getX()+(i-movePlusAttack)*16,sprite.getY()+(j-movePlusAttack)*16, 16, 16);
panel.add(actionSquare[i][j], new Integer(1));
}
catch(ArrayIndexOutOfBoundsException e){System.out.println("red :" + e);}
}
}
}
for(int x = 0; x <= twiceMoveAllowed; x++){
for(int y = 0; y <= twiceMoveAllowed;y++){
boolean a = moveAllowed <= y+x && moveAllowed >= y-x && x <= moveAllowed;
boolean b = moveAllowed <= y+x && moveAllowed >= x-y && x > moveAllowed && y <= moveAllowed;
boolean c = moveAllowed*3 >= y+x && moveAllowed >= y-x && x > moveAllowed && y >= moveAllowed;
if(a || b || c){
try{
actionSquare[x][y].setIcon(bluesquare);
System.out.println("Coucou !");
actionSquare[x][y].addMouseListener(mouse);
panel.repaint();
panel.revalidate();
}
catch(ArrayIndexOutOfBoundsException e){System.out.println("blue :" + e); }
}
}
}
}
if this.attackDistance is different of 0, then the second loop doesn't work (it seems to stop at the .setIcon() command).
Do you know a way to fix this ?
Thanks for reading.
Edit:
with :
try{
actionSquare[x][y].setIcon(bluesquare);
System.out.println("Coucou !");
[...]
}
On the second loop, nothing is printed.
but with :
try{
System.out.println("Coucou !");
actionSquare[x][y].setIcon(bluesquare);
[...]
}
"Coucou !" is printed once.
That's why I said that "it seems to stop at the .setIcon() command" I should have said that sooner, sorry.
Here are a few tips:
don't catch exceptions and do nothing with them. That's what you are doing here in both loops, and so it's normal you don't see the error message.
anytime you see long statements like you have, it should be a hint that you could refactor it. For example, create a separate method that validates whether or not you're going to do something in your loop, and then inside the main method you'd call it like if(shouldPerformAction())
consider using less than 8 spaces for indentation. This just eats up your screen real estate.
consider making computations before the loops instead of inside the loop conditions, if the computation is supposed to be fixed (for example this.moveAllowed*2)
imho, no point in prefixing all your methods/fields with this, it just clutters everything. Just call the methods directly.
This is a very, very bad idea:
catch(ArrayIndexOutOfBoundsException e){}
You effectively tell the JVM to ignore any problems with your arrays that it detects. And worse than that: you don't even print anything when that happens.
Put at least a e.printStackTrace() in there to see if a problem occurs and where.
And as a further step: fix your array access to not exceed any limits. Catching an ArrayIndexOutOfBoundsException is a terribly bad idea. Avoid having it thrown at all!
Hmmm... where to begin...
I would first suggest putting something (System.err.println(...)?) inside of your catch blocks. Or just commenting them out entirely so you'd see the full stacktrace. What if you're hitting an exception and just not seeing it?
catch(ArrayIndexOutOfBoundsException e){}
This is a bad practice for two reasons:
You should never catch RuntimeException. It is just a very helpful indicator for errors in code logic (i.e. developer errors) which ought be solved by writing good code.
You should never ignore e unless you know perfectly what you're doing. Add at least an e.printStackTrace() so that you at least know that something failed.
I cleaned up your code for you. Generally, when you have two sections of code that are supposed to be doing the exact same thing, but are not, then rolling them into one method can eliminate that possibility.public void showMovementCase(){
// probably want to remove anything left over from the last invocation
panel.removeAll();
for (JLabel[] array : actionSquare) Arrays.fill(array, null);
colorSquares(moveAllowed + attackDistance, redsquare, null);
colorSquares(moveAllowed * 2, bluesquare, mouse);
for (int x = 0; x < actionSquare.length; x++)
for (int y = 0; y < actionSquare[x].length; y++)
if (actionSquare[x][y] != null) panel.add(actionSquare[x][y], 1);
}
private void colorSquares(int move, Icon color, MouseListener mouse) {
int xMax = Math.min(2 * move, actionSquare.length);
int yMax = Math.min(2 * move, actionSquare[0].length);
for (int x = 0; x < xMax; x++) {
for (int y = 0; y < yMax; y++) {
if (isLegal(x, y, move)) {
if (actionSquare[x][y] == null)
actionSquare[x][y] = new JLabel();
actionSquare[x][y].setIcon(color);
actionSquare[x][y].setBounds(
sprite.getX() + (x - move) * 16,
sprite.getY() + (y - move) * 16, 16, 16 );
if (mouse != null) actionSquare[x][y].addMouseListener(mouse);
}
}
}
}
private static boolean isLegal(int x, int y, int move) {
// informative comment explaining why this mess makes sense
if (move <= y+x && move >= y-x && x <= move) return true;
// informative comment explaining why this mess makes sense
if (move <= y+x && move >= x-y && x > move && y <= move) return true;
// informative comment explaining why this mess makes sense
if (move * 3 >= y+x && move >= y-x && x > move && y >= move) return true;
return false;
}