I'm making a C++ text-based Battleship game. I use the rand() function to randomly place the computer's ships. I seed the number generator once at the beginning of main(), with the line below:
srand(static_cast<unsigned>(time(0)));
I later use the rand() function to choose the spaces where each individual ship will go. (The coordinates where one end of the ship will start). I then use rand() in the function below, which decides the direction in which they will extend (depending on the ship's length):
char randDirection()
{
int randNumber = rand();
int x = (randNumber % 4) + 1;
if (x = 1)
return 'u';
else if (x = 2)
return 'd';
else if (x = 3)
return 'l';
else
return 'r';
}
It randomly gets a number between 1 and 4, and returns a direction (represented by a char) depending on the number. While I had success with randomly choosing the locations for the pieces, this function always sets the pieces vertically. They always go up. Can anyone tell me why?
Your problem is on every "if", you're doing an assignation, not a test. Moreover, in a test an assignation will always return the result of the assignation. For example:
if (x = 0)
// will never be here because 0 is false in a test
else if (x = 42)
// will always end up here
else
// will never be here