所以我在做這個蛇游戲,我基本上是想防止食物在蛇尾巴上產卵。我的設定變數:
let headX = 10; //snake starting position
let headY = 10;
let appleX = 5; //food starting position
let appleY = 5;
這是檢查頭部/食物碰撞的功能
function checkAppleCollision() {
if (appleX === headX && appleY === headY) {
generateApplePosition();
tailLength ;
score ;
}
}
這是在碰撞后隨機化蘋果位置的函式,并且在幾次碰撞后還回傳“遞回過多”錯誤:
function generateApplePosition() {
let collisionDetect = false;
let newAppleX = Math.floor(Math.random() * tileCount);
let newAppleY = Math.floor(Math.random() * tileCount);
for (let i = 0; i < snakeTail.length; i ) {
let segment = snakeTail[i];
if (newAppleX === segment.x && newAppleY === segment.y) {
collisionDetect = true;
}
}
while (collisionDetect === true) {
generateApplePosition();
}
appleX = newAppleX;
appleY = newAppleY;
}
請幫忙,我不知道在這里做什么。其他一切都按預期作業。
uj5u.com熱心網友回復:
正如其他人所說,這不需要是遞回的,并且您還應該考慮(但不太可能)沒有更多可以生成的瓷磚的可能性,這會導致無限回圈。
function generateApplePosition() {
// Count how many tiles are left for spawning in
const tilesLeft = (tileCount * tileCount) - snakeTail.length;
let collisionDetect;
if (tilesLeft > 0) {
do {
const newAppleX = Math.floor(Math.random() * tileCount);
const newAppleY = Math.floor(Math.random() * tileCount);
collisionDetect = false;
for (let i = 0; i < snakeTail.length; i ) {
const { x, y } = snakeTail[i];
if (newAppleX === x && newAppleY === y) {
collisionDetect = true; // Collision
break;
}
}
if (!collisionDetect) {
// Found spawn point
appleX = newAppleX;
appleY = newAppleY;
}
} while (collisionDetect);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/446509.html
標籤:javascript 递归
上一篇:使用時刻計算差異
