注:未做死亡判断,小蛇碰到屏幕边缘会自动返回
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 20px;
height: 20px;
background-color: #6ff;
position: absolute;
left: 0;
top: 0;
border-radius: 50%;
}
.dot {
width: 20px;
height: 20px;
border-radius: 50%;
background: red;
position: fixed;
}
</style>
<body>
<div class="box" style="background: #f00; z-index: 9;"></div>
</body>
<script>
var oBox = document.getElementsByClassName('box');
var speed = 20;
var maxLeft = document.documentElement.clientWidth - oBox[0].offsetWidth;
var maxTop = document.documentElement.clientHeight - oBox[0].offsetHeight;
var timer;
var defaultLen = 8;
createDiv(defaultLen);
document.onkeydown = function (e) {
var ev = event || e;
var keyCode = ev.keyCode || ev.which;
if (keyCode < 37 || keyCode > 40) {
return false;
}
start(keyCode);
}
function start(keyCode) {
clearInterval(timer);
timer = setInterval(function () {
var left = oBox[0].offsetLeft;
var top = oBox[0].offsetTop;
switch (keyCode) {
case 37: {
left -= speed;
};
break;
case 38: {
top -= speed;
};
break;
case 39: {
left += speed;
};
break;
case 40: {
top += speed;
};
}
// 边界条件
if (left < 0) {
// left = 0
keyCode = 39;
// restart()
}
if (left > maxLeft) {
// left = maxLeft
keyCode = 37;
}
if (top < 0) {
// top = 0
keyCode = 40;
}
if (top > maxTop) {
// top = maxTop
keyCode = 38;
}
// console.log(left);
oBox[0].style.left = left + 'px';
oBox[0].style.top = top + 'px';
if (left === dotX && top === dotY) {
// console.log('迟到了');
console.log('吃到了');
oDot.remove();
createDot();
createDiv();
// oDot.className = "box";
// document.body.appendChild(oDot);
}
for (var i = oBox.length - 1; i > 0; i--) {
oBox[i].style.left = oBox[i - 1].style.left;
oBox[i].style.top = oBox[i - 1].style.top;
}
}, 100);
}
function restart() {
oBox[0].style.left = 0;
oBox[0].style.top = 0;
document.body.innerHTML = '';
document.body.appendChild()
createDiv(defaultLen);
start();
}
var oDot;
var dotX;
var dotY;
function createDot() {
console.log('创建dot');
oDot = document.createElement('div');
oDot.className = 'dot';
dotX = 20 * (Math.round(Math.random() * 30));
dotY = 20 * (Math.round(Math.random() * 30));
oDot.style.left = dotX + 'px'
oDot.style.top = dotY + 'px'
document.body.appendChild(oDot);
// createDiv();
}
function createDiv(n = 1) {
for (var i = 0; i < n; i++) {
var oDiv = document.createElement('div');
oDiv.className = "box";
document.body.appendChild(oDiv);
}
}
createDot();
</script>