mirror of
https://github.com/coding-horror/basic-computer-games.git
synced 2025-12-22 07:10:42 -08:00
Add comments to the sea class
This commit is contained in:
@@ -1,8 +1,13 @@
|
||||
// Track the content of the 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 boolean hits[];
|
||||
|
||||
private int size;
|
||||
|
||||
public Sea(int make_size) {
|
||||
size = make_size;
|
||||
tiles = new int[size*size];
|
||||
@@ -10,6 +15,8 @@ class Sea {
|
||||
|
||||
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() {
|
||||
StringBuilder out = new StringBuilder();
|
||||
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 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) {
|
||||
if ((x<0)||(x>=size)||(y<0)||(y>=size)) return false;
|
||||
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) {
|
||||
return tiles[index(x,y)];
|
||||
}
|
||||
@@ -37,15 +48,7 @@ class Sea {
|
||||
tiles[index(x, y)] = value;
|
||||
}
|
||||
|
||||
public int shipHit(int x, int y) {
|
||||
if (hits[index(x,y)]) return get(x, y);
|
||||
else return 0;
|
||||
}
|
||||
|
||||
public void recordHit(int x, int y) {
|
||||
hits[index(x, y)] = true;
|
||||
}
|
||||
|
||||
// map the coordinates to the array index
|
||||
private int index(int x, int y) {
|
||||
if ((x < 0) || (x >= size))
|
||||
throw new ArrayIndexOutOfBoundsException("Program error: x cannot be " + x);
|
||||
|
||||
Reference in New Issue
Block a user