Click here to Skip to main content
14,644,614 members
Rate this:
Please Sign up or sign in to vote.
See more:
I'm new to coding and I'm having some troubles with this piece of code.
Players' name and score are the same for both players when I run the program but different when I debug. Why is that?

private string name;
private int ID;
private static int nextID = 1;
private int score;

public void Test()
{
    Player player1 = new Player();
    player1.Register();
    player1.SetRandomInfo();
    Console.WriteLine(InfoToString(player1));

    Player player2 = new Player();
    player2.Register();
    player2.SetRandomInfo();
    Console.WriteLine(InfoToString(player2));
}

public void SetRandomInfo()
{
    Random randomGen = new Random();
    int random = randomGen.Next(100);
    name = "player" + random;
    random = randomGen.Next(20);
    score = random;
}
Posted
Comments
frostcox 22-Mar-13 11:53am
   
Inside SetRandomInfo()
set score = 0 and name = "" at the start
Rate this:
Please Sign up or sign in to vote.

Solution 2

You should not initialize your randomGen variable each time you call the SetRandomInfo() method.

Better create a class-wide Random variable, initialize it in the constructor of the class (with a seed or not), and use it in your method.

Name, ID and score variables should be local ones, on the contrary.
   
Comments
Maciej Los 22-Mar-13 12:14pm
   
Good idea!
+5!
phil.o 22-Mar-13 12:16pm
   
Thanks Maciej ;)
Rate this:
Please Sign up or sign in to vote.

Solution 1

Hello,

Try providing the initial seed value to the Random Number Generator. e.g.
DrandomGen = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);

Regards,
   
Comments
phil.o 22-Mar-13 12:14pm
   
It could do the trick (as long as name, ID and score variables are made local, see my solution).
But there is a performance penalty to initialize a Random at each iteration.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100