Pidgey Keeps Getting Displayed - Fix Chosen Pokemon Random Number Generating Issue
In this article, we'll explore why Pidgey keeps getting displayed as the chosen Pokemon even when a random number generator is implemented, and discuss how to resolve this issue. We'll cover key concepts such as random number generation, arrays, and conditional statements using code examples where necessary.
Random Number Generation
To ensure that a random Pokemon is chosen each time, we need to use a random number generator. This can be achieved using the built-in Math.random() function in JavaScript, for instance. The Math.random() function returns a random floating-point number between 0 (inclusive) and 1 (exclusive).
let randomNumber = Math.random();
Generating a Random Integer from 0 to N-1
To generate a random integer between 0 and N-1, we can use the following function:
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
Creating an Array of Pokemon
In order to choose a random Pokemon, we need to create an array of Pokemon that can be used for selection. Here's an example:
let pokemon = ['Pikachu', 'Squirtle', 'Charmander', 'Bulbasaur', 'Jigglypuff'];
Selecting a Random Pokemon
Now that we have a function for generating a random integer between 0 and N-1, and an array of Pokemon, we can use the following code to select a random Pokemon:
let randomNumber = getRandomInt(pokemon.length);
let chosenPokemon = pokemon[randomNumber];
Fixing the Issue
If you've followed the previous instructions and Pidgey is still getting displayed as the chosen Pokemon, there are a few possible reasons why:
- The
randomNumbergenerator is not being used to select a Pokemon from thepokemonarray. - The
pokemonarray contains Pidgey or an incorrect array is being used. - There is a typo or logical error in the code.
To ensure that the issue is resolved, you can use the following example code to select a random Pokemon:
const pokemon = [
'Pikachu',
'Squirtle',
'Charmander',
'Bulbasaur',
'Jigglypuff',
'Pidgey',
];
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
const randomNumber = getRandomInt(pokemon.length);
const chosenPokemon = pokemon[randomNumber];
console.log(`Chosen Pokemon is: ${chosenPokemon}`);
- Random number generators can be created using the
Math.random()function in JavaScript. - Arrays can be used to store arrays of Pokemon or other objects.
- Conditional statements and arrays can be combined to select a random element from an array.