📜 ⬆️ ⬇️

Managed random in javascript

"Algorithm" for random sampling of values ​​from the array without repeating them. More specifically, as part of JS training, I used it to generate a classic RPG group of characters (barbarian, magician, thief, knight, priest), without repeating classes and names.

image

The principle is extremely simple, but it can be useful to the same beginners in JS as I am. Binding to the RPG is extremely symbolic - now I'm actively trying to change my profile from marketing to IT (I realized that the soul is lying), and practicing in a game form is much more interesting.

')

1. Create a template


Before generating a group of characters, you need to set a template for generating them. Actually, here:

 function GamePlayer(n, r, l, p) { this.nick = n; this.role = r; this.level = l; this.portrait = p; } 

In fact, this function will create characters from the variables through which it will be called. For example:

 var player1 = new GamePlayer("Power Ranger","barbarian","64","img/barbarian.jpg") 

Now the player1 variable stores the Barbarian Power Ranger 64 level with a certain portrait; we can display any of its parameters in the body of the page using player1.nick , player1.level , etc.

The values (n, r, l, p) of GamePlayer are responsible for receiving and ordering data in the function. If we change the n and r places in the example, then the powerful Barbarian ranger player1 remain in player1 , which does not quite match the task.


2. Set the arrays


In order not to create characters on our own, and almost randomly generate them (as promised in the title), we need arrays from which we will take the parameters of these very characters. As already described above, we have only 4 parameters: , , and .


Name array:

 var playerNames = ['Rabbit Helpless', 'Warm Dreaded Foal', 'Desire Kit', 'Angel Dusty', 'Sweety Frozen', 'Silver Heavy Wombat', 'Lost Puma', 'Vital Panda', 'Rolling Sun', 'Steel Runny', 'Young Fox', 'Needless Ruthless Volunteer', 'Chipmunk Cult', 'Indigo Puppy']; 

It would be possible to go further and generate names from 2-3 components, but the algorithm for such an improvement does not contain anything new (the same random), and then it would simply complicate the learning process.


Class array:

 var playerRoles = ['barbarian', 'mage', 'rogue', 'knight', 'priest']; 

All just as obvious. Several string , from which we will then choose the values ​​to display on the page.


Array for level:

In a concrete example, I wanted all members of the group to be from level 60 to level 70. But, since the conditions can change, it was necessary to create an array from 0 to 80 level, from which then select the desired values. Created by loop:

 var playerLevels = []; for (i = 0;i <= 80;i++) { console.log(i); playerLevels[i] = i; } 

The result is an array of playerLevels , each cell of which contains an int with its own number.


Array for portraits:

 var playerPortraits = ['img/barbarian.jpg', 'img/mage.jpg', 'img/rogue.jpg', img/knight.jpg', 'img/priest.jpg']; 

The same principle, but instead of the text we use links to pictures. Next, we will be able to substitute them in the background-image parameter of the desired div (or in the src parameter of the desired image, for whom it is more convenient).

It is important that the order of the pictures in the playerPortraits array be identical to the order of the classes in the playerRoles array, then to generate them (so that the picture matches the class) we can use the same random variable.


3. We generate characters


As I said, there should be 5 characters in the group. Therefore, we create a cycle:

 for (i = 0;i<=4;i++) { } 

Before the cycle, it is important to declare an array for our future characters:

 var players = [ ]; 


Name generation

Next, create a random variable for randomly selecting a name:

 var namerand = Math.floor(Math.random() * playerNames.length) 


The caveat is that Math.floor rounds down, but since the numbering in the arrays comes from 0, it suits us.


Class generation

The principle and implementation is the same:

 var rolerand = Math.floor(Math.random() * (playerRoles.length)); 

The only difference is that for classes we use the playerRoles array.


Level generation

 var levelrand = Math.floor(Math.random() * (70 - 60 + 1) + 60); 

The calculation of random in a certain interval occurs according to the formula Math.random() * (max - min) + min .

In the example, we get a random from 0 to 10, and then we add 60 to it, getting an interval from 60 + 0 to 60 + 10 (this is what we need). Adding a unit is necessary because of the use of Math.floor (read above).


Character generation

Prefinal step. To form a character, we need to combine all its parameters into one variable, as in the first example. It looks like this:

 players[i] = new GamePlayer(playerNames[namerand], playerRoles[rolerand], playerLevels[levelrand], playerPortraits[rolerand]); 

In fact, each character becomes an element of the players array with its own sequence number. Its parameters are:


As I noted above, the arrays of portraits and classes must be identical in order for the “picture to match”; therefore, we can use the same random in both cases.


Controlled by random

The final. If you leave everything as it is, it will work. However, we get a group of characters of different classes (3 mage and 2 thieves, for example) with the same name. In order to avoid this, a couple of simple actions are enough:

 players[i] = new GamePlayer(playerNames[namerand], playerRoles[rolerand], playerLevels[levelrand], playerPortraits[rolerand]); playerNames.splice(namerand,1); playerRoles.splice(rolerand,1); playerPortraits.splice(rolerand,1); 

Immediately after we assign parameters to the character, we remove their cells from the corresponding arrays.

More specifically, playerNames.splice(namerand,1) removes the cell with the namerand number from the playerNames array using the splice operation. The unit after the comma shows how many cells need to be deleted starting with the specified one; we need to delete only one, the specified cell itself.

Further, the cycle repeats again, and could give out undefined if I stumbled upon the last cell of the array (after all, we reduced it by 1). But, since our Math.random uses playerNames.length and others, it directly depends on the length of the array, and will only give out new, not duplicate values.


4. Conclusion


Additionally, you can describe the interaction of this script with the page: displaying the “cards” of characters, uploading their portraits, etc., but this is quite an obvious process associated with the main functions of JS. In addition, I already tightened my simple manual a little. So, you can see a visualization of the process in the example.

Demonstration of implementation (similar, slightly different classes)

I hope this material will be useful to someone and will be useful in solving interesting problems. Successes in JS!

Source: https://habr.com/ru/post/181874/


All Articles