Currently creating a battleship game for my c class, I'm working on creating a way in which each ship can be randomly placed on the board. So far I have come up with this, the only issue is that I had ships overlapping each other. To try and fix this I put another condition within my while loop which calls a function to check if the spot is taken. I thought it would all work fine and dandy, but instead, I get this error message and now I'm pretty much stuck.
#include "ship.h"
#include "board.h"
#include <ctime>
#include <iostream>
using namespace std;
void Ship::setShip(Board &board) {
bool isOpen(int x, int y);
srand(time(0) * (size rand()));
int x = rand() % 10;
int y = rand() % 10;
int orientation = rand() % 2 == 0 ? 0 : 1;
string open = "[ ]";
if (orientation == 0) {
// check if ship is off the board
while (x size > board.COLS || !isOpen(x, y)) {
x = rand() % 10;
y = rand() % 10;
}
for (int i = x; i < x size; i ) {
board.board[i][y] = shipLetter;
}
} else {
while (y size > board.ROWS || board.board[x][y] != open) {
x = rand() % 10;
y = rand() % 10;
}
for (int i = y; i < y size; i ) {
board.board[x][i] = shipLetter;
}
}
bool isOpen(int x, int y)
{
bool taken = false;
for (int i = 0; i < size; i ) {
if (board.board[x i][y] != open) {
taken = true;
} else {
taken = false;
}
}
return taken;
}
}
CodePudding user response:
For the future, please read and consider https://stackoverflow.com/help/how-to-ask
This is really important because you cannot get a good answer without asking a good question.
I will try anyway, because one thing is just obvious in your code.
Move the function definition isOpen
outside, and before, the method body of setShip
. So according to this:
...
bool isOpen(int x, int y) {
.... full function implementation here
}
void Ship::setShip(Board& board) {
// isOpen(int x, int y); <-- remove this line
.... rest of method implementation here
}
This will at least solve the error you reported here. But I would be surprised if the code would work anyway or do what you expect right away... But this is a different problem.
CodePudding user response:
You can't define a function inside another function.