Reputation: 83
So I'm making a game with js and jquery, and I have 2 players that need to spawn randomly. The game map is composed of tiles and some of the tiles are blocked(the player can't click on them), they have a class of "unavaliable" and I need to make it so that when the players spawn, they don't spawn on those tiles that are blocked. The question is, can you make an if statement that checks if the tile has a certain class, and if it does, then don't spawn the player there. What I have for now is:
// This asigns 2 random tiles for player one and player two
let randomSpawn = tiles[Math.floor(Math.random() * tiles.length)];
let randomSpawnTwo = tiles[Math.floor(Math.random() * tiles.length)];
/* This is an if statement that chekcs if the class name coresponds to unavaliable*/
function checkIfempty(){
if(randomSpawn.className === "unavaliable"){
randomSpawn = tiles[Math.floor(Math.random() * tiles.length)]
console.log('heyo it does')
}else if(randomSpawn.classname !== "unavaliable"){
randomSpawn.appendChild(playerOne);
}
if(randomSpawnTwo.className === "unavaliable"){
randomSpawnTwo = tiles[Math.floor(Math.random() * tiles.length)];
}else if(randomSpawnTwo.className !== "unavaliable"){
randomSpawnTwo.appendChild(playerTwo);
}
}
So what I bassically want, is, if the already assigned random tile has a class of "unavaliable", pick another random field, and place the player there. This of course doesn't work for some reason that I'm unaware of. And the function is set to run on load.
Upvotes: 0
Views: 223
Reputation: 780724
You should use a loop to keep checking whether the selected tile is available. However, this will become slow when most tiles are unavailable, since it will have to repeat many times.
Instead of picking a random tile from the array and checking whether it's available, you could simply use a selector that only returns available tiles.
Give all your tiles a class like tile
, and then use:
var availableTiles = $(".tile:not(.unavailable)");
var randomSpawn = availableTiles.eq(Math.floor(Math.random() * availableTiles.length));
availableTiles = availableTiles.not(randomSpawn); // remove the one we just selected
randomSpawn2 = availableTiles.eq(Math.floor(Math.random() * availableTiles.length));
Upvotes: 1