grid.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. function Grid(size) {
  2. this.size = size;
  3. this.cells = this.empty();
  4. }
  5. Grid.prototype = {
  6. // 构造一个空的矩阵[[null,..,size.length],[]]
  7. empty: function() {
  8. var cells = [];
  9. for (var x = 0; x < this.size; x++) {
  10. var row = cells[x] = [];
  11. for (var y = 0; y < this.size; y++) {
  12. row.push(null);
  13. }
  14. }
  15. // [[{x:0,y:0},{x:0,y:1}],[]]
  16. return cells;
  17. },
  18. // 在空格子中随机挑选出一个格子
  19. randomAvailableCell: function() {
  20. var cells = this.availableCells();
  21. // 存在可填充的格子
  22. if (cells.length) {
  23. return cells[Math.floor(Math.random() * cells.length)];
  24. }
  25. },
  26. // 获取可填充的格子坐标
  27. availableCells: function() {
  28. var cells = [];
  29. for (var i = 0; i < this.size; i++) {
  30. for (var j = 0; j < this.size; j++) {
  31. // 当前格子无内容
  32. if (!this.cells[i][j]) {
  33. cells.push({
  34. x: i,
  35. y: j
  36. });
  37. }
  38. }
  39. }
  40. return cells;
  41. },
  42. // 是否存在空单元格
  43. cellsAvailable: function() {
  44. return !!this.availableCells().length;
  45. },
  46. cellAvailable: function(cell) {
  47. return !this.cellContent(cell);
  48. },
  49. insertTile: function(tile) {
  50. this.cells[tile.x][tile.y] = tile;
  51. },
  52. removeTile: function(tile) {
  53. this.cells[tile.x][tile.y] = null;
  54. },
  55. /*
  56. * 获取单元格内容
  57. * @param {object} cell {x:0,y:0} 单元格坐标
  58. */
  59. cellContent: function(cell) {
  60. if (this.withinBounds(cell)) {
  61. return this.cells[cell.x][cell.y] || null;
  62. } else {
  63. return null;
  64. }
  65. },
  66. /*
  67. * 空单元格,格子还未填充数字
  68. */
  69. emptyCell: function(cell) {
  70. return !this.cellContent(cell);
  71. },
  72. withinBounds: function(cell) {
  73. return cell.x >= 0 && cell.x < this.size && cell.y >= 0 && cell.y < this.size;
  74. },
  75. eachCell: function(callback) {
  76. for (var x = 0; x < this.size; x++) {
  77. for (var y = 0; y < this.size; y++) {
  78. callback(x, y, this.cells[x][y]);
  79. }
  80. }
  81. }
  82. }
  83. module.exports = Grid;