我为一个游戏创建了一个使用8x8矩阵的表格,我还在随机位置放入了表格等等,但是我遇到了一个问题,即为不与之冲突的用户创建随机起始位置表中已有的对象。
现在我有:
function startPos(matrix) {
var x = Math.round(Math.random() * matrix.length);
var y = Math.round(Math.random() * matrix.length);
while (matrix[y][x] != undefined) {
var x = Math.round(Math.random() * matrix.length);
var y = Math.round(Math.random() * matrix.length);
return matrix[y][x];
};
return matrix[y][x];
};
但我一无所获。对不起,如果问题似乎微不足道,我只是开始使用Javascript并且无处可寻找相关答案。
答案 0 :(得分:0)
一些错误:
return
,但必须检查条件才能离开Math.floor
代替Math.round
undefined
)
function startPos(matrix) {
var l = matrix.length; // assumes square matrix
do { // assumes at least one empty field
var x = Math.floor(Math.random() * l);
var y = Math.floor(Math.random() * l);
} while (matrix[y][x] != undefined);
return [y, x];
}
答案 1 :(得分:0)
看起来你想要做的是在矩阵中选择一个随机位置,如果它是未定义的,则返回它,否则选择一个新的随机位置并再试一次。您需要对此进行一些更改。
首先 - 循环中的return语句是不必要的,并且导致在第一次循环运行时返回函数,阻止它执行其工作。
第二次 - 在大多数情况下,您应该使用===
和!==
代替==
和!=
。您可以在此处找到详细说明 - Which equals operator (== vs ===) should be used in JavaScript comparisons?
第三次 - 如果要检查变量是否未定义,而myVar === undefined
大部分时间都应该有效,那么可能会出现故障。最佳做法是使用typeof myVar === 'undefined'
。更多信息 - https://stackoverflow.com/a/15093969/7739148
试试这个:
function startPos(matrix){
// first select a random position
var x = Math.round(Math.random() * matrix.length);
var y = Math.round(Math.random() * matrix.length);
// if the position is not empty, select a new one.
// continue like this until an empty spot is found.
while(typeof matrix[y][x] !== 'undefined'){
x = Math.round(Math.random() * matrix.length);
y = Math.round(Math.random() * matrix.length);
};
// once we have an empty position, return it
return matrix[y][x];
};
注意 - 如果没有未定义的位置,循环将永远不会结束,因此您应该确保矩阵至少有一个空位,或者在函数开始时执行检查。