Managed by random in JavaScript

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

image

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


1. Create a template


Before generating a group of characters, you need to specify a template for their generation. 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 instance:

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

Now the variable player1stores the level 64 Power Ranger barbarian with a specific portrait; we can display any of its parameters in the body of the page using player1.nick, player1.leveletc.

The values (n, r, l, p)from GamePlayerare responsible for the reception and procedure for receiving data into the function. If the example of change n, and rplaces in the player1maintained Power Rangers Barbarian, that does not quite match the task.
 

2. We set arrays


In order not to create characters on our own, but to almost randomly generate them (as promised in the header), arrays are needed from which we will take the parameters of these same characters. As described above, the parameters we have only 4: имя персонажа, класс, уровеньand портрет.
 

Array for the name:

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'];

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

Array for the class:

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

Everything is just as obvious. Several stringof which we will then choose the values ​​to display on the page.
 

Array for level:

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

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

The result is an array playerLevels, each cell of which contains intits 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 text we use links to pictures. Further, we can substitute them in the parameter of the background-imagedesired div(or in the parameter of the srcdesired picture, to whom it is more convenient).

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

3. We generate characters


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

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

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

var players = [ ];


Generating names

Next, create a random variable to randomly fetch the name:

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

  • Marh.random() used to generate a random number;
  • Multiplication by playerNames.length(array length playerNames) - to limit the random number of names in the array;
  • Math.floor - to turn the resulting number into an integer.

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

Class generation

The principle and implementation is the same:

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

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

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 add 60 to it, getting the interval from 60 + 0 to 60 + 10 (we need this). Adding a unit is necessary due to use Math.floor(read above).
 

Character generation

Pre-final step. To form a character, we need to combine all of his 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 array playerswith its own serial number. Its parameters:

  • playerNames[namerand]- the name of a random selection of names (cell numbered namerandin playerNames);
  • playerRoles[rolerand] - class, random selection from classes;
  • playerLevels[levelrand] - class, random level selection in the range of 60-70;
  • playerPortraits[rolerand] - portrait, random selection from portraits.

As I noted above, arrays of portraits and classes must be identical so that the “picture matches”; therefore we can use the same randomin both cases.
 

Managed random

Final. If you leave it as it is, it will work. However, we get a group of characters of different classes (3 mages and 2 thieves, for example) with the same names. In order to avoid this, a couple of simple steps 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, it playerNames.splice(namerand,1)deletes the cell with the number namerandfrom the array playerNamesusing the operation splice. The unit after the decimal point shows how many cells need to be removed starting from the specified one; we need to delete only one, the specified cell itself.

Further, the cycle repeats again, and could issue undefinedif it came across the last cell of the array (we reduced it by 1). But, since ours Math.randomuses playerNames.lengthothers, it directly depends on the length of the array, and will only produce new, non-repeating values.
 

4. Conclusion


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

Demonstration of implementation (similar, slightly different classes)

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

Also popular now: