Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone,

I am developing my own game and I have a problem with Random().

When game runs, the Random() merely gives me a same number.
C#
if (seconds % 5 == 0 && seconds != 0 && animal_appearance == false)
           {
               animal_appearance = true;
               Last_animal += seconds;
               anime_Index =new Random().Next(9);
           }

My first run: Random() give me 6 and then after 10 seconds it again gives me 6.
On my second run as first run but 1 instead of 6

I am really have no idea of this.

Sincerely.
Posted
Updated 20-Oct-11 10:42am
v2

You are making a common mistake for random numbers.

See the MSDN Documentation on Random[^] Seeding.

Random numbers are actually pseudo random and the clock is used by default for its seed (you can provide your own though).

To solve, you can make a single random object and have your own seed value (int) rather than the default.

C#
Random _randSeed = new Random(GetSavedSeedValue());//Get a seed value from somewhere
...
if (seconds % 5 == 0 && seconds != 0 && animal_appearance == false)
            {
                animal_appearance = true;
                Last_animal += seconds;  
                anime_Index = _randSeed.Next(9);
            }
 
Share this answer
 
v4
Comments
Sergey Alexandrovich Kryukov 20-Oct-11 18:38pm    
Exactly! My 5.
Why do they all try to do that, I wonder? To me, it's hard to understand.

--SA
[no name] 21-Oct-11 9:33am    
Thank you.
I think part of it comes from the objects simplicity. One feels they need not read any documentation, and most new programmers don't understand the concept of pseudo random so they use it incorrectly.
thx^^.
Sr for being late.
I have been busy recently. Thx for ur answer.
I will try my best.
Thx alot.
Sincerely.
 
Share this answer
 
Comments
André Kraak 23-Oct-11 10:07am    
If you have a question about or comment on a given solution use the "Have a Question or Comment?" option beneath the solution. When using this option the person who gave the solution gets an e-mail message and knows you placed a comment and can respond if he/she wants.

Please move the content of this solution to the solution you are commenting on and remove the solution.
Thank you.
[no name] 24-Oct-11 10:01am    
Also you should click accept if a solution meets your needs.

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900