cocos creator从零开发五子棋(08)-胜负判断
棋盘原点是左下角,每个落子根据所在行列计算出id
存储在chessMap
属性中。判断胜负时,依次把最后落子左至右
,下至上
、左下到右上
、左上到右下
两边各4
个棋子加上自己共9
个棋子取出来,判断是否有连续5
个颜色一样的棋子。
编辑scripts/Game.ts
,添加初始化胜负ui
相关方法。
private _panelSettle: cc.Node
private panelSettleInit() {
this._panelSettle = this.node.getChildByName('panelSettle')
this._panelSettle.active = false
}
private panelSettleShow(msg: string) {
this._panelSettle.getChildByName('lblMsg').getComponent(cc.Label).string = msg
this._panelSettle.getChildByName('btnOk').on('click', () => cc.game.restart())
this._panelSettle.active = true
}
添加判断胜负方法。
private checkWin(col: number, row: number) {
let datas: Chess[] = []
// 左至右
for (let i = row - 4; i <= row + 4; i++) {
datas.push(this.chessMap.get(this.gridToIdx(col, i)))
}
if (this.checkWin2(datas)) return
// 下至上
datas = []
for (let i = col - 4; i <= col + 4; i++) {
datas.push(this.chessMap.get(this.gridToIdx(i, row)))
}
if (this.checkWin2(datas)) return
// 左下到右上
datas = []
for (let i = - 4; i <= 4; i++) {
datas.push(this.chessMap.get(this.gridToIdx(col + i, row + i)))
}
if (this.checkWin2(datas)) return
// 左上到右下
datas = []
for (let i = - 4; i <= 4; i++) {
datas.push(this.chessMap.get(this.gridToIdx(col - i, row + i)))
}
if (this.checkWin2(datas)) return
if (this.chessMap.size == GRID_SIZE * GRID_SIZE) {
this.panelSettleShow('平局')
}
}
private checkWin2(datas: Chess[]): boolean {
for (let i = 0; i <= datas.length - 4; i++) {
// 判断是否等于当前下的棋子
if (datas[i]?.chessName != this._turn) continue
// 到这里就是有一颗棋子了
let sameNum = 1
for (let j = i + 1; j < datas.length; j++) {
if (datas[j]?.chessName != this._turn) break
sameNum++
if (sameNum >= 5) {
const msg = this._turn == CHESS_BLACK ? '黑棋赢了' : '白棋赢了'
this.panelSettleShow(msg)
return true
}
}
}
return false
}
编辑init
方法,末尾修改如下,主要是初始化胜负ui
并在落子结束后判断胜负。
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.checkWin(col, row)
this.turn()
})
this.panelSettleInit()
本作品采用《CC 协议》,转载必须注明作者和本文链接