Error in checking for if mouse is in tolerance - if-statement

I have a rect, which I want to disappear when it's getting clicked.
I use the following method to control if the mouseX and height*0.9 is in the area of the rectangle when clicked:
//balken is a ArrayList of the object holding the variables for the rectangle
boolean mouseInTolerance()
{
return ((mouseX > balken.get(0).x- balken.get (0).balkenWidth*.5
|| mouseX < balken.get(0).x+ balken.get (0).balkenWidth*.5)
&& (height*.9 > balken.get(0).y- tolerance
|| height*.9 <balken.get(0).y+ tolerance));
However, this returns true no matter where the mouse has been clicked.
Edit: rectMode is set to CENTER

Let's consider this line:
return ((mouseX > balken.get(0).x- balken.get (0).balkenWidth*.5
|| mouseX < balken.get(0).x+ balken.get (0).balkenWidth*.5)
&& (height*.9 > balken.get(0).y- tolerance
|| height*.9 <balken.get(0).y+ tolerance));
Now let's substitute in a value for your variables, just to more easily see what's going on. It doesn't really matter what values we choose, so let's go with these:
balken.get(0).x = 100;
balken.get(0).y = 200;
balken.get(0).balkenWidth = 20;
balken.get(0).balkenHeight = 30;
height = 1000;
tolerance = 10;
Doing the substitution, you get this:
return (mouseX > 90 || mouseX < 110)
&& (900 > 190 || 900 < 210);
Now let's take each half of that:
(mouseX > 90 || mouseX < 110)
When will that ever be false? Can you come up with a number for mouseX that makes this false? It looks like you were trying to determine when mouseX was between these two points, right? Therefore, you want and between these two inequalities, not or.
Similarly:
(900 > 190 || 900 < 210)
You can change that 900 to any value, and this will never be false. Again, you want an and operator in there, not an or.
The reason for this is simple. Let's say we have three X values: LEFT, MIDDLE, and RIGHT. How do we determine when the MIDDLE point is between the LEFT point and the RIGHT point? The MIDDLE point has to be to the right of the LEFT point- in other words, MIDDLE > LEFT. It also has to be to the left of the RIGHT point- in other words, MIDDLE > LEFT && MIDDLE < RIGHT.
The same logic applies to the vertical y value.

Related

How to avoid if / else if chain when classifying a heading into 8 directions?

I have the following code:
if (this->_car.getAbsoluteAngle() <= 30 || this->_car.getAbsoluteAngle() >= 330)
this->_car.edir = Car::EDirection::RIGHT;
else if (this->_car.getAbsoluteAngle() > 30 && this->_car.getAbsoluteAngle() <= 60)
this->_car.edir = Car::EDirection::UP_RIGHT;
else if (this->_car.getAbsoluteAngle() > 60 && this->_car.getAbsoluteAngle() <= 120)
this->_car.edir = Car::EDirection::UP;
else if (this->_car.getAbsoluteAngle() > 120 && this->_car.getAbsoluteAngle() <= 150)
this->_car.edir = Car::EDirection::UP_LEFT;
else if (this->_car.getAbsoluteAngle() > 150 && this->_car.getAbsoluteAngle() <= 210)
this->_car.edir = Car::EDirection::LEFT;
else if (this->_car.getAbsoluteAngle() > 210 && this->_car.getAbsoluteAngle() <= 240)
this->_car.edir = Car::EDirection::DOWN_LEFT;
else if (this->_car.getAbsoluteAngle() > 240 && this->_car.getAbsoluteAngle() <= 300)
this->_car.edir = Car::EDirection::DOWN;
else if (this->_car.getAbsoluteAngle() > 300 && this->_car.getAbsoluteAngle() <= 330)
this->_car.edir = Car::EDirection::DOWN_RIGHT;
I want to avoid the ifs chain; it's really ugly. Is there a another, possibly cleaner, way of writing this?
#include <iostream>
enum Direction { UP, UP_RIGHT, RIGHT, DOWN_RIGHT, DOWN, DOWN_LEFT, LEFT, UP_LEFT };
Direction GetDirectionForAngle(int angle)
{
const Direction slices[] = { RIGHT, UP_RIGHT, UP, UP, UP_LEFT, LEFT, LEFT, DOWN_LEFT, DOWN, DOWN, DOWN_RIGHT, RIGHT };
return slices[(((angle % 360) + 360) % 360) / 30];
}
int main()
{
// This is just a test case that covers all the possible directions
for (int i = 15; i < 360; i += 30)
std::cout << GetDirectionForAngle(i) << ' ';
return 0;
}
This is how I would do it. (As per my previous comment).
You can use map::lower_bound and store the upper-bound of each angle in a map.
Working example below:
#include <cassert>
#include <map>
enum Direction
{
RIGHT,
UP_RIGHT,
UP,
UP_LEFT,
LEFT,
DOWN_LEFT,
DOWN,
DOWN_RIGHT
};
using AngleDirMap = std::map<int, Direction>;
AngleDirMap map = {
{ 30, RIGHT },
{ 60, UP_RIGHT },
{ 120, UP },
{ 150, UP_LEFT },
{ 210, LEFT },
{ 240, DOWN_LEFT },
{ 300, DOWN },
{ 330, DOWN_RIGHT },
{ 360, RIGHT }
};
Direction direction(int angle)
{
assert(angle >= 0 && angle <= 360);
auto it = map.lower_bound(angle);
return it->second;
}
int main()
{
Direction d;
d = direction(45);
assert(d == UP_RIGHT);
d = direction(30);
assert(d == RIGHT);
d = direction(360);
assert(d == RIGHT);
return 0;
}
Create an array, each element of which is associated with a block of 30 degrees:
Car::EDirection dirlist[] = {
Car::EDirection::RIGHT,
Car::EDirection::UP_RIGHT,
Car::EDirection::UP,
Car::EDirection::UP,
Car::EDirection::UP_LEFT,
Car::EDirection::LEFT,
Car::EDirection::LEFT,
Car::EDirection::DOWN_LEFT,
Car::EDirection::DOWN,
Car::EDirection::DOWN,
Car::EDirection::DOWN_RIGHT,
Car::EDirection::RIGHT
};
Then you can index the array with the angle / 30:
this->_car.edir = dirlist[(this->_car.getAbsoluteAngle() % 360) / 30];
No comparisons or branching required.
The result however is slightly off from the original. Values on the borders, i.e. 30, 60, 120, etc. are placed in the next category. For example, in the original code the valid values for UP_RIGHT are 31 to 60. The above code assigns 30 to 59 to UP_RIGHT.
We can get around this by subtracting 1 from the angle:
this->_car.edir = dirlist[((this->_car.getAbsoluteAngle() - 1) % 360) / 30];
This now gives us RIGHT for 30, UP_RIGHT for 60, etc.
In the case of 0, the expression becomes (-1 % 360) / 30. This is valid because -1 % 360 == -1 and -1 / 30 == 0, so we still get an index of 0.
Section 5.6 of the C++ standard confirms this behavior:
4 The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first
expression by the second. If the second operand of / or % is zero
the behavior is undefined. For integral operands the / operator
yields the algebraic quotient with any fractional part discarded. if
the quotient a/b is representable in the type of the result,
(a/b)*b + a%b is equal to a.
EDIT:
There were many questions raised regarding the readability and maintainability of a construct like this. The answer given by motoDrizzt is a good example of simplifying the original construct that is more maintainable and isn't quite as "ugly".
Expanding on his answer, here's another example making use of the ternary operator. Since each case in the original post is assigning to the same variable, using this operator can help increase readability further.
int angle = ((this->_car.getAbsoluteAngle() % 360) + 360) % 360;
this->_car.edir = (angle <= 30) ? Car::EDirection::RIGHT :
(angle <= 60) ? Car::EDirection::UP_RIGHT :
(angle <= 120) ? Car::EDirection::UP :
(angle <= 150) ? Car::EDirection::UP_LEFT :
(angle <= 210) ? Car::EDirection::LEFT :
(angle <= 240) ? Car::EDirection::DOWN_LEFT :
(angle <= 300) ? Car::EDirection::DOWN:
(angle <= 330) ? Car::EDirection::DOWN_RIGHT :
Car::EDirection::RIGHT;
That code is not ugly, it's simple, practical, readable and easy to understand. It will be isolated in it's own method, so nobody will have to deal with it in everyday life. And just in case someone has to check it -maybe because he is debugging your application for a problem somewhere else- it's so easy it will take him two seconds to understand the code and what it does.
If I was doing such a debug I'd be happy to not have to spend five minutes trying to understand what your function does. In this regards, all other functions fail completely, as they change a simple, forget-about-it, bugs free routine, in a complicated mess that people when debugging will be forced to deeply analyse and test. As a project manager myself I'd strongly get upset by a developer taking a simple task and instead of implementing it into a simple, harmless way, wastes time to implement it into an over complicate way. Just think all the time you wasted thinking about it, then coming to SO asking, and all for just the sake of worsening maintenance and readability of the thing.
That said, there is a common mistake in your code that make it quite less readable, and a couple improvements you can do quite easily:
int angle = this->_car.getAbsoluteAngle();
if (angle <= 30 || angle >= 330)
return Car::EDirection::RIGHT;
else if (angle <= 60)
return Car::EDirection::UP_RIGHT;
else if (angle <= 120)
return Car::EDirection::UP;
else if (angle <= 150)
return Car::EDirection::UP_LEFT;
else if (angle <= 210)
return Car::EDirection::LEFT;
else if (angle <= 240)
return Car::EDirection::DOWN_LEFT;
else if (angle <= 300)
return Car::EDirection::DOWN;
else if (angle <= 330)
return Car::EDirection::DOWN_RIGHT;
Put this into a method, assign the returned value to the object, collapse the method, and forget about it for the rest of eternity.
P.S. there is another bug over the 330 threshold, but I don't know how you want to treat it, so I didn't fix it at all.
Later update
As per comment, you can even get rid of the else if at all:
int angle = this->_car.getAbsoluteAngle();
if (angle <= 30 || angle >= 330)
return Car::EDirection::RIGHT;
if (angle <= 60)
return Car::EDirection::UP_RIGHT;
if (angle <= 120)
return Car::EDirection::UP;
if (angle <= 150)
return Car::EDirection::UP_LEFT;
if (angle <= 210)
return Car::EDirection::LEFT;
if (angle <= 240)
return Car::EDirection::DOWN_LEFT;
if (angle <= 300)
return Car::EDirection::DOWN;
if (angle <= 330)
return Car::EDirection::DOWN_RIGHT;
I didn't do it 'cause I feel that a certain point it becomes just a matter of own preferences, and the scope of my answer was (and is) to give a different perspective to your concern about "ugliness of code". Anyway, as I said, someone pointed it out in the comments and I think it makes sense to show it.
In pseudocode:
angle = (angle + 30) %360; // Offset by 30.
So, we have 0-60, 60-90, 90-150,... as the categories.
In each quadrant with 90 degrees, one part has 60, one part has 30. So, now:
i = angle / 90; // Figure out the quadrant. Could be 0, 1, 2, 3
j = (angle - 90 * i) >= 60? 1: 0; // In the quardrant is it perfect (eg: RIGHT) or imperfect (eg: UP_RIGHT)?
index = i * 2 + j;
Use the index in an array containing the enums in the appropriate order.
switch (this->_car.getAbsoluteAngle() / 30) // integer division
{
case 0:
case 11: this->_car.edir = Car::EDirection::RIGHT; break;
case 1: this->_car.edir = Car::EDirection::UP_RIGHT; break;
...
case 10: this->_car.edir = Car::EDirection::DOWN_RIGHT; break;
}
Ignoring your first if which is a bit of a special case, the remaining ones all follow the exact same pattern: a min, max and direction; pseudo-code:
if (angle > min && angle <= max)
_car.edir = direction;
Making this real C++ might look like:
enum class EDirection { NONE,
RIGHT, UP_RIGHT, UP, UP_LEFT, LEFT, DOWN_LEFT, DOWN, DOWN_RIGHT };
struct AngleRange
{
int min, max;
EDirection direction;
};
Now, rather than writing a bunch of ifs, just loop over your various possibilies:
EDirection direction_from_angle(int angle, const std::vector<AngleRange>& angleRanges)
{
for (auto&& angleRange : angleRanges)
{
if ((angle > angleRange.min) && (angle <= angleRange.max))
return angleRange.direction;
}
return EDirection::NONE;
}
(throwing an exception rather than returning NONE is another option).
Which you would then call:
_car.edir = direction_from_angle(_car.getAbsoluteAngle(), {
{30, 60, EDirection::UP_RIGHT},
{60, 120, EDirection::UP},
// ... etc.
});
This technique is known as data-driven programming. Besides getting rid of a bunch of ifs, it would allow you to use easily add more directions (e.g., NNW) or reduce the number (left, right, up, down) without re-working other code.
(Handling your first special case is left as "an exercise for the reader." :-) )
Although the proposed variants based on a lookup table for angle / 30 are probably preferable, here is an alternative that uses a hard coded binary search to minimize the number of comparisons.
static Car::EDirection directionFromAngle( int angle )
{
if( angle <= 210 )
{
if( angle > 120 )
return angle > 150 ? Car::EDirection::LEFT
: Car::EDirection::UP_LEFT;
if( angle > 30 )
return angle > 60 ? Car::EDirection::UP
: Car::EDirection::UP_RIGHT;
}
else // > 210
{
if( angle <= 300 )
return angle > 240 ? Car::EDirection::DOWN
: Car::EDirection::DOWN_LEFT;
if( angle <= 330 )
return Car::EDirection::DOWN_RIGHT;
}
return Car::EDirection::RIGHT; // <= 30 || > 330
}
If you really want to avoid duplication you can express this as a mathematical formula.
First of all, assume that we are using #Geek's Enum
Enum EDirection { RIGHT =0, UP_RIGHT, UP, UP_LEFT, LEFT, DOWN_LEFT,DOWN, DOWN_RIGHT}
Now we can compute the enum using integer mathematics (with out the need for arrays).
EDirection angle2dir(int angle) {
int d = ( ((angle%360)+360)%360-1)/30;
d-=d/3; //some directions cover a 60 degree arc
d%=8;
//printf ("assert(angle2dir(%3d)==%-10s);\n",angle,dir2str[d]);
return (EDirection) d;
}
As #motoDrizzt points out, concise code isn't necessarily readable code. It does have the small advantage that expressing it as maths makes it explicit that some directions cover a wider arc. If you want to go this direction you can add some asserts to help understand the code.
assert(angle2dir( 0)==RIGHT ); assert(angle2dir( 30)==RIGHT );
assert(angle2dir( 31)==UP_RIGHT ); assert(angle2dir( 60)==UP_RIGHT );
assert(angle2dir( 61)==UP ); assert(angle2dir(120)==UP );
assert(angle2dir(121)==UP_LEFT ); assert(angle2dir(150)==UP_LEFT );
assert(angle2dir(151)==LEFT ); assert(angle2dir(210)==LEFT );
assert(angle2dir(211)==DOWN_LEFT ); assert(angle2dir(240)==DOWN_LEFT );
assert(angle2dir(241)==DOWN ); assert(angle2dir(300)==DOWN );
assert(angle2dir(301)==DOWN_RIGHT); assert(angle2dir(330)==DOWN_RIGHT);
assert(angle2dir(331)==RIGHT ); assert(angle2dir(360)==RIGHT );
Having added the asserts you have added duplication, but duplication in asserts isn't so bad. If you have an inconsistent assert you will find out soon enough. Asserts can be compiled out of release version so as not to bloat the executable you distribute. Nevertheless, this approach is probably most applicable if you want to optimize the code rather than just make it less ugly.
I'm Late to the party, but We could use enum flags and range checks to do something neat.
enum EDirection {
RIGHT = 0x01,
LEFT = 0x02,
UP = 0x04,
DOWN = 0x08,
DOWN_RIGHT = DOWN | RIGHT,
DOWN_LEFT = DOWN | LEFT,
UP_RIGHT = UP | RIGHT,
UP_LEFT = UP | LEFT,
// just so we be clear, these won't have much use though
IMPOSSIBLE_H = RIGHT | LEFT,
IMPOSSIBLE_V = UP | DOWN
};
the checking(pseudo-code), assuming angle is absolue (between 0 and 360):
int up = (angle > 30 && angle < 150) * EDirection.UP;
int down = (angle > 210 && angle < 330) * EDirection.DOWN;
int right = (angle <= 60 || angle >= 330) * EDirection.Right;
int left = (angle >= 120 && angle <= 240) * EDirection.LEFT;
EDirection direction = (Direction)(up | down | right | left);
switch(direction){
case RIGHT:
// do right
break;
case UP_RIGHT:
// be honest
break;
case UP:
// whats up
break;
case UP_LEFT:
// do you even left
break;
case LEFT:
// 5 done 3 to go
break;
case DOWN_LEFT:
// your're driving me to a corner here
break;
case DOWN:
// :(
break;
case DOWN_RIGHT:
// completion
break;
// hey, we mustn't let these slide
case IMPOSSIBLE_H:
case IMPOSSIBLE_V:
// treat your impossible case here!
break;
}

Colliding with obstacles on a map

I'm trying to make obstacles that stops the player after colliding. Simply, the walls.
I've created collision detection, like this:
if (x > (wall.x1 - wall.boundX) && x < (wall.x + wall.boundX) &&
y >(wall.y1 - wall.boundY) && y < (wall.y + wall.boundY))
{
x = 0;
y = 0;
}
but, as you can see, it just returns my player object to (0,0) on map (by the way, I'm using mouse to control my character). I want it to stop right where he collides and to be unable to move through this wall.
How can I do that?
You will need to separate your if statement to handle each wall separately, and then set the x or y position to the bounds of the wall:
if (x > wall.x1 - wall.boundX)
x = wall.x1 - wall.boundX;
if (x < (wall.x + wall.boundX))
x = wall.x + wall.boundX;
// etc
No matter how far the mouse attempts to move past the bounds of the wall, it will just remain at that position.

Determining if a set of points are inside or outside a square

I have two of these:
bool isPointOnShape(int a, int b)
{
}
bool isPointInShape(int a, int b)
{
}
Say I have a square, first point (bottom left corner) is x,y (0,0) second point (top left) is (0,2), third is (2,2) and fourth is (0,2).
The Points on shape would be (0,1) (1,2) (2,1) (1,0) and Points in shape is (1,1)
How do I find out the points on shape / in shape and return a true value so that I can store it somewhere?
I'll offer a general solution for any shape that can be divided in straight segments.
So, as you may have guessed, I'll start by consider your "shape" as a list of segments that completes a loop. Or simply put a circular list of points that represents a loop, for example, your square would be this list of points:
0, 0
0, 2
2, 2
2, 0
Note that we consider that there are segments from each point to the next and that the final point connects to the first. Also, we require that no consecutive points are equal, nor the first and last. If there are any, those must be removed before proceeding.
Now, for each segment we can determinate the bounding box. For example given this segment:
a = (0, 2)
b = (2, 2)
Then the range of values in x is [0, 2] and in y is [2, 2] and that is your bounding box for that segment.
The next thing you need is the director vector of the line of the segment. To get that, first calculate the length of the segment:
length = sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y))
And then:
director.x = (a.x - b.x)/length
director.y = (a.y - b.y)/length
Note 1: when then length is 0, then you have an invalid segment. That's why we don't want repeated points.
Note 2: Using the director vector instead of using the equation of the line will make things easier.
Now, given a point p, you can determinate if that point is in a segment (if it is one of the points in the list). For the rest of cases we start by looking if it is inside of the axis aligned bounding box. This is done simply by checking the range:
if
(
(p.x >= box.left && p.x <= box.right) &&
(p.y >= box.top && p.y <= box.bottom) // with origin at the top-left corner
)
{
//It is inside of the bounding box
}
And if it is, then we calculate the distance from the point to the line, if it is
0 then it is on the line. Now, because of floating point arithmetics, you could test if the distance is less or equal to epsilon, where epsilon is a very small number.
We use this formula:
distance vector = (a - p) - ((a - p) · director) * director
distance = the norm of distance vector
Where "·" denotes a dot product and "*" denotes an scalar product.
All that rests is to iterate over the segments, for each one calculate the distance and if for anyone the distance is less than epsilon then the point is "on the shape".
Ok, but what about "in the shape"?
Well, with a little help of a trick from topology we can determinate if a point is inside or not. This is the same algorithm Windows would use to fill a polygon or polyline (such as deciding what is inside a selected area with free hand in Microsoft Paint).
It goes like this:
Count the number of segments you have to cross to get to the point from outside. If the number is pair, then it is outside, if it is odd then inside.
You can choose from what direction to reach the point. I choose left.
Once more, you are going to iterate over the segments. For each one we need to decide if it is at the vertical range. For that use the bounding box:
if ((p.y >= box.top && p.y <= box.bottom))
{
//In the vertical range
}
Now, determinate if the segment is at left, or right:
if (p.x < box.left)
{
//The segment is at the left
}
else if (p.x > box.right)
{
//The segment is at the right
}
else
{
//The segment is close, need further calculation
}
In the case that the segment is close we need to calculate the vector distance to that segment and check it's direction.
The vector distance? Well, we already have it, we are taking its norm to determinate the distance. Now, instead of taking the norm, verify the sign of the x coordinate. If it is less than 0, it is right, if it is more than 0 then it is left. If it is 0... it means that the segment is horizontal (because the distance vector is always perpendicular to the segment), you can skip that segment*.
*: In fact, if the segment is horizontal and it is in vertical range, it means that it is at the segment. Are segments "in shape" or not?
Now, you need to count the number of segments at the left, and if it odd, the point is inside the shape. It is out otherwise. This can also be done with the segments that are up, or right, or below. I just picked left.
For large shapes where iterating over all the segments is expensive, you can store the segments in some space partitioning data structure. That is beyond the scope of this post.
If I suppose you have a Rectangle class and that this class has members bottomLeft and topRight, you can write something like this:
bool Rectangle::isPointOnShape(int x, int y) {
if (x == bottomLeft.x || x == topRight.x)
if (y > bottomLeft.y && y < topRight.y)
return true;
if (y == bottomLeft.y || y == topRight.y)
if (x > bottomLeft.x && x < topRight.x)
return true;
}
bool Rectangle::isPointInShape(int x, int y) {
bool inX = false;
bool inY = false;
if (x > bottomLeft.x && x < topRight.x)
inX = true;
if (y > bottomLeft.y && y < topRight.y)
inY = true;
return (inX && inY);
}
If your shape is not a rectangle, this functions will be different of course.

Recursive floodFill function? C++

So recursion is not my strong point, and I have been challenged to make a recursive floodFill function that fills a vector of a vector of ints with 1's if the value is zero. My code keeps segfaulting for reasons beyond me. Perhaps my code will make that sound more clear.
This is the grid to be flood filled:
vector<vector<int> > grid_;
It belongs to an object I created called "Grid" that is basically a set of functions to help manipulate the vectors. The grid's values are initialized to all zeros.
This is my flood fill function:
void floodFill(int x, int y, Grid & G)
{
if (G.getValue(x,y))
{
G.setValue(x,y,1);
if(x < G.getColumns()-1 && x >= 0 && y < G.getRows()-1 && y >= 0)
floodFill(x+1,y,G);
if(x < G.getColumns()-1 && x >= 0 && y < G.getRows()-1 && y >= 0)
floodFill(x,y+1,G);
if(x < G.getColumns()-1 && x >= 0 && y < G.getRows()-1 && y >= 0)
floodFill(x-1,y,G);
if(x < G.getColumns()-1 && x >= 0 && y < G.getRows()-1 && y >= 0)
floodFill(x,y-1,G);
}
}
The intention here is to have the function check if a point's value is zero, and if it is, change it to one. Then it should check the one above it for the same. It does this until it either finds a 1 or hits the end of the vector. Then it tries another direction and keeps going until the same conditions as above and so on and so forth until its flood filled.
Can anyone help me fix this? Maybe tell me whats wrong?
Thanks!
if(x < G.getColumns()-1 && x >= 0 && y < G.getRows()-1 && y >= 0)
floodFill(x-1,y,G);
won't work, since you can access index -1 of the underlying vector if x == 0
Same goes for floodFill(x,y-1,G);
This code has a lot of problems. First of all you check with if(G.getValue(x,y)) whether the value at a position is 1, and if so, then you set it to 1 with G.setValue(x,y,1). Think about this for a second, this can't be right. When will you ever set non-zero values to 1?
Then, another more subtle point is that you shouldn't do the recursion into neighbors if they are already set to 1.
As it stands the code you have will likely run until you overflow the stack because just going to recurse forever on the 1's that are connected to wherever you start from.
How about this?
void floodFill(int x, int y, Grid &g) {
if(x >= g.getColumns() || y >= g.getRows()) {
return;
}
floodFill(x+1, y, g);
if( x == 0 ) {
floodFill(x, y+1, g);
}
g.setValue(x, y, 1)
}
I think that will fill the grid without every hitting the same coordinate multiple times, and whenever either index is out of bounds it just returns so no chance of a seg fault.

Rectangle intersect code - Is this right?

Can someone tell me whether my rectangle intersect code is correct?
bool checkCollide(int x, int y, int oWidth, int oHeight,
int x2, int y2, int o2Width, int o2Height) {
bool collide = false;
if (x >= x2 && x <= x2+o2Width && y >= y2 && y <= y2+o2Height)
collide = true;
if (x+oWidth >= x2 && x+oWidth <= x2+o2Width && y >= y2 && y <= y2+o2Height)
collide = true;
if (x >= x2 && x<= x2+o2Width && y+oHeight >= y2 && y+oHeight <= y2+o2Height)
collide = true;
if (x+oWidth >= x2 && x+oWidth <= x2+o2Width && y+oHeight >= y2 && y+oHeight <= y2+o2Height)
collide = true;
return collide;
}
Nope, a corner of a rectangle doesn't have to be in the other rectangle for the rectangles to collide. What you want to do is to find the logic when they do not intersect and use the negation of that. The picture below shows two rectangles that clearly intersect each other, but only the sides are intersecting, not the corners.
Just formulate the logic as follows: What does it take for the blue to not intersect the red? Well it's either completely to the right, completely to the left, up or below. Formulate an if statement to that and negate it.
Let me help you with the beginning:
if (!(x2 > x+oWidth || x2+o2Width < x || ..))
collide = true;
Following on from Magnus's answer, I'd take a slightly different approach.
As he says, if the two don't intersect then one will be completely left, completely right, etc. For performance however you can stop testing as soon as any of these conditions are found to be false, e.g.:
if (x2 + owidth2 < x)
return false; // box 2 is left of box 1
if (x + owidth < x2)
return false; // box 1 is left of box 2
// etc...
First implement interval intersection (i.e. one dimension).
Then you can implement rectangle intersection by first applying interval intersection to the x-coordinates and then applying interval intersection to the y-coordinates.
checkCollide(0, 0, 3, 3, 1, 1, 1, 1) == false
I'm guessing that's not what you want.