grid.js 1.5 KB

1
  1. function Grid(e,t){this.size=e,this.cells=t?this.fromState(t):this.empty()}Grid.prototype.empty=function(){var e=[];for(var t=0;t<this.size;t++){var n=e[t]=[];for(var r=0;r<this.size;r++)n.push(null)}return e},Grid.prototype.fromState=function(e){var t=[];for(var n=0;n<this.size;n++){var r=t[n]=[];for(var i=0;i<this.size;i++){var s=e[n][i];r.push(s?new Tile(s.position,s.value):null)}}return t},Grid.prototype.randomAvailableCell=function(){var e=this.availableCells();if(e.length)return e[Math.floor(Math.random()*e.length)]},Grid.prototype.availableCells=function(){var e=[];return this.eachCell(function(t,n,r){r||e.push({x:t,y:n})}),e},Grid.prototype.eachCell=function(e){for(var t=0;t<this.size;t++)for(var n=0;n<this.size;n++)e(t,n,this.cells[t][n])},Grid.prototype.cellsAvailable=function(){return!!this.availableCells().length},Grid.prototype.cellAvailable=function(e){return!this.cellOccupied(e)},Grid.prototype.cellOccupied=function(e){return!!this.cellContent(e)},Grid.prototype.cellContent=function(e){return this.withinBounds(e)?this.cells[e.x][e.y]:null},Grid.prototype.insertTile=function(e){this.cells[e.x][e.y]=e},Grid.prototype.removeTile=function(e){this.cells[e.x][e.y]=null},Grid.prototype.withinBounds=function(e){return e.x>=0&&e.x<this.size&&e.y>=0&&e.y<this.size},Grid.prototype.serialize=function(){var e=[];for(var t=0;t<this.size;t++){var n=e[t]=[];for(var r=0;r<this.size;r++)n.push(this.cells[t][r]?this.cells[t][r].serialize():null)}return{size:this.size,cells:e}}