文章目录
一、找空闲位置
- 编写一个找
ROWS * ROWS
块中空闲位置的函数getEmptyLocations()
,返回值为一个表示空闲位置的数组。
getEmptyLocations() {
let locations = [];
for (let i = 0; i < ROWS; ++i) {
for (let j = 0; j < ROWS; ++j) {
if (this.blocks[i][j] == null) {
locations.push({ x: i, y: j });
}
}
}
return locations;
},
二、随机生成2或4的块
- 首先在
game.js
添加常量随机数字NUMBERS数组
。
const NUMBERS = [2, 4];
- 因为在游戏开始时需要有一些随机数字块,因此在
init()方法
中添加addBlock()
方法,并循环调用ROWS-1
次。
init() {
...
for (let i = 0; i < ROWS - 1; ++i) {
this.addBlock();
}
},
- 编写
addBlock()方法
,先调用getEmptyLocations()
找到当前所有空闲位置,如果此时没有空闲位置,直接返回false
,如果有空闲位置则从其中随机选择一个位置,在该位置生成NUMBERS数组中随机数的block
,并将block保存到blocks数组
,将该随机数保存到number数组
,返回true
。
addBlock() {
let locations = this.getEmptyLocations();
if (locations.length == 0) {
return false;
} else {
let location = locations[Math.floor(Math.random() * locations.length)];
let x = location.x;
let y = location.y;
let position = this.positions[x][y];
let block = cc.instantiate(this.blockPrefab);
block.width = this.blockSize;
block.height = this.blockSize;
this.bg.addChild(block);
block.setPosition(position);
let number = NUMBERS[Math.floor(Math.random() * NUMBERS.length);
block.getComponent('block').setNumber(number);
this.blocks[x][y] = block;
this.data[x][y] = number;
return true;
}
},
- 预览多次可看到每次生成不同的初始数字块。