您的位置:首页 > 产品设计 > UI/UE

Vue.js笔记-数字拼图小游戏

2016-11-02 09:56 519 查看
<!DOCTYPE html>

<html lang="en">

<head>
<meta charset="UTF-8">
<title>game</title>
<script type="text/javascript" src="vue.js"></script>
<style>
body {
 font-family: Arial, "Microsoft YaHei"; 
 color: #fff;
}
 
.box {
 width: 400px;
 margin: 50px auto 0;
}
 
.puzzle-wrap {
 width: 410px;
 height: 410px;
 margin-bottom: 40px;
 padding: 0;
 background: #ccc;
 list-style: none;
}
 
.puzzle {
 float: left;
 width: 100px;
 height: 100px;
 font-size: 20px;
 background: #f90;
 text-align: center;
 line-height: 100px;
 border: 1px solid #ccc;
 box-shadow: 1px 1px 4px;
 text-shadow: 1px 1px 1px #B9B4B4;
 cursor: pointer;
}
 
.puzzle-empty {
 background: #ccc;
 box-shadow: inset 2px 2px 18px;
}
 
.btn-reset {
 width: 410px;
 height: 40px;
 background: #f90;
 border: none;
 color: #fff;
 outline: none;
}
</style>

</head>

<body>

<div class="box" id="demo">
<ul class="puzzle-wrap">
<li :class="{'puzzle':true,'puzzle-empty':!puzzle}" v-for="puzzle in puzzles" v-text="puzzle" @click="moveFn($index)"></li>
</ul>
<button class="btn btn-warning btn-block btn-reset" @click = "render">重置</button>
</div>

<script type="text/javascript">
new Vue({
el:'#demo',
data:function(){
return{
puzzles:[]
}
},
methods:{
render(){
var puzzleArr = []
for (var i = 1; i < 16; i++) {
puzzleArr.push(i)//生成1-15数字的数组
}
puzzleArr = puzzleArr.sort(()=>{
return Math.random()-0.5//随机打算数组,这里利用Math.random()生成一个 0 ~ 1 之间的随机数,再减去0.5,这样就会有一半概率返回一个小于 0 的值,一半概率返回一个大于0的值,就保证了生成数组的随机性,实现了动态随机生成数字格子的功能。
})
this.puzzles = puzzleArr
this.puzzles.push('')//空白格子
},

moveFn(index){
var curNum = this.puzzles[index],//获取点击位置及上下左右的值
leftNum = this.puzzles[index-1],
rightNum = this.puzzles[index+1],
topNum = this.puzzles[index-4],
bottomNum = this.puzzles[index+4];

if (leftNum === '') {
this.puzzles.$set(index-1,curNum)//和空位置交换数值
this.puzzles.$set(index, '')
}
else if (rightNum === '') {
this.puzzles.$set(index+1,curNum)
this.puzzles.$set(index, '')
}
else if (topNum === '') {
this.puzzles.$set(index-4,curNum)
this.puzzles.$set(index, '')
}
else if (bottomNum === '') {
this.puzzles.$set(index+4,curNum)
this.puzzles.$set(index, '')
}
this.passFn()
},
//检验是否过关
passFn(){
if (this.puzzles[15]==='') {//当数组最后一个元素为空时,截取数组的前15个元素生成一个新的数组,通过every方法循环截取后数组的每一个元素是否等于其index+1,array.every(callback[,thisObject]);callback:函数用来测试每个元素thisObject:对象作为该执行回调时使用
const newPuzzels = this.puzzles.slice(0,15)
const isPass = newPuzzels.every((e,i) => e === i+1)
if (isPass) {
alert('恭喜,闯关成功!')
}
}
}
},
ready(){
this.render()
}
})
</script>

</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: