0

I have a grid based game 8 squares by 8 squares giving 64 pieces in total, these pieces are stored in an array. I'm having a problem where certain grid squares are being populated twice so I need to check the array for duplicate co-ordinates.

Below code gives the x, y grid co-ordinates of each piece - testX and testY, I'm not sure how I would go about running through this array to remove duplicates. If there are duplicates pieces I need to keep the first encountered and remove any subsequent duplicates. I'm using jQuery if that helps.

function checkGrid() {

    var x;

    for (x = 0; x < grid.length; x++) {

    var testY= grid[x].getY();
    var testX = grid[x].getX();

    }
}
4

1 回答 1

1

您可以考虑使用对象而不是数组:

var grid = {};

function setGridValue(x,y, value){
    var key = x + '-' + y;
    grid[key] = value;
}

function getGridValue(x,y){
    var key = x + '-' + y;
    return grid[key];
}

像这样的东西。然后,如果您更改网格位置的值,则无需检查重复项。

编辑。

由于您无法更改为对象,因此您应该在插入它们时找到现有项目。您没有发布将项目添加到网格的代码,但是您可以执行以下操作:

function setItem(x, y, value){
   var item;
   // check for existing item in array
   for(var i = 0; i < grid.length; i++){
       if(grid[i].getX() === x && grid[i].getY() === y){
           item = grid[i];
           break;
       }
   }
   // if no existing item, create new one
   if(!item){
      item = new GridItem(x,y,value);  // dont know what is in the grid...
      grid.push(item);
   } else {
      // update existing item here...
   }
}
于 2013-02-14T04:08:57.807 回答