vue实现井字棋游戏
#代码知识 发布时间: 2026-01-12
本文实例为大家分享了vue实现井字棋游戏的具体代码,供大家参考,具体内容如下

之前看react的教程时看到的小游戏,试着用vue做一个。右边的winner提示胜者,还没有胜者时提示下一个棋子的种类。restart按钮点击可重新开始。go to step可跳转到第n步。
html:
<div id="app">
<ul id="board" class="white normal">
<li class="square" v-for="i, idx in datas" @click=set(idx)>{{i}}</li>
</ul>
<div id="console">
<div id="hint" class="white">{{hint}}</div>
<input type="button" class="white" id="restart" value="restart" @click="init()"/>
<ul id="history" class="normal">
<li class="history" v-for="i, idx in history">
<input type="button" class="white" :value="'go to step' + (idx + 1)" @click=jump(idx) />
</li>
</ul>
</div>
</div>
css:
<style type="text/css">
body {
background: #5af;
}
.white {
background: #fff;
border-radius: 11px;
outline: none;
border: none;
}
.normal {
list-style: none;
padding: 0px;
margin: 0px;
}
#app {
display: flex;
justify-content: space-between;
width: 450px;
height: 306px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
#board {
display: flex;
width: 306px;
height: 306px;
flex-wrap: wrap;
overflow: hidden;
}
#hint {
width: 100px;
height: 22px;
text-align: center;
margin: 10px;
}
#restart {
width: 70px;
height: 22px;
margin: 10px;
}
#history,
.history {
margin: 5px;
}
.square {
height: 100px;
width: 100px;
border: #ebebeb solid 1px;
flex: 0 0 auto;
font-size: 50px;
font-weight: 900;
line-height: 100px;
text-align: center;
}
</style>
js:
new Vue({
el: '#app',
data: {
datas: Array(9).fill(''),
history: [],
next: true,
winner: '',
cases: [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
]
},
methods: {
//放置棋子
set(idx) {
if (!this.datas[idx] && !this.winner) {
this.$set(this.datas, idx, this.next_player);
this.history.push({
status: [...this.datas],
player: this.next
});
if (this.is_win(this.next_player)) {
this.winner = this.next_player;
}
this.next = !this.next;
}
},
//跳转到第n步
jump(idx) {
this.datas = this.history[idx].status;
this.history.splice(idx + 1, this.history.length - idx - 1);
this.next = !this.history[idx].player;
this.winner = this.is_win('O')
? 'O'
: this.is_win('X')
? 'X'
: '';
},
//判断是否胜出
is_win(player) {
return this.cases.some(arr => arr.every(el => this.datas[el] === player));
},
//初始化
init() {
this.datas = Array(9).fill('');
this.history = [];
this.next = true;
this.winner = '';
}
},
computed: {
next_player() {
return this.next ? 'O' : 'X';
},
hint() {
return this.winner ? 'winner: ' + this.winner : 'next: ' + this.next_player;
}
}
})
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
代码知识SEO上一篇 : python 两种方法删除空文件夹
下一篇 : python 生成器需注意的小问题
-
SEO外包最佳选择国内专业的白帽SEO机构,熟知搜索算法,各行业企业站优化策略!
SEO公司
-
可定制SEO优化套餐基于整站优化与品牌搜索展现,定制个性化营销推广方案!
SEO套餐
-
SEO入门教程多年积累SEO实战案例,从新手到专家,从入门到精通,海量的SEO学习资料!
SEO教程
-
SEO项目资源高质量SEO项目资源,稀缺性外链,优质文案代写,老域名提权,云主机相关配置折扣!
SEO资源
-
SEO快速建站快速搭建符合搜索引擎友好的企业网站,协助备案,域名选择,服务器配置等相关服务!
SEO建站
-
快速搜索引擎优化建议没有任何SEO机构,可以承诺搜索引擎排名的具体位置,如果有,那么请您多注意!专业的SEO机构,一般情况下只能确保目标关键词进入到首页或者前几页,如果您有相关问题,欢迎咨询!