先上简版贪吃蛇(即移动方块)xmind思维导图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<style>
.box {
width: 30px;
height: 30px;
background-color: pink;
position: fixed;
top: 50px;
left: 50px;
}
</style>
<div id="lists" class="box" style="top: 50px;left: 50px;">
</div>
<script>
var lists = document.getElementById("lists")
var x = 5;
var y = 0;
console.log(parseInt(lists.style.top));
console.log(lists.style.left);
setInterval(snake, 20);
function snake() {
var div=document.createElement("div");
div.className="box";//在这里添加类,可以使用style里的设置
lists.style.left = parseInt(lists.style.left) + x + "px";
lists.style.top = parseInt(lists.style.top) + y + "px";
}
window.onkeydown = function (event) {
var key = event.keyCode;
switch (key) {
// 左边
case 37:
x = -5;
y = 0;
break;
// 上边
case 38:
x = 0;
y = -5;
break;
// 右边
case 39:
x = 5;
y = 0;
break;
// 下边
case 40:
x = 0;
y = 5;
break;
}
}
</script>
</body>
</html>
版本1在codepen里的演示结果: https://codepen.io/1980450400/pen/YzGvLVz
再逐步增加难度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
width: 20px;
height: 20px;
background-color: #000;
position: fixed;
top:50px;
left:50px;
}
</style>
</head>
<body>
<div id="lists">
<!-- <div class="box" style="top:50px;left:50px;"></div> -->
<!-- <div>11</div>
<div>10</div>
<div>4</div>
<div>4</div>
<div>4</div>
<div>4</div>
<div>4</div>
<div>3</div>
<div>2</div>
<div>1</div> -->
</div>
<script>
var lists = document.getElementById("lists");
var x = 20; //控制左右 left
var y = 0; //控制上下 top
var dx = 50;
var dy = 50;
// 定时器
setInterval(boxgame, 100);
function boxgame(){
// box.style.left = parseInt(box.style.left) + x + "px";
// box.style.top = parseInt(box.style.top) + y + "px";
// 创建小盒子
var div = document.createElement("div");
div.className = "box";
// 移动位置
div.style.left = dx + x + "px";
div.style.top = dy + y + "px";
lists.insertBefore(div,lists.children[0]);
// 控制蛇身长度 10
if(lists.children.length > 10){
for(var i = 11; i < lists.children.length;i++){
lists.removeChild(lists.children[i]);
}
}
// 记录上一个位置
dx = dx + x;
dy = dy + y;
}
window.onkeydown = function(event){
var key = event.keyCode;
// 37左 39右 left x
// 38上 40下 top y
switch(key){
case 37:
console.log("左");
x = -20;
y = 0;
break;
case 39:
console.log("右");
x = 20;
y = 0;
break;
case 38:
console.log("上");
x = 0;
y = -20;
break;
case 40:
console.log("下");
x = 0;
y = 20;
break;
}
}
</script>
</body>
</html>
版本2在codepen里的演示结果:https://codepen.io/1980450400/pen/RwGJyeR
后面会逐步完善