新建scripts/Game.ts
,内容如下,把它挂载到Canvas
节点上。拖拽Canvas/grid/bg
节点到bgNode
属性上,拖拽Canvas/grid/root
节点到rootNode
属性上。
import Grid from "./Grid"
const { ccclass, property } = cc._decorator
const GRID_SIZE = 4
@ccclass
export default class Game extends cc.Component {
@property(cc.Node)
private bgNode: cc.Node = null
@property(cc.Node)
private rootNode: cc.Node = null
private grids: Grid[][] = []
private gridsReversed: Grid[][] = []
protected onLoad(): void {
this.init()
}
private init() {
const gridPrefab = this.rootNode.children[0]
gridPrefab.active = false
let idx = 0
for (let col = 0; col < GRID_SIZE; col++) {
this.grids[col] = []
for (let row = 0; row < GRID_SIZE; row++) {
const grid = cc.instantiate(gridPrefab)
grid.parent = this.rootNode
const gridComp = grid.getComponent(Grid)
gridComp.init(this.bgNode.children[idx].getPosition())
grid.active = true
gridComp.num = Math.pow(2, idx + 1)
this.grids[col][row] = gridComp
idx++
}
}
gridPrefab.destroy()
for (let col = 0; col < GRID_SIZE; col++) {
this.gridsReversed[col] = []
for (let row = 0; row < GRID_SIZE; row++) {
this.gridsReversed[col][row] = this.grids[row][col]
}
}
}
}
运行项目,会发现16
个格子依次显示了从2
到65536
这16
个数字,并且有不同的文字颜色和背景颜色。
这是因为加了调试的代码,编辑scripts/Game.ts
,删除下面两行调试代码,再次运行项目就不会显示任何格子了。
编辑scripts/Game.ts
,添加DURATION
常量设置缓动时间。
const GRID_SIZE = 4
const DURATION = 0.1
添加randGrid
方法用于随机显示格子。
private randGrid() {
const randGrids: Grid[] = []
for (const rowGrids of this.grids) {
for (const grid of rowGrids) {
if (!grid.num) randGrids.push(grid)
}
}
const grid = randGrids[this.randRange(0, randGrids.length - 1)]
grid.num = 2
grid.node.scale = 0
cc.tween(grid.node).to(DURATION, { scale: 1 }).start()
}
// 整数范围随机 [min, max]
private randRange(min: number, max: number): number {
return Math.round(Math.random() * (max - min) + min)
}
添加start
方法,调用randGrid
方法两次,这样程序运行时就会随机显示两个格子。
protected start(): void {
this.randGrid()
this.randGrid()
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。