Snake game - how to calculate the next apple position - javascript

I'm implementing a Snake game in javascript for fun, I have successfully implemented the snake, its movements and the snake-growth thing as it eats an apple.
To calculate the apple position I'm currently following these steps:
create a new apple object
create random coordinates (X and Y, between game-container boundaries) for the apple
check if the coordinates of the apple are equal to one of the snake-blocks coordinates
if step #3 is TRUE, recalculate the position of the apple, else draw the apple in the game-container
Unfortunately I found out that this algorithm is very weak.. let's say I have a 10 x 10 game container, the red square is the apple, the green square is my snake head (initial game state)
as the game progresses the snake eats more and more apples, increasing its length and leaving less and less empty cells to place an apple
Now suppose that the snake reaches a length equals to 99 while eating an apple. This means that there's only one square left to place the next apple. My algorithm (this is the worst case obviously) could take forever in order to randomize the correct value, as it discards any randomized position that it's already taken by the snake's head or tail, not caring at all to randomize the new position in a range of "empty cells" only but instead randomizing on the whole 10 x 10 game canvas.
How should I proceed to solve my busillis? Can you give me any advice on a good algorithm that I can use?
Thank you

As said in comments, the easiest solution I can think is to make a list of free coordinates and then just choose randomly from them.
And you can calculate free coordinates only if needed(when you need to add an apple).

Related

3D Calculating the Z position of a point in a triangle

To create my three-dimensional engine, I used rasterization: dividing the triangles at their points.
However to carry out the rasterization I convert the points into the 2 dimensions. I then add the dot to a list that will render them later. To rearrange them, however, I need to know the Z position of the points.
So my question is: I have a triangle in 3 dimensions. I then convert it into the 2 dimensions. For each single point, how do I know the Z position, knowing its position of the 2 dimensions?
I tried a weird formula, which based on the distance from the points averaged the Z positions, but it's not working; Can you help me?

Efficient algorithm for finding which hexagon a point belongs to

I'm trying to find a more efficient way of determining which hexagon a point belongs to from the following:
an array of points - for the sake of argument, 10000 points.
an array of center points of hexagons, approximately 1000 hexagons.
every point will belong to exactly one hexagon, some (most) hexagons will be empty.
The hexagons form a perfect grid, with the point of one hexagon starting in the top left corner (it will overlap the edge of the total area).
My current solution works, but is rather slow n * (m log m) I think, where n=length(points) and m=length(hexagons).
I suspect I can do much better than this, one solution that comes to mind is to sort (just once) both the points and the hexagons by their distance to some arbitrary point (perhaps the middle, perhaps a corner) then iterate over the points and over a subset of the hexagons, starting from the first hexagon whose distance to this point is >= to the last hexagon matched. Similarly, we could stop looking at hexagons once the distance difference between the (point -> ref point) and (hexagon center -> ref point) is larger than the "radius" of the hexagon. In theory, since we know that every point will belong to a hexagon, I don't even have to consider this possibility.
My question is: Is there a Much better way of doing it than this? In terms of complexity, I think it's worst case becomes marginally better n * m but the average case should be very good, probably in the region of n * 20 (e.g., we only need to look at 20 hexagons per point). Below is my current inefficient solution for reference.
points.forEach((p) => {
p.hex = _.sortBy(hexes, (hex) => {
const xDist = Math.abs(hex.middle.x - p.x);
const yDist = Math.abs(hex.middle.y - p.y);
return Math.sqrt((xDist * xDist) + (yDist * yDist));
})[0];
});
For an arbitrary point, you can find the nearest hexagon center in two steps (assuming the same arrangement as that of Futurologist):
divide the abscissa by the horizontal spacing between the centers, and round to the nearest integer.
divide the ordinate by the half of the vertical spacing, and round to the nearest even or odd integer, depending on the parity found above.
consider this center and the six ones around it, and keep the closest to the target point.
This gives you the indexes of the tile, in constant time.
Just a suggestion: assume you have the centers of each regular hexagon from your regular hexagonal grid (if I have understood correctly, that's part of the information you have).
-----
/ \
- ----- -----------> x - axis
\ / \
----- -
/ \ /
- -----
\ / \
----- -
| \ /
| -----
|
|
V
y - axis
You can think that your coordinate system starts from the center of the hexagon in the upper left corner and the y coordinate axis runs vertically down, while the x axis runs from left to right horizontally. The centers of the hexagons from your regular hexagonal grid form an image of the regular square grid, where the integer vertices of the square grid are transformed into the centers of the polygons by simply multiplying the coordinates of points in the square grid by the 2 x 2 square matrix (a sheer metrix)
A = a*[ sqrt(3)/2 0;
1/2 1 ]
where a is a parameter of the hexagonal grid, the distance between the centers of two edge-adjacent hexagons. This provides a way to assign integer indices [m n] to the grid formed by the hexagonal centers. After that, if you are given a point with coordinates [x y] in the hexagonal grid, you can apply the inverse matrix of A
[u; v] = A^(-1)*[x; y]
where
A^(-1) = (2/(a*sqrt(3)))*[ 1 0 ;
-1/2 sqrt(3)/2 ]
([x; y] and [u; v] are column vectors) and then take m = floor(u) and n = floor(v) to determine the integer coordinates (also the indices) [m = floor(u), n = floor(v)] of the upper left corner of the square cell from the square grid (observe that we have chosen the coordinates for both grids to start from the upper left corner). Thus, your point [u, v] is in the square with vertices [m,n] [m+1, n] [m, n+1] [m+1, n+1]
which means that the original point [x y] is in one of the four hexagons whose centers have indices [m,n] [m+1, n] [m, n+1] [m+1, n+1]. So you can use that to check in which of the four hexagons the point [x y] is.
I hope this helps.
Update: Leaving the below comment for posterity
I am now using the code provided here: https://www.redblobgames.com/grids/hexagons/
A really important note, is that your hexagon grid MUST start with the first hexagons mid point at (0, 0) - if it doesn't you get extremely odd results from this, which at first glance appeared as rounding errors (even after accounting for the expected offset). For me, it didn't matter where the first hexagon was positioned, so I just set it to be (0, 0) and it worked great.
Old solution
I'm still hoping for an optimal solution, but I ended up rolling my own which needs only check 6 hexagons per point, with a little overhead (approximately sqrt(m)) needed in addition.
With approximately 3000 points, and 768 hexagons (of which 310 were populated), it correctly assigned the point to the hexagon 100% of the time (as checked against a brute force approach) and took 29 milliseconds, compared to ~840 with brute force.
To start with, I store the hexagons in a map where the key is "${column},${row}". The columns technically overlap, so for the 0th row, the 0th column starts at -0.5 * hexWidth, and for row 1, the 0th column starts at 0px.
Next, I start from the position of the top left hexagon, item "0,0", which should also be at position 0, and increment y by either the height of the hexagon, or the edge length of the hexagon accordingly. When the y is > the points y, I've found the probable row, I then check the row above and below.
For the column within the row, I take the both the Math.floor and Math.ceil of x / hexWidth.
Doing this gives 6 hexagons to check, from this point the solution is identical to the solution in the question.
In theory, this could be used to just look up the correct hexagon, using the x/y position. However in practice, this didn't work for me about 5% of the time with off by 1 errors, likely a rounding problem.
Some other things I looked at:
As suggested by #jason-aller, https://www.redblobgames.com/grids/hexagons/#rounding. Unfortunately, this seems to assume some form of transformation on the hex grid (rotations) and is not easy to follow - continually referencing functions which have yet to be defined.
QuadTree (various implementations) unfortunately, this returned approximately 100 "potential matches" for each point - so the performance improvement was not good. I'm aware that insertion order changes how useful QuadTree is, I tried natural order, sorted by distance from top, left and shuffled, they all performed equally badly. It's likely that an optimal solution with QuadTree would involve populating the tree with the item closest to the mid point, then the items 1/2 from the mid point to each corner, recursively. Too much like hard work for me!

Concept of a sript to calculate mouse velocity

Hi guys:)Could someone explain me this code?I am trying to understand but there is nothing to do.Why this line of code?
Math.sqrt(x_dist*x_dist+y_dist*y_dist)/interval;
Isn't sufficent this?
x_dist+y_dist/interval;
I don't understand the concept of this code...
https://jsfiddle.net/vnodkumar1987/ER8qE/
The first example calculates the hypotenuse, and in so doing achieves an absolute velocity value of the mouse vector.
The second example will give a bad result unless both x_dist and y_dist are positive. In other words, if you were moving down and left, or up and right, the second example would have a subtractive effect, and not represent the true overall velocity. In the case of up and left, the velocity would not only be proportionately incorrect (only useful for comparison purposes), but also result negative sign that you would have to account for. (I am assuming 0,0 represents the upper left of the mouse-able area and x_max,y_max to be the lower right.)
The Math.sqrt may not be necessary if you are just scaling proportionate velocity, but it certainly is if you want to know true pixels/interval. You would also have to take into account how big a variable container you are working with, but I'm sure it would all fit into a double... unless you were looking for extreme precision.
Imagine you travel in a straight line so that you end up at a point 3 miles West, and 4 miles South in exactly 1 hour. The velocity answer is not 3+4=7 miles per hour, nor is it-3+4=1 miles per hour. The correct answer of absolute velocity is the hypotenuse, which would be 5 mph. sqrt(west^2+south^2)
Example #1 would be the proper code. Example #2 could be roughly used if you can ignore the sign, and you needed the code to execute very quickly.
The velocity is distance_travelled/time_taken.
Say the pointer moves from (x1,y1) to (x2,y2) as shown in the figure above. The distance travelled is not the sum of the x and y distances.
Summing up x and y assumes that the pointer went from (x1,y1) to (x2,y1) and then from (x2,y1) to (x2,y2). i.e. the sum of the lengths of the 2 blue lines. But what you need is the length of the black line.
The actual distance travelled is d as shown in the figure. Using Pythagorean theorem, d^2 = x_dist^2 + y_dist^2.
Which leaves you with the line of code you have in the question for the speed
Math.sqrt(x_dist*x_dist+y_dist*y_dist)/interval;
You are making a pythagorean triangle with the two catethus being x_dist and y_dist, which are the distance the mouse moved in each of X and Y axis each frame. What that line of code does is to get the magnitude of the delta position vector of the mouse and divide it by some scalar value.
Also, note that sqrt(a^2 + b^2) does NOT equal a + b.
EDIT: Not velocity, but delta position.

Accounting for vertical slope

I'm not a programmer primarily, so this might be a simple answer.
I'm working on a script in Illustrator where you select three points and then it does stuff. First it makes a triangle. Then, it recreates two of the line segments in the triangle and rotates them 90 degrees. Then, I find the intersect of those points so that I can make a circumcircle.
I'm actually moving along quite well, but the only problem I don't know how to solve at the moment is when two points that comprise the triangle have the same y-coordinates. When I make the perpendicular line, that line is vertical and therefore has no slope. It throws an error.
How do I account for a vertical slope with JavaScript? I was thinking about something along the lines of, "if the slope is NaN, then set the slope value to 9999999" or something like that, but this seemed a bit crude. Any better options?
You could normalise your gradient in the range -1 to 1. Anything larger than 1, or a NaN, is clamped at 1. The same goes for negative numbers, but with -1.

Could you use Html 5 canvas to calculate the distance you travelled along a river?

My thought was that you could draw a line that traversed the river and then if you knew the total distance of the river you divide the line's pixel length by the distance.
So if your line was 760px and the distance of the river was 20 miles then 760 / 20 = 38px = 1 mile.
Of course if my line was just a straight line or a series of lines this would be fairly simple. However, I would like my line to reflect the contours of the river and as such would be curved in places.
Firstly, is this a good method for plotting distance travelled along a river? If not what would work better (i have a feeling my maths is wrong!).
If this is a good method how would i take into account the curved nature of the line and how this might affect the pixel length of the line?
Calculating the length of a river is similar to calculating the Length of an Arc
.
Even if you draw the river exactly as you want it in an canvas(or in any Raster Image for that matter), and then count the amount of blue pixels, you would only be able to get an approximate answer as close as canvaswidth / riverdistance.
I wouldn't use miles (because its too crude). Use something shorter instead (I'd use meters, but ymmv).
Then just draw a line along the curvature of the river and count the pixels of that line, every pixel represents a given distance. (e.G. one pixel could represent 150 meters)

Categories

Resources