cocos creator从零开发五子棋(05)-棋子布局调试

编辑scripts/Game.ts,导入Chess脚本。

import Chess from "./Chess"

const { ccclass, property } = cc._decorator

添加CHESS_BLACKCHESS_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 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!