How to correctly model a Battleships Game in Java

java, oop, swing

Solution

the separation sounds good though i think, it could be made more clear. using the MVC pattern, you can clearly define the model (ships and grid), the controllers(your logic) and the view (the jframe that draws the grid).

Now basically, the model dont know anything else, the controller knows view and model and the view knows how to draw model and calls controller as reaction on user input. That is: user clicks, the view just calls a controller with the coordinates and the event that happened. This controller now modifies the grid and issues a redraw.

So in my pov, you probably dont need a cellGUI class, just a view that draws everything (though, you could model it like this if you store x,y in cellgui classes...). But you dont need a celllogic class. you need a "higher" controller that knows, how to modify the whole grid and what happens, if there is already something and so on.

Problem

I am trying to create a Battleships game for a 'Games' project my group is doing at university. I've never really used GUIs before, with almost all my output previously being in the Eclipse console. To begin with, I created a GUI class, which is effectively my "runner" class. It loads up a JFrame. I have a second class, GUIGrid, which sets a dimension for the two game boards that will be displayed and uses nested for loops to create the grid from GUICells. This contains listeners etc to detect what the mouse is doing and stores the x and y coordinates of each cell. I have run a little piece of test code so I can click anywhere on either grid and a popup tells me exactly which coordinates that cell is. In addition to these classes, I have a Ship class, with five subclasses for types of ship and a Player class, with stores the player's name and create an array of Ship objects for them to use. Finally, I have my logic classes. I have a GridLogic class and a CellLogic class. The former uses nested for loops to create a 2D array of CellLogic objects. The CellLogic class then stores things like coordinates and information on whether the cell has been attacked. My question (at last!) is - is this the correct way to model the system? When I look at the CellLogic and CellGUI classes, they seem to have fairly similar stuff. Additionally, although I can make the GUI respond to mouse clicks, I am really struggling to connect the GUI to the Logic. For example, I have no idea how to add ships onto the grid and then store which positions store ships in the 2D array. Without posting copious amounts of code, I was hoping someone would be able to tell me if I'm at least on the right track, or if I've separated the system out too much.

Original source