Skip to content

Instantly share code, notes, and snippets.

@Lif3line
Last active August 29, 2015 14:02
Show Gist options
  • Save Lif3line/53b32c9ff017d2ba534e to your computer and use it in GitHub Desktop.
Save Lif3line/53b32c9ff017d2ba534e to your computer and use it in GitHub Desktop.
My solution to CodeCombat's Gridmancer Challenge. Attempts to draw the minimum number of rectangles onto the level (used for path finding and what not), manages to find the optimum number too <3
// Calculate positioning of rectangles by using a 2D array with a one-one mapping to the environmenet where a 1 indicates a
// potential mappable square and a 0 represents an unmappable square. Squares are 4mx4m
// Find rectangles by sweeping up then right to find the max possible rectangle for each section
// Adam Hartwell 2014, Idea shamelessly taken from post of the best algorithms for this challenge
var tileSize = 4;
var grid = this.getNavGrid().grid;
var gridArr = [];
var row, counter, x, y;
// Create an array with grid size 4m and each square being 1 to indicate free and 0 otherwise
for(y = 0; y + tileSize < grid.length; y += tileSize) {
row = [];
counter = 0; // For adding array indices
for(x = 0; x + tileSize < grid[0].length; x += tileSize) {
occupied = grid[y][x].length > 0;
if(occupied) {
row[counter] = 0;
} else {
row[counter] = 1;
}
counter++;
}
gridArr.push(row);
}
// Act on nice array that was generated and map to the environment
// Sweep up then right
var xSweep, ySweep, xMax, yTop, valid, height, width, xMiddle, yMiddle;
for(x = 0; x < gridArr[0].length; x++) {
for(y = 0; y < gridArr.length; y++) {
if (!gridArr[y][x]) { continue; } // Skip over impassable grid locations
xSweep = x; // Use current x,y as start position for sweep
ySweep = y;
while (gridArr[ySweep][xSweep]) { ySweep++; } // Sweep up
yTop = ySweep - 1;
valid = true;
// Sweep right (checking each column) until it hits an impass then save biggest previous rectangle
while (valid) {
xSweep++; // Move right one
// Sweep up column
for (ySweep = y; ySweep <= yTop; ySweep++){
if (!gridArr[ySweep][xSweep]){
valid = false;
}
}
}
xMax = xSweep - 1;
// Map to environment
height = (yTop + 1 - y)*tileSize;
width = (xMax + 1 - x)*tileSize;
xMiddle = tileSize*(x+xMax)/2 + tileSize/2;
yMiddle = tileSize*(y+yTop)/2 + tileSize/2;
this.addRect(xMiddle, yMiddle, width, height);
// Remove from array map
for(ySweep = y; ySweep <= yTop; ySweep++) {
for(xSweep = x; xSweep <= xMax; xSweep++) {
gridArr[ySweep][xSweep] = 0;
}
}
this.wait(); // Hover over the timeline to help debug!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment