cocos creator从零开发五子棋(06)-棋盘落子

编辑scripts/Game.ts,添加GRID_INIT常量配置第一个落子的棋子。

const CHESS_WHITE = 'white'

const GRID_INIT = [7, 7]

添加如下成员属性。

@property(cc.Node)
private rootNode: cc.Node = null

// 已下棋的格子
private chessMap: Map<number, Chess> = new Map()

// 该谁下棋了(black | white)
private _turn: string
// 最后下的棋子(有 红点 标识)
private _lastChess: Chess

添加如下方法。

private turn() {
    this._turn = this._turn == CHESS_BLACK ? CHESS_WHITE : CHESS_BLACK
}

private drawChess(col: number, row: number) {
    const idx = this.gridToIdx(col, row)

    const chess = cc.instantiate(this.chessPrefab)
    chess.parent = this.rootNode
    chess.setPosition(this.gridToPos(col, row))

    if (this._lastChess) {
        this._lastChess.redHide()
    }

    const chessComp = chess.getComponent(Chess)
    chessComp.init(this._turn)
    chessComp.redShow()

    this.chessMap.set(idx, chessComp)
    this._lastChess = chessComp
}

修改start方法。

protected start(): void {
    this._turn = CHESS_BLACK
    this.drawChess(GRID_INIT[0], GRID_INIT[1])
    this.turn()
}

修改init方法,末尾添加如下代码。

this.rootNode.on(cc.Node.EventType.TOUCH_START, (event: cc.Event.EventTouch) => {
    const pos = this.rootNode.convertToNodeSpaceAR(event.getLocation())
    const [col, row] = this.posToGrid(pos)

    const idx = this.gridToIdx(col, row)
    if (this.chessMap.has(idx)) return

    this.drawChess(col, row)
    this.turn()
})

运行项目,已经可以在棋盘上落子了。

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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