Add comments to the sea class

This commit is contained in:
andrew
2022-01-10 20:22:14 +00:00
parent 49be31b8e2
commit 0614831f46

View File

@@ -1,8 +1,13 @@
// Track the content of the sea
class Sea { class Sea {
// the sea is a square grid of tiles. It is a one-dimensional array, and this
// class maps x and y coordinates to an array index
// Each tile is either empty (value of tiles at index is 0)
// or contains a ship (value of tiles at index is the ship number)
private int tiles[]; private int tiles[];
private boolean hits[];
private int size; private int size;
public Sea(int make_size) { public Sea(int make_size) {
size = make_size; size = make_size;
tiles = new int[size*size]; tiles = new int[size*size];
@@ -10,6 +15,8 @@ class Sea {
public int size() { return size; } public int size() { return size; }
// This writes out a representation of the sea, but in a funny order
// The idea is to give the player the job of working it out
public String encodedDump() { public String encodedDump() {
StringBuilder out = new StringBuilder(); StringBuilder out = new StringBuilder();
for (int x = 0; x < size; ++x) { for (int x = 0; x < size; ++x) {
@@ -22,13 +29,17 @@ class Sea {
/* return true if x,y is in the sea and empty /* return true if x,y is in the sea and empty
* return false if x,y is occupied or is out of range * return false if x,y is occupied or is out of range
* Doing this in one method makes placing ships much easier
*/ */
public boolean isEmpty(int x, int y) { public boolean isEmpty(int x, int y) {
if ((x<0)||(x>=size)||(y<0)||(y>=size)) return false; if ((x<0)||(x>=size)||(y<0)||(y>=size)) return false;
return (get(x,y) == 0); return (get(x,y) == 0);
} }
/* return the ship number, or zero if no ship */ /* return the ship number, or zero if no ship.
* Unlike isEmpty(x,y), these other methods require that the
* coordinates passed be valid
*/
public int get(int x, int y) { public int get(int x, int y) {
return tiles[index(x,y)]; return tiles[index(x,y)];
} }
@@ -37,15 +48,7 @@ class Sea {
tiles[index(x, y)] = value; tiles[index(x, y)] = value;
} }
public int shipHit(int x, int y) { // map the coordinates to the array index
if (hits[index(x,y)]) return get(x, y);
else return 0;
}
public void recordHit(int x, int y) {
hits[index(x, y)] = true;
}
private int index(int x, int y) { private int index(int x, int y) {
if ((x < 0) || (x >= size)) if ((x < 0) || (x >= size))
throw new ArrayIndexOutOfBoundsException("Program error: x cannot be " + x); throw new ArrayIndexOutOfBoundsException("Program error: x cannot be " + x);