So, for my assignment, I had to create the battleship game using arrays, and several methods and classes. Anyways, my program is pretty much completed except I'm having a minor issue. My program takes in the users guess in the form of a column int, and row int. Then it's declared if that guess is a hit or miss. If it is a hit, it shows as a H on the console, and a M for a miss. However, after a ship is sunk, all the H's for that ship need to turn to an X. I believe I should have either an if statement or a for loop, but after several attempts, I feel like i'm straying further and further from the correct answer. Here is what the method looks like:
If you need any additional code, please let me know! I just didn't want to post the whole program !
In the loop you commented out, you used j to index a segment of the sunk ship. That means it's not an absolute coordinate on the board, but a relative one. For instance, if the ship lies horizontally on the board with the first segment at (c: 3, r: 2), then:
j = 0
j = 1
j = 2
So you need to add the relative index to the absolute starting position of the first segment of the ship. That's not the whole story though. For horizontally oriented ships, you need to add the relative index to the absolute starting column index, and for vertically oriented ships, you need to add the relative index to the absolute starting row index. That means you need to keep track of the orientation of the individual ships somewhere.
From experience I can tell you that keeping track of a ship's starting coordinates and orientation and calculating absolute coordinates from them is much more difficult than just letting the ship keep track of all the absolute coordinates of its segments. Encapsulate coordinates in a Position class. Here is a skeleton:
A Ship needs only one absolute grid coordinate, preferably the closest to (0,0) and then an orientation (UP or DOWN).
Ideally, you’d just write:
Come to think of it, you really only need something like this:
Because is a Ship is sunk, it should know to show “X” for all its position on the board otherwise, it should only show “H” for whatever parts of it have been hit. The symbolic constants for HIT and SUNK should be in the Ship class, not wherever the OP’s code shows it. Doing it the way OP has done it has broken the Ship class’ encapsulation.
World domination requires a hollowed out volcano with good submarine access. Tiny ads are optional.