# Problem with battleship game

This is a discussion on Problem with battleship game within the C Programming forums, part of the General Programming Boards category; Hey! I made a battleship game: computer generates 10 random coordinates (x ; y) - ships. In my game computer ...

1. ## Problem with battleship game

Hey!
I made a battleship game: computer generates 10 random coordinates (x ; y) - ships. In my game computer generates only 1 coordinate (x ; y) long ships. And i have a checking function - thats where the problem is.
The checking function must check, if the generated ship is located next to the other ships (before generated ships). If the generated ship is located next to the othed ships, then it must generate new coordinates and must do the checking function again. If the generated ship is located in free place ( no other ships are next to the ship), then it saves the coordinates to ships array.

problem is: when the program generates the ships, it like ignores the checking funktion - some ships are still side by side.

sorry for my bad english, hope you undestand.

Code:
```//Genereerib 1-sed laevad
int laev1(int laev[][2], int *laud[][10]){
int x, k, l;
for(x = 0; x < laevade_arv; x++){
a = arv_N(10);
b = arv_N(10);
if(kontroll(laev, a, b)== 1){
laev[x][0] = a;
laev[x][1] = b;
}
}
}

int kontroll(int laev[][2], int a, int b){
int x, s;
s = 0;
while(s != 1){
for(x = 0 ; x < laevade_arv ; x++){
if(a == laev[x][0] || a== laev[x][0]+1 || a == laev[x][0]-1){
if(b == laev[x][1] || b == laev[x][1]+1 || b == laev[x][1]-1){
//Genereerib uued koordinaadid ning teeb kontrolli uuesti läbi
a = arv_N(10);
b = arv_N(10);
kontroll(laev, a, b);
}
}

else{
s = 1;
break;
}
}
}
return 1;
}```

2. could anybody help me please? I have no idea, why it still generated some ships side by side.

3. Originally Posted by P6nn
could anybody help me please? I have no idea, why it still generated some ships side by side.
The basic approach is OK.
But you're not using recursion properly.The function checks if the ships are alongside, if not, it calls recursively with new a and b, but then it throws away the new a and b instead of passing them up.
It might be simpler to code it non-recursively.

Write a function to check if a and b are adjacent to a ship. That's all the function should do.
The just do

Code:
```do
{
a = random();
b = random();
} while(adjacenttoship(ships, a, b));```

4. okay, thanks

Popular pages Recent additions