I'm working on the game battleship on c++ and everything works out great except for the part that its the AI turn to take a shot. I got it to work with the AI picking a random number, but it sometimes picks the same number twice. so I was working on the code to check if the coordinates had already been picked before. according to me the code below should work, but if doesn't it stills picks the same coordinates twice.
What its supposed to do is pick to random numbers. then it checks it with the other previous coordinates. if they match it sets attack to false and the while loop repeats. then it stores the coordinates in a vector.
this is a member function of a class. Row and column are declared private in the class.
Code:
vector<int> prevAttacksY(1, -1);
vector<int> prevAttacksX(1, -1);
bool attack;
int count = 0;
while(!attack){
row = rand() % 8;
column = rand() % 8;
attack = true;
for(count = 0; count < prevAttacksY.size(); count++){
if (row == prevAttacksY.at(count) && column == prevAttacksX.at(count))
attack = false;
}
}
prevAttacksY.push_back(row);
prevAttacksX.push_back(column);