Saturday, March 9, 2019

algorithm - Logic behind a bejeweled-like game


In a prototype I am doing, there is a minigame similar to bejeweled. Using a grid that is a 2d array (int[,]) how can I go about know when the user formed a match? I only care about horizontally and vertically.


Off the top of my head I was thinking I would just look each direction. Something like:


int item = grid[x,y];
if(grid[x-1,y]==item)
{

int step=x;
int matches =2;
while(grid[step-1,y]==item)
{
step++;
matches++
}
if(matches>2)
//remove all matching items
}

else if(grid[x+1,y]==item
//....
else if(grid[x,y-1==item)
//...
else if(grid[x,y+1]==item)
//...

It seems like there should be a better way. Is there?



Answer



Loop through each item in the same axis (x or y), if they are the same as the previous item them increment matches. When the next item becomes different, check if matches is or greater than 3, call a function that removes matching items, and continue.



AS3 code:


var grid:Array = [[2,3,2,2,2,4],
[ .. ]]; //multidimensional array
var matches:uint;
var gemType:uint;
for(col = 0; col < grid.length; col++){
matches = 0;
gemType = 0; //Reserve 0 for the empty state. If we make it a normal gem type, then only 2 are needed to match for the start.
for(i = 0; i < grid[0].length; i++){
if(grid[col][i] == gemType){

matches++;
}
if(grid[col][i] != gemType || i == grid[0].length - 1){ //subtract 1 because arrays start at 0
if(matches >= 3){
removeMatches(blah);
}
gemType = grid[col][i];
matches = 1;
}
}

}

This is only for the x axis, for y, grid[col][i] would become grid[i][row], etc. I'm sure you can figure that out :)


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...