编辑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()
})
运行项目,已经可以在棋盘上落子了。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。