Reputation: 33
I created a table using an 8x8 matrix for a game and i also put into the table prizes, and etc in random places but I am having an issue creating also random start position for the user that doesn't conflict with the objects that are already in the table.
For now I have:
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];
};
but I get nothing. Sorry if the question seems trivial I am just starting Javascript and have looked everywhere for a relevant answer with no avail.
Upvotes: 3
Views: 1941
Reputation: 28
It looks like what you want to do is select a random position in the matrix, if it is undefined then return it, otherwise select a new random position and try again. You need to make a few changes for this.
First - the return statement in your loop is unnecessary and is causing your function to be returned on the first run of the loop, stopping it from doing its job.
Second - In most cases, you should use ===
and !==
instead of ==
and !=
. You can find a detailed explanation here - Which equals operator (== vs ===) should be used in JavaScript comparisons?
Third - When you want to check if a variable is undefined, while myVar === undefined
should work most of the time, there a situations where it could fail. best practice is to use typeof myVar === 'undefined'
. More info here - https://stackoverflow.com/a/15093969/7739148
try this:
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];
};
Caution - if there are no positions that are undefined the loop will never end, so you should either make sure your matrix will have at least one empty spot, or perform a check at the start of your function.
Upvotes: 0
Reputation: 664356
A few mistakes:
return
from within the loop, but have to check the condition to leave itMath.floor
instead of 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];
}
Upvotes: 1