使用vue实现一个井字棋游戏?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
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;
}
}
})
看完上述内容,你们掌握使用vue实现一个井字棋游戏的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。