Good night folks.
I'm new to programming, less than 2 months, so I don't quite understand how to make this work. Here's exactly what I want to do: I have this game I'm trying to make which needs to do a raffle between existing units that fit the condition "is alive" and have "is able to use the prize". To do that, I was told I needed to include an array with the unit Id for the units that can receive it, then filter them by "is alive" to choose from by a random generator. Thing is, I have no idea how to make this work. I've tried this code, but it does not work. Anyone has any idea why or how I should do it instead?
var rafflearray = []; // the array containing the units
if (root.getExternalData().isUnitRegistered() = true) {var character = root.getCurrentSession().getPlayerList().getData()}; // establish the character as a variable
if (var character.getAliveStatus = true ) {rafflearray.push(character)}; // checks his alive status and send him to the array
var chosen = rafflearray [Math.random()*chosenarray.lenght]; // to choose amongst them
chosen.addItem()
Thanks in advance for the attention!
CodePudding user response:
I strongly suggest going through Javascript Fundamentals (here section 1 & 2) before this project. However I hope this answer helps you
First of all you cannot use var inside if statements like
if(var character.getAliveStatus = true)
And you need to use ==
or ===
instead of =
, like:
if(isAlive === true){
// Code to be executed
}
// the difference between '==' and '===' can be found in the docs mentioned below
see Javascript Operators from here on section 3
var is for declaring a variable which is not limited to its parent blocks see javascript scoping
In your case I'm not sure if you have an array of players already or if you're trying to make one.
In the first situation, I suggest you use Array.filter()
function which is a cool way. For example :
// Assuming 'players' is the array of players in the game
// filtering out raffle worthy players
let raffle_worthy = players.filter(player => player.getAliveStatus === true);
// Randomly choosing 1 person between the raffle worthy players
let chosen = raffle_worthy[Math.floor(Math.random * raffle_worthy.length)]
You may want to take a look at Array.filter() docs and also Js Math has been used in the above example
On the other hand if you dont have an array of players and getting them one by one, I'm not really sure if I can understand the way you get users and what gathers them