# Battleship Ai

Updated on December 12, 2017 in
1 on December 12, 2017

Hello!

I’m currently making battleships as an assignment in school. I’m almost finished with the code but I have encountered a problem. I have written my code in such a way that the computer will always shoot at random targets.

``` aiShotX = randomNumber.Next(1,6);
aiShotY = randomNumber.Next(1,6);
```

how can I make so if the computer once shot X = 5 and Y = 3. Those coordinates are dead and won’t be shot at again?

//Erik

• Liked by
on December 12, 2017

If you are using a gameObject to hold your projectile shot you can use OnCollisionEnter to check if the object collided with that point on the playing board.

Here is an example:

```//This holds the coordinates that have been hit
Dictionary<int, Vector3> hitCoords;

//This is used as an index of all of the contacts
int contactCount;

void Start()
{
contactCount = 0;
hitCoords = new Dictionary<int, Vector3>();
}

void OnCollisionEnter(Collision collision)
{
//Contact X Coordinate
int hitPointX = (int) collision.transform.position.x;

//Contact Y Coordinate
int hitPointY = (int) collision.transform.position.y;

//Contact Z Coordinate
int hitPointZ = (int) collision.transform.position.z;

//3D position of the contact point
Vector3 hitArea = new Vector3(hitPointX, hitPointY, hitPointZ);

//Checks if the contact point has been hit and if it has returns
if (hitCoords.ContainsValue(hitArea))
{
PrintAllExistingHitAreas();
return;
}
// If it gets here it adds one to the index
contactCount += 1;

//Adds the position at the index contactCount
}

//This prints all locations that have been hit
void PrintAllExistingHitAreas()
{
Debug.Log("Current Locations That Have Been Hit: ");
for (int i = 1; i <= hitCoords.Count; i++)
{
Debug.Log("Position" + i + ": "+ hitCoords[i]);
}
}
```
• Liked by