vue实现井字棋游戏
编程学习 2021-07-04 14:06www.dzhlxh.cn编程入门
这篇文章主要为大家详细介绍了vue实现井字棋游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了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。
上一篇:原生js实现表格翻页和跳转
下一篇:js实现移动端图片滑块验证功能
编程语言
- Win10 PC创意者更新慢速版15048改进内容与已知问题
- 用纯CSS3实现网页中常见的小箭头
- 神舟笔记本问题集锦
- Bellnames常用操作说明
- 揭秘手机淘宝搜索排序的影响因素
- XHTML入门学习教程-网页Head和DTD
- 笔记本光驱保养常用知识
- hzhost虚拟主机系统致命漏洞
- 电脑无线网络出现红色叉叉无线网卡打不开的六
- 16项评比不得不看 机箱哪些功能最实用
- AI怎么绘制一个呲牙的qq表情-
- 红帽指点杆机械键盘 TEX Yoda上手体验测评
- 笔记本电脑保养常识有哪些-笔记本保养常识总结
- cdr怎么设计圆角矩形效果的图标-
- 在XSLT样式表中声明命名空间小结
- Fireworks教程-常用操作技巧总结