function sta() {
var she = [{ x: 0, y: 0,s:0 }]; //身体
var shenti = '';//当前前进方向
var zou = '';//下次前进方向
var dan = { x:0, y: 0 } //蛋坐标
function adddan() {
//生成一个蛋
var sy = [];
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
if (she.filter(q => q.x == i && q.y == j).length == 0) {
sy.push({x:i,y:j})
}
}
}
if (sy.length == 0) {
console.log('mei');
return;
}
dan = sy[Math.floor(Math.random() * sy.length)]
console.log('蛋', JSON.stringify(dan))
}
adddan();
function miao() {
//处理蛇的行动
if ((shenti == 'w' && zou == 's') || (shenti == 's' && zou == 'w') || (shenti == 'a' && zou == 'd') || (shenti == 'd' && zou == 'a')) {
zou = shenti;
} else {
shenti = zou;
}
if (zou == '') {
return;
}
var x = 0, y = 0;
if (zou == 'w') {
y = -1;
}
if (zou == 's') {
y = 1;
}
if (zou == 'a') {
x = -1;
}
if (zou == 'd') {
x = 1;
}
var newarrs = [];
var jd = -1;
var add = {};
for (var i = 0; i < she.length; i++) {
if (i == 0) {
var ex = she[i]['x'] + x;
var ey = she[i]['y'] + y;
if (ex < 0 || ey < 0 || ex >= 10 || ey >= 10) {
console.log('end')
return;
}
if (she.filter(q => q.x == ex && q.y == ey).length > 0) {
console.log(JSON.stringify(she))
console.log('ends')
console.log(ex, ey)
return;
} else {
newarrs.push({ x: ex, y: ey, s: 0 })
}
} else {
newarrs.push(she[i - 1])
}
if (she[i]['s'] == 1) {
jd = i;
}
add = she[i];
add.s = 0;
}
var ad = false;
if (newarrs.length > 0) {
if (newarrs[0].x == dan.x && newarrs[0].y == dan.y) {
console.log('chi');
newarrs[0].s = 1;
ad = true;
}
if (jd>=0 ) {
if (jd + 1 == newarrs.length) {
newarrs.push(add)
} else {
newarrs[jd + 1].s = 1;
}
}
}
//setTimeout(() => {
// miao();
//}, 1000)
she = newarrs;
if (ad) {
adddan();
}
st();
console.log(JSON.stringify(she))
}
function anniu(type) {
//每次按下按键
zou = type;
miao()
return;
if (zou == '') {
zou = type;
miao()
} else {
zou = type;
}
}
//监听按键
document.addEventListener('keydown', function (event) {
console.log(event.key)
if (event.key === 'w' || event.key === 'd' || event.key === 'a' || event.key === 's') {
anniu(event.key)
}
});
//刷新图画
function st() {
var h = "";
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
var sty = "";
if (she[0].x == j && she[0].y == i) {
sty = "red";
} else if (she.filter(q => q.x == j && q.y == i).length) {
if (she.filter(q => q.x == j && q.y == i && q.s == 1)) {
sty = "blue";
} else {
sty = "#000";
}
}
if (dan.x == j && dan.y == i) {
sty = "yellow"
}
h += '<div style="background:' + sty +'" ></div>'
}
}
$("#ss").empty();
$("#ss").append(h);
}
st();
}
页面代码
<div id="ss"></div>
css代码:
#ss {
width:220px;
display: grid;
grid-template-columns: auto auto auto auto auto auto auto auto auto auto;
grid-gap: 1px;
}
#ss div {
border: 1px solid red;
width: 20px;
height: 20px;
background-color: rgba(255, 255, 255, 0.8);
border: 1px solid black;
text-align: center;
font-size: 30px;
}
标签:auto,js,简易,贪吃蛇,she,&&,var,newarrs,zou
From: https://www.cnblogs.com/mufuhu/p/18412305