Vue 实现人机五子棋
发布于 2018-12-13|
Vue 实现人机五子棋,Canvas绘图,不难理解直接上码
> * [预览效果](https://unnue.com/game/gobang)> * [github源码](https://github.com/jigsaw-china/unnue-nuxt/blob/master/pages/game/gobang.vue)
* 核心代码
``` javascript
export default {
data () {
return {
chess: {},
context: {},
chessBoard: [], // 记录是否走过
me: true,
count: 0, // 所有赢法数量
wins: [], // 赢法数组
myWin: [], // 我方赢法的统计数组
computerWin: [], // 计算机赢法的统计数组
over: false,
}
},
mounted () {
setTimeout(_ => {
this.init()
})
},
methods: {
// 初始化
init () {
this.chess = this.$refs.canvas
this.context = this.chess.getContext("2d")
this.drawImage( _ => {
this.drawChessBoard()
})
this.fillArray()
},
// 填充数组
fillArray () {
// 是否走过
for (let i = 0; i 3; j--) {
for (let k = 0; k {
context.drawImage(img, (450 - img.width)/2, (450 - img.height)/2, img.width, img.height)
callback()
}
},
// 绘制棋盘
drawChessBoard () {
const { context } = this
context.strokeStyle = '#bfbfbf'
for (let i = 0; i max) {
max = myScore[i][j]
u = i
v = j
} else if (myScore[i][j] === max) {
if (computerScore[i][j] > computerScore[u][v]) {
u = i
v = j
}
}
if (computerScore[i][j] > max) {
max = computerScore[i][j]
u = i
v = j
} else if (computerScore[i][j] === max) {
if (myScore[i][j] > myScore[u][v]) {
u = i
v = j
}
}
}
}
}
this.onStep(u, v, false)
this.chessBoard[u][v] = 2
// 统计赢法
for (let k = 0; k < this.count; k++) {
if (this.wins[u][v][k]) {
this.computerWin[k]++
this.myWin[k] = 6
if (this.computerWin[k] === 5) {
alert('计算机赢了')
this.over = true
}
}
}
if (!this.over) {
this.me = !this.me
}
}
}
}
```
慕课网教程视频:[https://www.imooc.com/learn/644](https://www.imooc.com/learn/644)