cocos creator从零开发五子棋(05)-棋子布局调试
编辑scripts/Game.ts
,导入Chess
脚本。
import Chess from "./Chess"
const { ccclass, property } = cc._decorator
添加CHESS_BLACK
和CHESS_WHITE
常量。
const GRID_WIDTH = 50
const CHESS_BLACK = 'black'
const CHESS_WHITE = 'white'
添加chessPrefab
属性。
@property(cc.Prefab)
private chessPrefab: cc.Prefab = null
@property(cc.Node)
private bgNode: cc.Node = null
拖拽chess
预设到对应属性上。
添加如下方法。
// 检查输赢的时候格子有越界情况,在这里判断,返回一个不在正常范围内的索引 [0, 224(15 * 15 -1)]
private gridToIdx(col: number, row: number): number {
if (col < 0 || col >= GRID_SIZE || row < 0 || row >= GRID_SIZE) return -1
return col * GRID_SIZE + row
}
private gridToPos(col: number, row: number): cc.Vec2 {
return cc.v2(row * GRID_WIDTH + GRID_WIDTH / 2, col * GRID_WIDTH + GRID_WIDTH / 2)
}
private posToGrid(pos: cc.Vec2): number[] {
return [Math.floor(pos.y / GRID_WIDTH), Math.floor(pos.x / GRID_WIDTH)]
}
// 棋盘随机显示所有棋子
private showAll() {
for (let col = 0; col < GRID_SIZE; col++) {
for (let row = 0; row < GRID_SIZE; row++) {
const chess = cc.instantiate(this.chessPrefab)
chess.parent = this.rootNode
chess.setPosition(this.gridToPos(col, row))
const name = this.randRange(0, 1) == 1 ? CHESS_BLACK : CHESS_WHITE
const chessComp = chess.getComponent(Chess)
chessComp.init(name)
}
}
}
// 整数范围随机 [min, max]
private randRange(min: number, max: number): number {
return Math.round(Math.random() * (max - min) + min)
}
添加start
方法。
protected onLoad(): void {
this.init()
}
protected start(): void {
this.showAll()
}
运行项目,所有格子都随机绘制了棋子。
因为只是调试,删除调试代码。
protected start(): void {
}
本作品采用《CC 协议》,转载必须注明作者和本文链接