jquery 简单的别踩白块小游戏

时间:2021-03-30 07:02:59

写写简单的东西,效果如图:

jquery 简单的别踩白块小游戏

1.html代码

     <div class="warp">
<div class="title">
<h3>别踩白块</h3>
<p class="maxScore"></p>
</div>
<ul class="Garea">
</ul>
</div>

2.css代码

 body,
ul,
li,
p {
margin:;
padding:;
} li {
list-style: none;
/*border: 1px solid #000;*/
} .warp {
width: 960px;
margin: 0 auto;
} .title {
text-align: center;
} .Garea {
border: 1px solid #000;
width: 300px;
height: 550px;
margin: 0 auto;
} .Garea li {
height: 90px;
} .Garea li p {
float: left;
width: 73px;
height: 100%;
border: 1px #c9c9c9 solid;
} .black {
background-color: #000;
}

3.js代码,记得先引入jquery

 init(); // 初始化页面黑白块

         function init() {
localStorage.setItem('score', '0'); // 初始化当前得分 var html = ''
for (let i = 0; i < 6; i++) {
html += '<li>';
var random = Math.floor(Math.random() * 3 + 1);
for (let j = 0; j < 4; j++) {
var black = "";
if (j == random) { black = "black" };
html += '<p class="' + black + '" onclick="cai(this);"></p>';
}
html += '</li>';
}
$("ul").prepend(html)
if (localStorage.getItem('maxScore')) {
$('.maxScore').html('历史最高分为:' + localStorage.getItem('maxScore'))
}
}
function cai(obj) {
//判断是否点击最后一行
if ($(obj).parent().index() != '5') {
return false;
} //判断是否踩到白块
if (obj.className == "") {
if (localStorage.getItem('score') > localStorage.getItem('maxScore') - 1) {
alert("Game Over! You get the higher score is " + localStorage.getItem('score'));
} else {
alert("Game Over! Your score is " + localStorage.getItem('score'));
}
$('.maxScore').html('历史最高分为:' + localStorage.getItem('maxScore'))
localStorage.setItem('score', '0')
//游戏结束!
} else {
//游戏继续
$(obj).parent().remove();
var p = "";
var random = Math.floor(Math.random() * 4 + 1);
for (var i = 4; i >= 1; i--) {
var black = "";
if (i == random) { black = "black" };
p += '<p class="' + black + '" onclick="cai(this);"></p>';
}; var html = '<li>' + p + '</li>'
$("ul").prepend(html); if (!localStorage.getItem('maxScore')) {
localStorage.setItem('maxScore', '0');
} if (localStorage.getItem('score')) {
localStorage.setItem('score', localStorage.getItem('score') * 1 + 1)
if (localStorage.getItem('score') * 1 > localStorage.getItem('maxScore') * 1) {
localStorage.setItem('maxScore', localStorage.getItem('score') * 1)
}
}
}
};

完成。