糖果小游戏
规则:输入总数目,且每次只能拿1-3颗,拿完机器自动拿,谁先拿到0谁就赢;
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>糖果游戏</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<style>
.js {
width: 200px;
height: 100px;
border: 1px solid red;
position: fixed;
left: 50%;
top: 40%;
text-align: center;
}
.txt {
width: 100px;
height: 100px;
margin: auto;
}
</style>
</head>
<body>
<div id="app">
总数量:<input type="number" v-model="all" @input="zs" />
<br />
<br />
拿取数量:<input type="number" v-model="nqsl" />
<input type="submit" @click="op" value="确定" />
<br />
<br />
<div v-for="(item,index) in arr" :key="index">
{{item}}<br /><br />
</div>
<div class="js" :style="`display:${dd}`">
<div class="txt">{{err}}</div>
</div>
</div>
<script type="text/javascript">
var vm = new Vue({
el: "#app",
data: {
all: 20, //总数量
nqsl: 0, //拿取数量
sysl: 10, //剩余数量
arr: [],
dd: "none",
err: "",
},
//创建后
created() {
this.sysl = this.all;
},
methods: {
op() {
if (this.nqsl < 1 || this.nqsl > 3) {
vm.err = "拿取数量不在范围内,请输入1到3的整数!!!";
this.dd = "block";
return
}
if (this.all < 1) {
vm.err = "总数量错误";
this.dd = "block";
return
}
if (this.sysl == 0) {
vm.err = "已结束";
this.dd = "block";
return
}
if (this.nqsl > this.sysl) {
vm.err = "err";
this.dd = "block";
return
}
this.sysl = this.sysl - this.nqsl;
this.arr.push("你拿了" + this.nqsl + "颗,剩余" + this.sysl + "颗。");
if (this.sysl <= 0) {
vm.err = "你赢了!!!";
this.dd = "block";
return
}
let jqn = this.sysl % 4;
if (jqn == 0) {
jqn = Math.random() * 3 + 1;//机器随机获取数量[1,4)
jqn = parseInt(jqn);//获取整数,小数删掉
this.sysl = this.sysl - jqn;
this.arr.push("机器拿了" + jqn + "颗,剩余" + this.sysl + "颗。")
} else {
this.sysl = this.sysl - jqn;
this.arr.push("机器拿了" + jqn + "颗,剩余" + this.sysl + "颗。")
}
if (this.sysl <= 0) {
vm.err = "机器赢了!!!";
this.dd = "block";
return
}
},
zs() {
// console.log(this.all) ;
this.sysl = this.all
}
},
})
</script>
</body>
</html>