1.背景:
2.实现过程:
- 设置移动方向:
方向默认为四个,通过监听键盘的wsda键进行识别,对应1-4四种方向
function changeMd() {
//更改记录方向的数组
snakeNum = replaceNum(snakeNum);
//调用移动方法,每节移动
for (let i = 0; i < snakeNum.length; i++) {
if (i === 0) {
moving(map.children[i], snakeNum[i], true);
} else {
moving(map.children[i], snakeNum[i], false);
}
}
}
let sBody = document.createElement('div');
sBody.id = id;
sBody.className = 'snake'
if (isFood) {
sBody.style.left = Math.ceil(Math.random() * 420 / 20) * 20 + 'px';
sBody.style.top = Math.ceil(Math.random() * 420 / 20) * 20 + 'px';
}
id === 0 ? true : sBody.style.backgroundColor = color;
return sBody;
}
let food = map.children[snakeNum.length]
let foodLeft = food.offsetLeft;
let foodTop = food.offsetTop;
let isEat = false;
switch (num) {//判断是否吃掉食物)
if (isEat) {//吃掉后,改变小蛇的长度
map.appendChild(AddSnake(snakeNum.length + 1, randomColor(), true));//生成新的食物
snakeNum.push(0);//往记录方向的数组中添加一位
//把新的蛇div放到蛇的末尾
let snakeNewDom = map.children[snakeNum.length - 1];
let snakeLastDom = map.children[snakeNum.length - 2];
snakeNewDom.style.left = snakeLastDom.offsetLeft + 'px';
snakeNewDom.style.top = snakeLastDom.offsetTop + 'px';
}
3.实现截图:
