vendredi 29 mai 2015

Using C++ rand() to get random directions (up/down/left/right) - always getting up

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?




Aucun commentaire:

Enregistrer un commentaire