[CHAT/TAG]Random Color Nickname

Started by rww, Dec 17, 2014, 10:54 PM

Previous topic - Next topic

rww

This is a very simple script...

In header:
RandomColor <- [
RGB(0,255,0),
RGB(130,0,0),
RGB(255,255,0)
];

class PInfox
{
FirstSpawn = false;
ColorNick = RGB(100,100,100);
}

PInfo <- array(GetMaxPlayers(),null);

function onPlayerJoin(p)
{
PInfo[p.ID] = PInfox();
p.Color = RGB(100,100,100);
return 1;
}

function onPlayerPart(p,r)
{
PInfo[p.ID].ColorNick = RGB(100,100,100);
PInfo[p.ID].FirstSpawn = false;
return 1;
}

function onPlayerRequestClass(p,c,t,s)
{
p.Color = RGB(100,100,100);
return 1;
}

function onPlayerSpawn(p)
{
if (!PInfo[p.ID].FirstSpawn)
{
local col = RandomColor[ rand() % RandomColor.len() ];
p.Color = col;
PInfo[p.ID].ColorNick = col;
PInfo[p.ID].FirstSpawn = true;
}
else p.Color = PInfo[p.ID].ColorNick;
return 1;
}
Join to Irrelevant Club Discord: https://discord.gg/MsPPZ5uV4X

.

BTW you forgot to seed the random function. Therefore you won't get a random number. Before using the rand() function you need to pass an integer to the srand() function. The number you pass to srand() will decide how your random numbers will be generated. Which means that the number you'll pass to srand() must also be a little random it self. Which is why most people pass the return value from the time() function which returns the number of seconds that have passed since Thursday, 1 January 1970.

If you're using the random function inside your code very frequently then you won't get any new random numbers until a second passes and the return value from time() changes. For a code as simple like this it won't pose any threats but if the rand() function is called frequently then you might have some numbers that will look the same and probably cause some collisions. You can use this workaround if something like that happens:
function accurate_seed()
{
local uptime = split(clock().tostring(), ".");
uptime = uptime.len() > 1 ? uptime[0] + uptime[1] : uptime[0];
return uptime.tointeger();
}

Also, that's not a random color. That's a random pick from a preset list of colors. You could generate a true random color using the rand() function:
// Seed the rand() function
srand(accurate_seed());
// Create a true random color
print(rand() % 255);
print("\n");
print(rand() % 255);
print("\n");
print(rand() % 255);

Might not get you the desired results because it might generate some colors that will be hard to read. Which brings me to my suggestion and tell you that you should make a command that will allow the player to get another color if something like that happens.
.