Monday, July 27, 2009

Rolling 2 dice in c++?

k well part of a game i have to write includes me maknig a function which rolls a dice and returns its value (between 1 and 6)





int doRoll()


{


randomize();


int die = 1 + random(6);


return(die);


}





theres my function and wen i call it in the main method





int main()


{


int d1 = doRoll();


int d2 = doRoll();


cout %26lt;%26lt; "You have rolled: " %26lt;%26lt; d1 %26lt;%26lt; " %26amp; " %26lt;%26lt; d2 %26lt;%26lt; endl;


return(0);


}





every single time this program runs both dice present the same number, and i want to know how to make it so both dice randomize a different number

Rolling 2 dice in c++?
You can use the rand() and srand() functions like this:





http://xoax.net/comp/cpp/console/Lesson2...
Reply:Personally, I never use the rand and supplied random functions as they use a linear conguential random number generator and I have a pseudo LFSR function that is incredibly fast for generating integer random numbers.


That being said, your problem lies in the fact that your DoRoll function runs the same way each time it is called. You either need to store a static state within the function so each time it is called it returns a different value OR pass in an argument that gets updated each time the function is called.


Bottom line is the seed for the random number needs to be different each time around.


Within the doRoll function you can then scale the random number to fit within 1 to 6 (beware of it being from 1.0 to 5.999 in which case 6 never happens....you get what I'm saying?).





OK, you are good to go.


Good luck.


-D
Reply:What library are you getting random() from?





Also, when you pass the 6 to the function you are giving it a 'seed'. When you start with the same seed, as you have, you'll get the same sequence of random numbers.





Usually what people do is use


put


#include %26lt;cstdlib%26gt;





and use srand(time(NULL)) ; // early in main





which will get the current time, which will be different each time the program is run.





You should use


int die = 1 + rand()%6 ;


to get an random number between 1 and 6





Let me know how this works.


No comments:

Post a Comment