我正在为学校制作蛇游戏,任务之一是使蛇穿过墙壁并从另一侧开始。
newX
和newY
是蛇在网格(30x30)上的头部位置。我该怎么做?
if (
0 > newX || newX > grid["width"] - 1 ||
0 > newY || newY > grid["height"] - 1 ||
getValueFromGrid(newX,newY) === SNAKE
)
答案 0 :(得分:2)
这是一个简单的函数,用于对正负数进行模运算。
假设宽度为val originalList = arrayListOf(1,2,3,4,5)
val orginalListCopy = ArrayList(originalList)
(请记住,索引基于0,0 ... 29 = 30宽度)
30
,则将x改正为-1
29
,则将x改正为30
0
使用方式如下:
const mod = (n, max) => ((n % max) + max) % max;
console.log(mod(29, 30), mod(30, 30), mod(31, 30), mod(32, 30)); // 29, 0, 1, 2
console.log( mod(1, 30), mod(0, 30), mod(-1, 30), mod(-2, 30)); // 1, 0, 29, 28
使用世界尺寸9×7的简单示例:
const newX = mod(currentX, width);
const newY = mod(currentY, height);
const mod = (n, max) => ((n % max) + max) % max;
const World = {
w: 9,
h: 7,
el: document.querySelector("#world"),
render() {
const map = new Array(this.w * this.h).fill("\u00b7");
Snake.body.forEach((s, i, b) => map[this.w * s.y + s.x] = i == b.length - 1 ? "\u25a0" : "\u25a1");
this.el.textContent = map.join("").replace(new RegExp(`(.{${this.w}})`, "g"), "$1\n");
}
};
const Snake = {
body: [{x:0,y:0}, {x:1,y:0}, {x:2,y:0}], // [tail, ..., head]
dir: "R", // L, R, U, D
speed: 300,
move() {
const head = Object.assign(this.body.shift(), this.body[this.body.length-1]); // Convert tail to head
if (this.dir === "L") head.x = mod(head.x - 1, World.w);
if (this.dir === "R") head.x = mod(head.x + 1, World.w);
if (this.dir === "U") head.y = mod(head.y - 1, World.h);
if (this.dir === "D") head.y = mod(head.y + 1, World.h);
this.body.push(head);
}
};
const setDirection = (e) => {
const d = (e.key.match(/^Arrow(.*)$/)||[])[1];
if (!d || /UD|DU|LR|RL/.test(`${Snake.dir}${d}`)) return;
e.preventDefault();
Snake.dir = d[0];
}
document.addEventListener("keydown", setDirection);
(function engine() {
Snake.move();
World.render();
setTimeout(engine, Snake.speed);
}());
#world{margin: 0; letter-spacing: 0.5em;}
答案 1 :(得分:0)
您没有提供太多信息,但是我可以给您答案,猜测蛇不能做对角线运动。您可以仅应用以下内容:
if (newX < 0 ) newX = grid['width'] - 1;
if (newX > grid['width']) newX = 0;
if (newY < 0) newY = grid['height'] - 1;
if (newY > grid['height']) newY = 0;