Elegant verification of a piece being at the edge of a maze - algorithm

Let's consider a game where the player has n number of pieces on a x*y grid. Also the player can move his pieces in any direction (north, south, north-east etc...). Let's assume that the only rule is that the player (when he decides to move) must move a piece for as much as he can.
ooooo
.....
.....
.....
.....
Player moves the first piece
.oooo
.....
.....
.....
o....
To make such a function (ignoring for a moment about the other directions that the player can move his piece) we have:
while(!AtEdge()){
move()
}
However this AtEdge must be configured to check if the piece is at edge depending on the direction of travel. For example:
o.....
......
......
The first piece is at edge if the direction is north, west or north-west but it's good to go in any other direction.
My thinking at the moment is that I need a switch statement to check if the piece is AtEdge() based on the direction of travel. But then I also need a switch statement for the move function.
switch(direction){
case NORTH_EAST: //code to move north-east
}
This results in 16 Switch statements however if the game was 3D and then the number would multiply. Is there a more elegant solution to achieve what I described? Is there a better way to check if the piece can move any further based on direction of travel?

The position in a x*y grid can be represented by coordinates 0 <= px < x and 0 <= py < y. (You can also choose 1 <= px <= x and 1 <= py <= y, but starting with index/coordinate 0 is more common.)
A single move to a neighbouring field can be represented by a vector (mx my) with mx, my having each one of the values -1,0,1; the combination (0 0) is excluded.
Moving now just means adding the move vector to the position giving
px_new = px + mx
py_new = py + my
Checking if the new position is inside the board can simple be done by:
inside = (0 <= px_new) and (px_new < x) and (0 <= py_new) and (py_new < y)

Related

What is the best way to check all pixels within certain radius?

I'm currently developing an application that will alert users of incoming rain. To do this I want to check certain area around user location for rainfall (different pixel colours for intensity on rainfall radar image). I would like the checked area to be a circle but I don't know how to do this efficiently.
Let's say I want to check radius of 50km. My current idea is to take subset of image with size 100kmx100km (user+50km west, user+50km east, user+50km north, user+50km south) and then check for each pixel in this subset if it's closer to user than 50km.
My question here is, is there a better solution that is used for this type of problems?
If the occurrence of the event you are searching for (rain or anything) is relatively rare, then there's nothing wrong with scanning a square or pixels and then, only after detecting rain in that square, checking whether that rain is within the desired 50km circle. Note that the key point here is that you don't need to check each pixel of the square for being inside the circle (that would be very inefficient), you have to search for your event (rain) first and only when you found it, check whether it falls into the 50km circle. To implement this efficiently you also have to develop some smart strategy for handling multi-pixel "stains" of rain on your image.
However, since you are scanning a raster image, you can easily implement the well-known Bresenham circle algorithm to find the starting and the ending point of the circle for each scan line. That way you can easily limit your scan to the desired 50km radius.
On the second thought, you don't even need the Bresenham algorithm for that. For each row of pixels in your square, calculate the points of intersection of that row with the 50km circle (using the usual schoolbook formula with square root), and then check all pixels that fall between these intersection points. Process all rows in the same fashion and you are done.
P.S. Unfortunately, the Wikipedia page I linked does not present Bresenham algorithm at all. It has code for Michener circle algorithm instead. Michener algorithm will also work for circle rasterization purposes, but it is less precise than Bresenham algorithm. If you care for precision, find a true Bresenham on somewhere. It is actually surprisingly diffcult to find on the net: most search hits erroneously present Michener as Bresenham.
There is, you can modify the midpoint circle algorithm to give you an array of for each y, the x coordinate where the circle starts (and ends, that's the same thing because of symmetry). This array is easy to compute, pseudocode below.
Then you can just iterate over exactly the right part, without checking anything.
Pseudo code:
data = new int[radius];
int f = 1 - radius, ddF_x = 1;
int ddF_y = -2 * radius;
int x = 0, y = radius;
while (x < y)
{
if (f >= 0)
{
y--;
ddF_y += 2; f += ddF_y;
}
x++;
ddF_x += 2; f += ddF_x;
data[radius - y] = x; data[radius - x] = y;
}
Maybe you can try something that will speed up your algorithm.
In brute force algorithm you will probably use equation:
(x-p)^2 + (y-q)^2 < r^2
(p,q) - center of the circle, user position
r - radius (50km)
If you want to find all pixels (x,y) that satisfy above condition and check them, your algorithm goes to O(n^2)
Instead of scanning all pixels in this circle I will check only only pixels that are on border of the circle.
In that case, you can use some more clever way to define circle.
x = p+r*cos(a)
y = q*r*sin(a)
a - angle measured in radians [0-2pi]
Now you can sample some angles, for example twenty of them, iterate and find all pairs (x,y) that are border for radius 50km. Now check are they on the rain zone and alert user.
For more safety I recommend you to use multiple radians (smaller than 50km), because your whole rain cloud can be inside circle, and your app will not recognize him. For example use 3 incircles (r = 5km, 15km, 30km) and do same thing. Efficiency of this algorithm only depends on number of angles and number of incircles.
Pseudocode will be:
checkRainDanger()
p,q <- position
radius[] <- array of radii
for c = 1 to length(radius)
a=0
while(a<2*pi)
x = p + radius[c]*cos(a)
y = q + radius[c]*sin(a)
if rainZone(x,y)
return true
else
a+=pi/10
end_while
end_for
return false //no danger
r2=r*r
for x in range(-r, +r):
max_y=sqrt(r2-x*x)
for y in range(-max_y, +max_y):
# x,y is in range - check for rain

Determine whether the direction of a line segment is clockwise or anti clockwise

I have a list of 2D points (x1,y1),(x2,y2)......(Xn,Yn) representing a curved segment, is there any formula to determine whether the direction of drawing that segment is clockwise or anti clockwise ?
any help is appreciated
Alternately, you can use a bit of linear algebra. If you have three points a, b, and c, in that order, then do the following:
1) create the vectors u = (b-a) = (b.x-a.x,b.y-a.y) and v = (c-b) ...
2) calculate the cross product uxv = u.x*v.y-u.y*v.x
3) if uxv is -ve then a-b-c is curving in clockwise direction (and vice-versa).
by following a longer curve along in the same manner, you can even detect when as 's'-shaped curve changes from clockwise to anticlockwise, if that is useful.
One possible approach. It should work reasonably well if the sampling of the line represented by your list of points is uniform and smooth enough, and if the line is sufficiently simple.
Subtract the mean to "center" the line.
Convert to polar coordinates to get the angle.
Unwrap the angle, to make sure its increments are meaningful.
Check if total increment is possitive or negative.
I'm assuming you have the data in x and y vectors.
theta = cart2pol(x-mean(x), y-mean(y)); %// steps 1 and 2
theta = unwrap(theta); %// step 3
clockwise = theta(end)<theta(1); %// step 4. Gives 1 if CW, 0 if ACW
This only considers the integrated effect of all points. It doesn't tell you if there are "kinks" or sections with different directions of turn along the way.
A possible improvement would be to replace the average of x and y by some kind of integral. The reason is: if sampling is denser in a region the average will be biased towards that, whereas the integral wouldn't.
Now this is my approach, as mentioned in a comment to the question -
Another approach: draw a line from starting point to ending point. This line is indeed a vector. A CW curve has most of its part on RHS of this line. For CCW, left.
I wrote a sample code to elaborate this idea. Most of the explanation can be found in comments in the code.
clear;clc;close all
%% draw a spiral curve
N = 30;
theta = linspace(0,pi/2,N); % a CCW curve
rho = linspace(1,.5,N);
[x,y] = pol2cart(theta,rho);
clearvars theta rho N
plot(x,y);
hold on
%% find "the vector"
vec(:,:,1) = [x(1), y(1); x(end), y(end)]; % "the vector"
scatter(x(1),y(1), 200,'s','r','fill') % square is the starting point
scatter(x(end),y(end), 200,'^','r','fill') % triangle is the ending point
line(vec(:,1,1), vec(:,2,1), 'LineStyle', '-', 'Color', 'r')
%% find center of mass
com = [mean(x), mean(y)]; % center of mass
vec(:,:,2) = [x(1), y(1); com]; % secondary vector (start -> com)
scatter(com(1), com(2), 200,'d','k','fill') % diamond is the com
line(vec(:,1,2), vec(:,2,2), 'LineStyle', '-', 'Color', 'k')
%% find rotation angle
dif = diff(vec,1,1);
[ang, ~] = cart2pol(reshape(dif(1,1,:),1,[]), reshape(dif(1,2,:),1,[]));
clearvars dif
% now you can tell the answer by the rotation angle
if ( diff(ang)>0 )
disp('CW!')
else
disp('CCW!')
end
One can always tell on which side of the directed line (the vector) a point is, by comparing two vectors, namely, rotating vector [starting point -> center of mass] to the vector [starting point -> ending point], and then comparing the rotation angle to 0. A few seconds of mind-animating can help understand.

Collision Detection between a line and a circle in python(tkinter)

I writing a python program in which a circle bounces off of user drawn lines. There are multiple circles that bounce off the wall. For each one, the shortest distance from the center of the circle and the ball should be calculated. I would prefer if this code was very efficient because my current algorithm lags the computer a lot. If point a is the starting point ,and point b is the end point, and point c is the center, and r is the radius, how would I calculate the shortest distance between the ball? This algorithm should also work if the X coordinate of the ball is out of range of x coordinates in segment AB.
Please post python code
Any help would be appreciated!
Here's what I have so far:
lineList is a list with 4 values that contains beginning and end coordinates of the user drawn lines
center is the center of the ball
global lineList, numobjects
if not(0 in lineList):
beginCoord = [lineList[0],lineList[1]]
endCoord = [lineList[2]-500,lineList[3]-500]
center = [xCoordinate[i],yCoordinate[i]+15]
distance1 = math.sqrt((lineList[1] - center[1])**2 + (lineList[0] - center[0])**2)
slope1 = math.tan((lineList[1] - lineList[3]) / (lineList[0] - lineList[2]))
try:
slope2 = math.tan((center[1] - beginCoord[1])/(center[0]-beginCoord[0]))
angle1 = slope2 + slope1
circleDistance = distance1 * math.sin(angle1)
except:
#If the circle is directly above beginCoord
circleDistance = center[1] - lineList[1]
global numbounces
if circleDistance < 2 and circleDistance > -2:
print(circleDistance)
b = False
b2=False
if xCoordinate[i] < 0:
xCoordinate[i] += 1
speed1[i] *= -1
b=True
elif xCoordinate[i] > 0:
xCoordinate[i] -= 1
speed1[i] *= -1
b=True
if yCoordinate[i] < 0:
yCoordinate[i] += 1
speed2[i] *= -1
b2=True
elif yCoordinate[i] > 0:
yCoordinate[i] -= 1
speed2[i] *= -1
b2=True
if b and b2:
#Only delete the line if the ball reversed directions
numbounces += 1
#Add a ball after 5 bounces
if numbounces % 5 == 0 and numbounces != 0:
numobjects = 1
getData(numobjects)
canvas.delete("line")
lineList = [0,0,0,0]
To be correct we are not speaking not about lines, but rather segments.
I would suggest the following idea:
Since the ball is moving in some direction, the only points that might collide with something lie on a 180° arc - the part that is moving forward. Meaning at some point of time when you check for collision you have to check whether any of those points collided with something. The more points you check, the better the precision of the collision in time, but worse the complexity.
Checking the collision: you check whether any of the points is in between the extremes of the segment. You can do this by first checking the coordinates (example is given looking at your drawn line, meaning A.x < B.x and A.y > B.y) if (A.x <= point.x <= B.x && A.y >= point.y >= B.y if the condition satisfies, you check whether the 3 points form a line. Since you have already the coordinates of A and B you can deduce the equation of the line and check whether the point satisfies it.
In short: you check if the point satisfies the equation of the line and is inside the rectangle defined by the 2 points.
How to get the points you have to check: assuming 2k+1 is the number of points you want to check at some time, C is your center r the radius and V the vector of motion. Then the number of points from the left side of the direction vector and from the right side will be equal and be k (+1 point at the intersection of the circle and the motion vector). Then 90° / k is one angular division. Since you know the motion vector, you can calculate the angle between it and the horizontal line (let it be angle). You keep adding to go left and decrementing to go right from the motion vector the value of 90° / k exactly k times (let us denote this value by i) and calculate the position of the point by point.x = C.x + sin(i) * r and point.y = C.y + cos(i) * r.
Sry, I don't know python.
The shortest distance from a circle to a line is the shortest distance from its center to that line, minus the radius of the circle. If the distance from the center to the line is less than the radius, the line passes through the circle.
Finding the distance from a point to a line is documented many places, including here.
Sorry for not posting Python code, but it is pretty basic.

Dynamic Programming: Chessboard

A rook starts in the upper left corner of a standard 8 by 8 chessboard. Two players take turns moving the rook either horizontally to the right or vertically downward, as many squares as they like.
Stationary moves are not allowed and Player 1 goes first. The winner is the player that places the rook on the lower right corner square. Say who will win and describe the winning strategy.
I have the above statement problem and I'm interested in seeing how others would approach the problem. I know there is way to calculate the different paths that the rook can take. I tried doing the problem by hand and it always seemed like Player 2 always won but I might be thinking of it too simply. Approaching it in a dynamic programming fashion seemed like a good way to go. Anyway, anyone have any insights, algorithms, or such to approaching this problem!
H8 is a winner box so everything above and left of it is loser box.
Everything to right and below of G7 (G8 and H7) is a loser box so it is a winner box.
G7 is a winner box so everything above and left of it is loser box.
And so on…
Player one that starts the game has only choice to go to a loser box so player two always wins.
All player two has to do is to move to a w box every time it's his turn.
I think it's worth to note, that the game described is in fact a Nim game with two piles seven coins each. The winner of Nim game can be determined by xoring the numbers of coins in each pile. They call it Nim-sum and it gives a value of Sprague-Grundy function. The position is winning whenever Nim-sum is positive. So considering your game: 7^7 = 0, which is a losing position. Every diagonal position is losing since for whatever x is, x^x is always 0.
The good thing is that using this technique you can play (and win) this game in 3-dimensional and arbitrarily large space, as well as in 4-, 5-dimensional and so on.
Player two always wins for a chessboard of any size. Proof by induction on the size of the board.
The n=1 case can be ignored, so start with n=2; it is clear that Player 2 wins on a 2x2 board.
Assume that Player 2 always wins on a board of size n or less. On a board of size n+1, Player 1 moves to a position in the left column or the top row. Player 2 then moves to a position on the diagonal (that's all the strategy you need), which is then a starting position on a board of size n or less.
QED
A winning position has the following properties:
All terminal positions are winning. In this case the position (8, 8) is a winning position
All positions that can reach the goal position in a step are winning postions. I.e. all positions in the last row or column are winning positions
If we can move to a losing position then we are in a winning position since the next player cannot win the game
If we are only able to move to a winning position then we are in a losing position
With that in mind we can create an algorithm that can tell us if the current position is a winning position or a losing one. Using a table (dpTable) to store previously calculated results will avoid doing repeated computations.
boolean isWinning(int x, int y) {
if (dpTable[x][y] != null)
return dpTable[x][y];
// From the last row or the last column we can always win the game
if (x == n || y == n)
return true;
for (int i = 1; x + i <= n; i++) {
// Moving right
if (x + i <= n && !isWinning(x+i, y) {
dpTable[x][y] = true;
return true;
}
// Moving down
if (y + i <= n && !isWinning(x, y+i) {
dpTable[x][y] = true;
return true;
}
}
dpTable[x][y] = false;
return false;
}
The isWinning(x, y) function returns true when starting from position (x, y) you can win the game by playing optimally and false when there is no way for you to start at (x, y) and win.

An algorithm to randomly place circles at least D distance apart

I'm trying to work out how to write an algorithm to randomly place circles of R radius, in a 2d rectangle of arbitrary dimensions, such that each placed circle is at least D distance away from other circles in the rectangle,
The rectangle doesn't need to be filled, to be more specific older circles may be destroyed, so I need to be able to place a new circle that respects the positions of the last N circles I've already placed (say 5 for eg), if it can't satisfy these conditions then I could handle it seperately.
Can anyone help me how to deduce such an algorithm, or perhaps point to some research that may cover this?
1 Place circle at random location
2 Loop over previous circles
3 if too close
4 delete new circle
5 goto 1
6 if need more circles
7 goto 1
To determine if there is room
Choose resolution required, say delta = D/100
for( x = 0; x < rectangle_size x += delta )
for( y = 0; y < rectangle_size y += delta )
unset failed
loop over circles
if x,y less than 2D from circle
set failed
break from circle loop
if not failed
return 'yes there is room'
return 'no, there is no room'
If you expect to have so many circles that there only a few holes left with room for new circles, then you could do this
clear candidates
Choose resolution required, say delta = D/100
for( x = 0; x < rectangle_size x += delta )
for( y = 0; y < rectangle_size y += delta )
unset failed
loop over circles
if x,y less than 2D from circle
set failed
break from circle loop
if not failed
add x,y to candidates
if no candidates
return 'there is no room'
randomly choose location for new circle from candidates
1. Pick random startingspot.
2. Place circle
3. Move in random direction at least D
4. Goto 2 until distance to edge is < D or the distance to another circles center is < 2D
The first algorithm to come to mind is simulated annealing. Basically, you start out with the easiest solution, probably just a grid, then you "shake the box" in random ways to see if you get better answers. First you do large shakes, then gradually make them smaller. It sounds a little chaotic, and doesn't always produce the absolute best solution, but when something is computationally intensive it usually comes pretty close in a lot shorter time.
It really depends on what you mean by "random". Assuming that you want as close to a uniform distribution as possible, you will probably have to use an iterative solution like the one ravenspoint suggested. It may be slightly faster to place all of the circles randomly and then start replacing circles that don't meet your distance condition.
If the randomness isn't that important - i.e. if it just has to "look" random (which is probably fine if you're not doing something scientific), then grid your space up and place your N circles by choosing N indices in the grid. You could make it slightly more "random" by adding some noise to the location that you place the circle inside the grid. This would work really well for sparse placement.

Resources