How should I get adjacent blocks of the same color?

algorithm, javascript, jquery

Solution

Your 2d array is really nested arrays. You need to only check the level of the array that is possibly going out of bounds:

var n = !!grid[x][y-1]?grid[x][y-1]:false;
var s = !!grid[x][y+1]?grid[x][y+1]:false;
var e = !!grid[x-1]?grid[x-1][y]:false;   // Instead of !!grid[x-1][y]
var w = !!grid[x+1]?grid[x+1][y]:false;   // Instead of !!grid[x+1][y]

In other words, when you do `array[x][y]`, javascript first retrieves `array[x]`, and then looks for index `[y]` in that retrieved array. In your case, the first lookup is undefined (`grid[x-1]`), so it cannot look up `grid[x-1][y]`. You are checking for undefined on the last step, when the first step is undefined.

Demo: http://jsfiddle.net/jtbowden/qWktv/

Also, if you `$(c).addClass('active')` at the beginning of `parse_quad_tree`, you will be able to highlight single blocks, and you don't have to call `.addClass('active') for each neighbor because it will happen at the beginning of the recursion.

Demo: http://jsfiddle.net/jtbowden/qWktv/1/

Problem

I'm trying to make a simple color matching game and I want to find a way to select groups of blocks of the same color. This is the fiddle I'm working on, and if you run it you will see that there are issues when I try to mouse over elements at the edges of the game area, telling me that it's trying to use undefined variables If you check below, at the `parse_quad_tree()` function you'll see I handle the case of undefined vars, but since it brakes, it means I'm wrong somewhere... Thank you for your time

Original source