<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../code/jq/jquery-3.3.1.min.js"></script>
</head>
<style>
.box {
width: 400px;
height: 400px;
border: red solid 3px;
}
.miniBox {
float: left;
border: white 1px solid;
font-size: 6px;
color: white;
}
.qiang {
background: brown;
}
.kong {
background: grey;
}
.snake {
background: greenyellow;
}
</style>
<body>
<button>开始创建地图</button>
<div class="box">
</div>
var direction = "r";
$(function () {
$('button').click(function () {
var num = prompt('请输入游戏难度') - 0;
creatMap(num, $('.box'));
var snakeArr = [num + 1, num + 2, num + 3];
snakeH(snakeArr, num);
run(snakeArr, num);
})
function snakeH(snakeArr) {
for (var i = 0; i < snakeArr.length; i++) {
$('.box').children().eq(snakeArr[i]).removeClass("kong").addClass("snake");
}
}
function run(snakeArr, num) {
var timer = setInterval(function () {
var nextIndex = 0;
if (direction = "r") {
nextIndex = snakeArr[snakeArr.length - 1] + 1;
} else if (direction = "l") {
nextIndex = snakeArr[snakeArr.length - 1] - 1;
} else if (direction = "t") {
nextIndex = snakeArr[snakeArr.length - 1] - num;
} else if (direction = "b") {
nextIndex = snakeArr[snakeArr.length - 1] + num;
}
if ($('.box').children().eq(nextIndex).hasClass('qiang')) {
clearInterval(timer);
return alert('撞墙了');
}
$('.box').children().eq(snakeArr[0]).removeClass('snake').addClass('kong');
$('.box').children().eq(nextIndex).removeClass('kong').addClass('snake');
snakeArr.shift();
snakeArr.push(nextIndex);
console.log(snakeArr);
}, 500)
}
})
function creatMap(num, $box) {
for (var i = 0; i < num * num; i++) {
if (i < num || i % num === 0 || (i + 1) % num === 0 || i > (num - 1) * num) {
$box.append($('<div class="miniBox qiang">' + i + '</div>'))
continue;
}
$box.append($('<div class="miniBox kong">' + i + '</div>'))
}
$box.children().css({
width: 400 / num - 2,
height: 400 / num - 2
})
}