在正文的第一句加入“我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!”
先放出游戏截图馋一下你们
滚动的月饼,跳跃的死神,尽全力跳起,又在重力的作用下回落。。。这不正是人生奋斗的写照吗?只是, 盛年不重来,一日难再晨。 珍惜奋斗拼搏的时光,珍惜陪在你身边的亲人,兄弟,爱人。
基础框架
- 背景图依旧是采用中秋主题
- 游戏容器就是设置左上角和右下角圆角,加半透明背景色即可,绝对定位的方式居中
- 死神素材来源于网络,定位的方式固定在那里
- 滚动的月饼素材来源于网络,通过动画+js方式实现位移+滚动
- 初始化定时器,得分
<div id="box">
<div class="ground"></div>
<div class="Death"></div>
<div class="score">0</div>
<div class="result"></div>
</div>
判断逻辑
- 监听按键的空格和上箭头事件,更新死神dom的bottom值,来实现向上跳,向下回落采用定时器递减方式回落,每次进来清空上一个定时器,这也是为什么定时器需要声明为全局变量,边界条件处理,当落回地面时,需要清空定时器
let t = null
$(document).on('keydown', function (e) {
if([38,32].includes(e.keyCode)) {
if (t) {
clearInterval(t)
}
let bottom = Number($('.Death').css('bottom').split('px')[0]) + 15
if(bottom > $('#box').height() - 120) bottom = $('#box').height() - 120
bottom = bottom+'px'
$('.Death').css('bottom',bottom)
t = setInterval(function () {
let bottom = Number($('.Death').css('bottom').split('px')[0]) - 5
if(bottom < 40) {
clearInterval(t)
t = null
bottom = 40
}
bottom = bottom+'px'
$('.Death').css('bottom',bottom)
}, 100)
}
})
- 生成滚动月饼,采用封装函数的方式进行生成,动态生成月饼,在滚到最左侧时将月饼dom移除,同时,需要判断是否与死神发生碰撞,发生碰撞,则游戏结束
function initBing () {
let div = $('<div>')
div.addClass('bing')
$('#box').append(div)
div.css('right', Math.ceil(Math.random()*50) + 'px')
let t = setInterval(function () {
let right = Number(div.css('right').split('px')[0]) + 3
let left = div.css('left').split('px')[0]
if (left > DeathLeft && left < (DeathLeft+120)) {
if ($('.Death').css('bottom').split('px')[0] <= 40) {
clearInterval(t)
$('.result').show()
$('.bing').remove()
}
}
if(right > $('#box').width()) {
clearInterval(t)
t = null
div.remove()
score++
$('.score').html(score)
initBing()
}
right = right+'px'
div.css('right',right)
}, 10)
}
初始化
初始化就是 重复调用initBing方法,实现一次产出多个小球
function start () {
$('.result').hide()
score = 0
t = null
initBing()
initBing()
initBing()
}
重新开始
给结果dom绑定点击事件
$('.result').click(start)
就这样,我们的游戏就做完了,本文采用的是非常经典的jquery直接操作dom的这种实现思路,代码即实现,可读性强。