PDA

View Full Version : rand c++




chris200x9
Oct 24, 2007, 09:18 PM
#include <iostream>
#include <ctime>

using namespace std;

enum Move
{
rock,
paper,
scissors,
};

enum Outcome
{
win,
lose,
draw
};

Move RandomMove()
{
switch( rand() % 3 ) {
case 0:
return rock;
break;
case 1:
return paper;
break;
default:
break;
} // end switch

return scissors;
}

Move SelectMove( Move yourPrevMove, Move oppPrevMove )
{
Move m;


m = paper;

return m;
}

/*
Returns the results of a vs. b in terms of player a.
Thus, either a wins, loses, or draws with player b.
*/
Outcome DetermineOutcome( const Move &a, const Move &b )
{
if( a == rock ) {
if( b == rock )
return draw;
else if( b == paper )
return lose;
// player b played scissors
return win;
}
else if( a == paper ) {
if( b == rock )
return win;
else if( b == paper )
return draw;
// player b played scissors
return lose;
}
// a == scissors;
if( b == rock )
return lose;
else if( b == paper )
return win;
// player b played scissors
return draw;
}

int main()
{
int rounds, winsA, winsB;
Move moveA, moveB;

// seed generator
srand( (unsigned int) time(NULL) );

// initialize variables
winsA = 0;
winsB = 0;

// 100 rounds of rock/paper/scissors
moveA = moveB = rock;
for( rounds = 0; rounds < 1000; rounds++ ) {
moveA = SelectMove( moveA, moveB );
moveB = RandomMove();

// who won?
switch( DetermineOutcome( moveA, moveB ) ) {
case win:
winsA++;
break;
case lose:
winsB++;
break;
case draw:
default:
break;
} // end switch
} // end for

// display summary
cout << endl;
cout << "Player 1 won " << winsA << " rounds (";
cout << (winsA * 100) / rounds << "%)." << endl;

cout << "Player 2 won " << winsB << " rounds (";
cout << (winsB * 100) / rounds << "%)." << endl;

cout << "There were " << rounds - winsA - winsB << " ties (";
cout << ((rounds - winsA - winsB) * 100) / rounds << ")." << endl;
cout << endl;

system( "pause" );
return 0;
}


why do I keep getting the EXACT same output?



SilentPanda
Oct 24, 2007, 09:20 PM
I didn't read your code and I'm not a C++ guru but you probably need to "seed" the random number with the time... otherwise your random numbers will be the same.

ChrisBrightwell
Oct 24, 2007, 09:44 PM
Yeah, you need to seed the RNG.

srand ( time(NULL) );