PDA

View Full Version : [Tutorial] Random Numbers.



SergiuOfficial
19-06-17, 12:22
Hello Guys, idk how my old Tut (a bad one) was deleted. So, i am gonna make a new Tutorial with some better explanations.

So, Random is nothing but just choosing something blinded. For Example, u are allowed to pick a ball in a bag without seeing it, you wouldn't know which u might pick, its random.

How We Are Going To Use Random In Pawn Scripting.

It is just a simple code, it is inclused in a_samp.inc so no need to include any other stuffs.
Code:
random(number);
the above code will generate a random number.
But in most of the Computer Languages, all numbers Start from 0, So if i do
Code:
random(10);
the possibilities are
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
If u don't want the 0 to come as a result , u must use this code
Code:
random(number) + 1;
So, is the random number generated is 0, the result will be 0 + 1 which is 1. If the Random number generated is 9, the result is 9 + 1 which is 10.

Y_less made a code which makes a better random number
Code:
stock randomEx(min, max)
{
//Credits to y_less
new rand = random(max-min)+min;
return rand;
}



Example Of Uses With Random.

I will show u an example code and explain it
Code:
CMD:lotto(playerid, params[])
{
new rand = random(10) + 1; // As i said above
new number; // a new variable Named "number" to store the data of the input the player typed.

if(sscanf(params,"i", number)) // sscanf.
{
SendClientMessage(playerid, 0xFF0000AA, "/lotto [1-10]"); // if the player typed a Not-Numeric Number, it shows this msg (even if he didnt type a thing)
}
else // if he didnt make a mistake in typing the code, it passes the code.
{
if ( number > 10 || number < 1) // if he typed /lotto 11 or /lotto 0 or /lotto 1243
{
SendClientMessage(playerid, 0xFF0000AA, "choose a number From 1-10"); // the error message.
}
else // If his number is between 1 and 10, it passes the code.
{
if (number == rand) // If he won, if the randomly generated number is same as the number he typed.
{
SendClientMessage(playerid, 0x33AA33AA, "You won it!!");// Winner message.
GivePlayerMoney(playerid, 1000000); // Cash (i am rich, i will give 1m :P)
SetPlayerScore(playerid, GetPlayerScore(playerid) + 1); // score for winning.
}
else
{
if( number != rand) // If his number is not same as the number which is randomly generated.
{
SendClientMessage(playerid, 0xFF0000AA, "You Lost"); // Loser message.
}
}
}
}
return 1;
}
This code works, but u can make a better one. It is just an example code, try to be differ


Want me to add more things? Comment.

I've heard that pawn uses "pseudorandom numbers" to generate random numbers.
__________________
SUGGESTION FOR FUTURE SA-MP
Code:
forward SetWeaponRange(weaponid, maxrange); // if weapon is fist and 100 range, it may give a warn or super punch xD
forward SetWeaponRecoil(weapoinid, maxrecoil);