How to suitably avoid RangeErrors when "looking around" this 2D array? - multidimensional-array

I have a 2D array structure to represent a grid of tiles that is a part of the game I am making. One aspect of the game is that the grid is filled in in a somewhat random fashion, based on analysis of a text file. Right from the outset though, I already realised that just leaving it be pretty much randomly done like this without sticking in some kind of validity checks or prevention mechanism, to stop really badly configured grid from forming, would not work out. The main problem I want to avoid is too many tiles that would be untraversable being close together, potentially severing chunks of the grid from the rest.
The idea I came up with to try avoid some really bad grids is to check when assigning a tile value to each "grid square" during generation with logic like this
if (tileBeingInserted.isTraversable()) {
//all is well
return true;
} else {
//we may have a problem, are there too many untraversables nearby?
//Proceed to check all squares "around" the current one.
}
To be clear, checking around the current square means checking the square immediately adjacent in each of the 8 cardinal directions. Now, my problem is that I am trying to reason out how to code this so that it will certainly not give a RangeErrorat any point or at least catch it and recover if it must. As an example, you could clearly take one of the corner squares to be the worst scenario in the sense that only 2 of the squares the algorithm would want to check are within the array's bounds. Naturally, if a RangeErrorhappens for this reason I just want the program to progress onward without issue so the structure
try {
//check1
//check2...8
} catch (RangeError e) {
}
is unacceptable because as soon as a single out of range square is tested the code falls out of the check block. An alternative I thought of, but do not like because of its messiness, would be to individually wrap each check in a try-catch and yes that would work I guess but that's some horrid looking code...so can anyone help me out here? Is there perhaps a different angle from which to come at this problem of avoiding the RangeErrors that I am not seeing?

So my code for testing whether another untraversable tile should be placed has shaped up like this:
bool _tileFitsWell(int tileTypeInt, int row, int col)
{
//...initialise some things, set stuff up
...
if (tile.traversable == true) {
//In this case a new traversable tile is being put in, so no problems.
return true;
} else {
//begin testing what tiles are around the current tile
//Test NW adjacent
if (row > 0 && col > 0) {
temp = tileAt(row - 1, col - 1);
if (!temp.traversable) {
strikeCount++;
}
}
//Test N adjacent
if (row > 0) {
temp = tileAt(row - 1, col - 1);
if (!temp.traversable) {
strikeCount++;
}
}
//Test NE adjacent
if (row > 0 && col < _grid[0].length - 2) {
temp = tileAt(row - 1, col 1);
if (!temp.traversable) {
strikeCount++;
}
}
//Test W adjacent
if (col > 0) {
temp = tileAt(row, col - 1);
if (!temp.traversable) {
strikeCount++;
}
}
}
return strikeCount < 2;
}
The code inside each "initial" if-statement (the ones that check row and col) is a bit pseudocode-ish for simplicity's sake. As I explained in a previous comment, the reason why I don't need to check tiles in the other 4 cardinal directions is since these checks are done while filling the map, tiles in those positions will always be either uninitialised or just out of bounds, depending on what tile the function is called to check at a given time.

Related

Finding the row of an object

I'm trying to create a procedural shape made up of quads.
I want to be able to take any quad and use it's index to find the row that it is in.
Take quad 9 from the image. What sort of function can I use to find the row (in this case it is 2 from a 0-index). What about quad 20?
The rows always change in width by 2 quads, one removed from each side.
Sorry it's a bit convoluted but I'm not sure how to approach the problem.
Assume diameter d and quad number q. I claim the rows go 0 to d-1. Moreover, there are (d/2)(2+d) elements. The easier case is if 0<=q<(d/4)(2+d) in which case we are in the first half. Then the index is trunc((-1+sqrt(1+4*q))/2). This comes from using the observation that row n begins with n(n+1) which could be formally shown with the sum of an arithmetic series, then working backwards and solving the quadratic equation.
On the other hand, if we are in the second half (d/4)(2+d)<=q<(d/2)(2*d) and we solve by taking the offset from the end. Let q' be (d/2)(2+d)-1-q. Apply the above index formula to q' instead of q, and subtract the result from d-1 to get the index of q's row.
I may be off by one here or there, but I think this is the gist of it.
I was thinking since this was posted to a programming site, maybe it would be more logical to give a function one could implement without pulling out a lot of math, and instead just relying on addition. I think it would be easier to follow and harder to mess up (though maybe I underestimate my capability to mess up, and I almost did).
var quadRowIndex = function (diameter, quadNumber) {
//diameter should be a positive even number
//quadNumber should be between 0 and index of last number in last row (inclusive)
var quadIndex = 0; //holds the RowIndex, which the function will return once the row contains quadNumber
var rowStartNum = 0;
var rowLength = 2;
//iterate through first half
while (rowLength <= diameter) {
rowStartNum += rowLength;
if (rowStartNum > quadNumber) {
return quadIndex;
}
quadIndex++;
rowLength += 2;
}
rowLength -= 2;
//iterate through second half if still here
while (rowLength >= 2) {
rowStartNum += rowLength;
if (rowStartNum > quadNumber) {
return quadIndex;
}
quadIndex++;
rowLength -= 2;
}
//still here -- number was too high, return error signal
return -1;
};
console.log(quadRowIndex(6, 9));
console.log(quadRowIndex(6, 20));
console.log(quadRowIndex(6, 100));

Game Maker bounce code not woking

Okay so I am making one of those scrolling shooter Galaga-type game using Game Maker Studio. I created the first enemy and set up a spawner for them. They are supposed to just fly downwards towards your ship. That worked fine. But when I made the 2nd enemy, I wanted to make it move more slowly and side-to-side. I also wanted to make them bounce off the edges of the screen. But it just won't work. I can't figure what the hell the problem is and it it driving me insane. If anyone has any ideas, please, share them with me. If you need any more info on the game i can provide it. Here is the code for the step event of the 2nd enemy:
// Control the enemy
if (y > room_height+16)
{
instance_destroy();
}
// Die code
if (armor <= 0)
{
instance_create(x, y, o_explosion_center);
instance_destroy();
}
// Bounce off edges
if (x >= room_width-16)
{
hspeed = -1;
}
if (x < 16)
{
hspeed = 1;
}
First of all, you didn't say what wasn't working. The code you posted is correct, everything depends on the expected result.
One issue I can see id if this code is used by the two enemies. You want them to have different speeds, but once they bounce, their horizontal speeds will be 1 because you set hspeed to 1 and -1. When you create them, you should set a move_speed variable, and for the bouncing, write in the step event :
hspeed = -1*move_speed //instead of hspeed = -1
and
hspeed = move_speed //instead of hspeed = 1
This way, they will keep their initial speeds.
For more help, could you please explain what doesn't work and post the creation code ?

Pathfinding issues

Ok I am trying to make a dynamic pathing system so the player can move from point A to point B without having predefined paths. Note this game is all text based no graphics. The player can move in 10 directions: up, down, n, e, s, w, sw, se, nw and ne.
The map of the entire world is in a database, each row of the database contains a room or a node, each room/node has directions it's capable of going. The room may not be sequential persay. An Example:
Map Number, Room Number, Direction_N, Direction_S, Direction_E, Direction_W, etc.
1 1 1/3 1/100 1/1381 1/101
The Direction_N indicates it goes to Map 1 Room 3, Direction_S Map 1 Room 100, etc...
Ok, I reworked the code with suggestions (thank you guys by the way!) here is revised code. It seems to find the rooms now, even vast distances! But now the issue is finding the shortest path to the destination, I tried traversing the collection but the path is not coming out right...
In the image link below, I have start point in red square in center and stop point at red square at upper left. This returns visitedStartRooms = 103 and visitedStopRooms = 86, when it's only about 16 rooms.
Quess my missing piece of the puzzle is I am not sure how to sort out the rooms in those collection to gain the true shortest route.
Example of map
Here is the new code
public void findRoute(ROOM_INFO startRoom, ROOM_INFO destinationRoom)
{
Dictionary<ROOM_INFO, bool> visitedStartRooms = new Dictionary<ROOM_INFO, bool>();
Dictionary<ROOM_INFO, bool> visitedStopRooms = new Dictionary<ROOM_INFO, bool>();
List<string> directions = new List<string>();
startQueue.Enqueue(startRoom); // Queue up the initial room
destinationQueue.Enqueue(destinationRoom);
visitedStartRooms.Add(startRoom, true);// say we have been there, done that
visitedStopRooms.Add(destinationRoom, true);
string direction = "";
bool foundRoom = false;
while (startQueue.Count != 0 || destinationQueue.Count != 0)
{
ROOM_INFO currentStartRoom = startQueue.Dequeue(); // remove room from queue to check out.
ROOM_INFO currentDestinationRoom = destinationQueue.Dequeue();
ROOM_INFO startNextRoom = new ROOM_INFO();
ROOM_INFO stopNextRoom = new ROOM_INFO();
if (currentStartRoom.Equals(destinationRoom))
{
break;
}
else
{
// Start from destination and work to Start Point.
foreach (string exit in currentDestinationRoom.exitData)
{
stopNextRoom = extractMapRoom(exit); // get adjacent room
if (stopNextRoom.Equals(startRoom))
{
visitedStopRooms.Add(stopNextRoom, true);
foundRoom = true;
break;
}
if (stopNextRoom.mapNumber != 0 && stopNextRoom.roomNumber != 0)
{
if (!visitedStopRooms.ContainsKey(stopNextRoom))
{
if (visitedStartRooms.ContainsKey(stopNextRoom))
{
foundRoom = true;
}
else
{
destinationQueue.Enqueue(stopNextRoom);
visitedStopRooms.Add(stopNextRoom, true);
}
}
}
}
if (foundRoom)
{
break;
}
}
// start from the start and work way to destination point
foreach (string exit in currentStartRoom.exitData)
{
startNextRoom = extractMapRoom(exit); // get adjacent room
if (startNextRoom.Equals(destinationRoom))
{
visitedStartRooms.Add(startNextRoom, true);
foundRoom = true;
break;
}
if (startNextRoom.mapNumber != 0 && startNextRoom.roomNumber != 0)
{
if (!visitedStartRooms.ContainsKey(startNextRoom))
{
if (visitedStopRooms.ContainsKey(startNextRoom))
{
foundRoom = true;
break;
}
else
{
startQueue.Enqueue(startNextRoom);
visitedStartRooms.Add(startNextRoom, true);
}
}
}
}
if (foundRoom)
{
break;
}
}
}
You have a good start. There are a few basic improvements that will help. First, to be able to reconstruct your path, you should create a new data structure to store visited rooms. But for each entry, you want to store the room, plus the previous room in the path back to the starting point. A good data structure for this would be a dictionary where the key is the room identifier, and the value is the previous room identifier. To know if you've visited a room, you look to see if it exists in that data structure, not your openList queue. With this new structure, you can properly check if you've visited a room, and you can reconstruct the path back by repeatedly looking up the previous room in the same structure until you get to the origination.
The second improvement will increase the performance quite a bit. Instead of just doing a breadth-first search from the start point until you bump into the destination, as you currently do, instead create matching data structures like you have for the start room search, but have them be for the destination room. After you've looked one room away from the start, look one room away from the destination. Repeat this...two rooms away from start, then two rooms away from destination.. etc., working your way out, until you discover a room that has been visited by both your search from start and your search from destination. Build the path from this room back to the start, and back to the destination, and that will be your shortest path.
The problem you are trying to solve is the shortest path problem with unweighted edges or where the weights of all edges are equal. The weight of an edge is the time/cost to move from one room to another. If the cost to move from one room to another varies depending on which pair of rooms you're talking about, then the problem is more complicated, and the algorithm you started with and for which I've suggested modifications, will not work as it is. Here are some links about it:
Shortest path (fewest nodes) for unweighted graph
http://en.wikipedia.org/wiki/Shortest_path_problem
You may also be interested in the A* algorithm which uses a different approach. It uses a hueristic approach to concentrate the search in a subset of the solution space more likely to contain the shortest path. http://en.wikipedia.org/wiki/A%2a_search_algorithm
But A* is probably overkill in your case since the weight of all edges is the same between all rooms.

ConcurrentModificationError on Vector

What I am trying to accomplish here is to remove a "blossom" from the Vector whenever a collision is detected. However, I keep getting a ConcurrentModificationError. It messes up when I try to remove the blossom from the Vector. I have tried doing it many ways. At one point when it was detected that the blossom should be removed, I saved its position in the Vector and then tried to remove it when the next position in the list was being looked at. I think this is the only method that you need to see. Can anybody see what I can do to fix this??
private synchronized void DrawBlossoms(Canvas c) // method to draw flowers on screen and test for collision
{
Canvas canvas = c;
for(Blossom blossom: blossomVector)
{
blossom.Draw(canvas);
if (blossom.hit(box_x,box_y, box_x + boxWidth, box_y + boxHeight, blossomVector) == true)
{
Log.v(TAG, "REMOVE THIS!");
//blossomVector.remove(blossom);
}
}
}
The solution is to use an iterator and synchronize on the Vector.
synchronize(blossomVector)
{
Iterator dataIterator = blossomVector.iterator();
while (dataIterator.hasNext())
{
//... do your stuff here and use dataIterator.remove()
}
}

javascript loop only applying to every other element

i have the following javascript below after i finish an ajax query
all of my images have name="pic"
<script type="text/javascript">
function done() {
var e = document.getElementsByName("pic");
alert(e.length);
for (var i = 0; i < e.length; i++) {
cvi_instant.add(e[i], { shadow: 75, shade: 10 });
}
}
my goal is to apply an image border around using this library:
http://www.netzgesta.de/instant/
the problem is that for some reason this works but it only seem to apply to every other picture instead of every one. any clue why the code above would skip every other element??
EDIT: I added an alert in the loop and it does correctly go 0, 1,2,3,4,5,6 . .
for (var i = 0; i < e.length; i++)
{
alert(i);
cvi_instant.add(e[i], { shadow: 75, shade: 10 });
}
it only seem to apply to every other picture instead of every one
That's a classic sign of destructive iteration.
Consider what happens if, as I'm guessing, the function cvi_instant.add replaces the element named pic with some other element or elements.
getElementsByName returns a ‘live’ NodeList: it is kept up to date every time you make a change to the DOM. So if it had five elements before, after your call to cvi_instant.add it now contains only four: the first node is gone and nodes 1–4 have moved down to positions 0–3.
Now you go around the loop again. i++, so we're looking at element 1. But element 1 is now what was originally element 2! We skipped the original element 1, and we will continue skipping every other element until we reach the end of the (now half as long) list.
Altering a list at the same time as iterating it causes this kind of problem. If the process inside the iteration actually adds elements to the list you can even get an infinite loop!
The quick fix is to iterate the loop backwards. Now you do the last element first, leaving all the other elements in their original positions and causing no skipping:
var e= document.getElementsByName("pic");
for (var i= e.length; i-->0;) {
cvi_instant.add(e[i], { shadow: 75, shade: 10 });
}
Another simple solution if you know you're always going to be removing the element from the list on each call is:
var e= document.getElementsByName("pic");
while (e.length>0) {
cvi_instant.add(e[0], { shadow: 75, shade: 10 });
}
The most general solution is needed when your loop body can do anything to the list, such as inserting new elements named pic at the start of the document or removing other elements from the middle. It is slightly slower but always safe to make a static copy of the list to work from:
function Array_fromList(l) {
var a= [];
for (var i= 0; i<l.length; i++)
a.push(l[i]);
return a;
}
var e= Array_fromList(document.getElementsByName("pic"));
for (var i= 0; i<e.length; i++) {
cvi_instant.add(e[i], { shadow: 75, shade: 10 });
}
My guess is that cvi_instant.add() is doing some incrementing or iteration on the values passed to it. Try doing this instead - it's easier, and I believe it will fix your problem:
function done() {
var e = document.getElementsByName('pic');
for (pic in e) { cvs_instant.add(pic, { shadow: 75, shade: 10 }); }
}
Hi I came across the same problem.
My script was skipping every other
element. I finally solved it by simply
changing the variable name from i to
k in my loop. My guess is therefor
that the variable i is used by
getElementsByTagName internally to
keep track of where it is in the
live nodelist and is leaking out
to the programmers interface somehow.
So its a bug! :-)
-- EDIT:
All of what I claim below appears to be totally wrong. I leave this here as a point for anyone who thought the same :) I tested in FF3. I would love to claim that I saw this behaviour once, in IE, but maybe it was many years ago (come to think of it, it was probably 7 years ago). My memory is probably bad :)
-- OLD:
To slightly expand on my wild guess, if it turns out to be accurate:
From memory, if you don't declare a variable ('var ...') it'll use one from somewhere else.
Thus, without testing, this code:
for(var k = 0; k < 2; k++){
f();
alert("k: " + k);
}
function f () {
k++;
}
Should show the same behaviour. I think TML's solution is quite nice, from a 'defensive coding' point of view, it my analysis turns out to be correct.

Resources