//Catchfish
function catchFish() {
if (character === "steve") {
// STEVE PROBABILITIES: cod (70%), salmon (20%), tropical (5%), puffer (5%)
simulateCatch (70%, 20%, 5%, 5%);
} else if (character === "alex") {
// ALEX PROBABILITIES: cod (10%), salmon (10%), tropical (30%), puffer (50%)
simulateCatch(10%, 10%, 30%, 50%);
} else if (character === "villager") {
// VILLAGER PROBABILITIES: cod (25%), salmon (25%), tropical (25%), puffer (25%)
simulateCatch(25%, 25%, 25%, 25%);
}
}
How do I simulateCatch? I dont know how to do and send probabilitties back to catchFish
The idea is to generate a random number between 0 and 1, and then subtract each of the successive probabilities for each of the types of the fish, until the rolled value becomes less than 0. Beware, though, that this assumes the probabilities are in range between 0 and 1 and give 1 in sum. Otherwise, it won't work correctly.
// Returns an index of the randomly selected item function simulateCatch(probabilities) { let roll = Math.random(); for (let i = 0; i < probabilities.length; i++) { roll -= probabilities[i]; if (roll <= 0) return i; } // never gets to this point, assuming the probabilities sum up to 1 } var fishArray = ["cod", "salmon", "tropical", "puffer"] //Catchfish function catchFish(character) { if (character === "steve") { // STEVE PROBABILITIES: cod (70%), salmon (20%), tropical (5%), puffer (5%) return simulateCatch ([0.7, 0.2, 0.05, 0.05]); } else if (character === "alex") { // ALEX PROBABILITIES: cod (10%), salmon (10%), tropical (30%), puffer (50%) return simulateCatch([0.1, 0.1, 0.3, 0.5]); } else if (character === "villager") { // VILLAGER PROBABILITIES: cod (25%), salmon (25%), tropical (25%), puffer (25%) return simulateCatch([0.25, 0.25, 0.25, 0.25]); } } function test() { console.log(fishArray[catchFish("steve")]) console.log(fishArray[catchFish("alex")]) } test()
You can define the function like this
function simulateCatch(character,cod,salmon,tropical,puffer){
return `${character.toUpperCase()} PROBABILITIES: cod (${cod}%), salmon (${salmon}%), tropical (${tropical}%), puffer (${puffer})`;
}
and update your catchFish like this
function catchFish() {
if (character === "steve") {
// STEVE PROBABILITIES: cod (70%), salmon (20%), tropical (5%), puffer (5%)
simulateCatch (character,70, 20, 5, 5);
} else if (character === "alex") {
// ALEX PROBABILITIES: cod (10%), salmon (10%), tropical (30%), puffer (50%)
simulateCatch(character,10, 10, 30, 50);
} else if (character === "villager") {
// VILLAGER PROBABILITIES: cod (25%), salmon (25%), tropical (25%), puffer (25%)
simulateCatch(character,25, 25, 25, 25);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.