Battleship – A Senior Design Preparatory Experience

laboredbumbaileySoftware and s/w Development

Jun 7, 2012 (6 years and 9 months ago)


Session F1C
1-4244-1084-3/07/$25.00 ©2007 IEEE October 10 – 13, 2007, Milwaukee, WI
ASEE/IEEE Frontiers in Education Conference
Battleship – A Senior Design Preparatory Experience

Brian J Resnick
Assistant Professor, University of Cincinnati, Electrical & Computer Engineering Technology
Cincinnati, OH 45206

Abstract - The senior design capstone project can be
overwhelming for some electrical and computer
engineering technology students. In addition to selecting a
topic and then actually designing something, it may be the
first time that a student has had to execute all aspects of a
project from conception to completion. In preparation for
this challenge, students could benefit from practice on a
somewhat predefined project. This paper presents a series
of homework and laboratory assignments that guide the
student through the development of a large object-oriented
programming project: an Internet enabled version of the
game Battleship. Project elements include rules of play, a
graphical user interface for ship placement, another for
battle, and a communications protocol for play over the
Internet. While the overall scope of project is fixed, there
are many opportunities for the students, as a team, to
impose variations on the theme during the specification
process. This customization activity promotes a sense of
ownership and commitment. Student feedback has been
positive and the paper includes a summary of their

Index Terms - Battleship, Capstone, Java, Laboratory
Assignments, Object-Oriented Programming, Senior Design

For some engineering technology students, the senior design
capstone project is overwhelming because they do not know
where to start. Their education focuses on analysis. They have
no experience with design, and yet, to graduate, they must
select a topic, perform research, design and implement
something, manage the project, write a report, and produce a
showcase piece.
Informal departmental discussions led to the concept of
providing a preparatory experience for upcoming seniors. It
was the consensus of the department that students might
benefit from some practice in their pre-senior years. If they
experienced the design process on a predefined topic, they
might be able to apply the principles to their own topic. If
interconnecting laboratory assignments produced a single
large-scale project, the students might learn to break their own
project into pieces.
Those discussions led to the development of laboratory
assignments for a junior-level programming course that guide
the student through the complete design experience for a
large-scale project.
This paper presents a set of laboratory and homework
assignments for junior-level electrical and computer students
taking a one-quarter course entitled Graphical Network
Programming. The objectives of the course, beyond the
aforementioned design experience, include more object-
oriented programming, graphics (both primitive and forms),
exposure to an integrated development environment, and
development of a networking application. This is a tall order
for one quarter, and as you will find in some of the student
comments, it may have been a bit too much.
Prior to this course, the students have had an introduction
to object-oriented programming in C++, at least one other
course in programming, and a course in networks (everything
below the application level).
Student familiarity with the game Battleship and the
simplicity of the game make it an excellent topic for design.
The coding requirements are no more complex than three
nested loops, which permits the student to spend more time
appreciating and implementing the higher-level concepts such
as interfaces. The graphic side of the project allows the
student’s individuality to shine. The need for all programs to
support the same communications protocol encourages
The paper begins with a description of the course,
followed by an overview of the entire project. The next
sections contain the actual assignments, followed by student
comments and the conclusion.

Graphical Network Programming is a junior-level three-hour
lecture course with a three-hour lab that explores using Java in
graphical applications and network/web applications. The
course objectives include:
• Use NetBeans integrated development environment [1]
• Apply object-oriented programming methodologies
available in Java [2]
• Draw a specified graphic using Graphics methods [3]
• Implement a specified form using Swing components [4]
• Specify and implement a program to support the form
• Specify and implement a communications protocol

The students have varied programming backgrounds;
some have had a course in Java, some have had a course in C
in their first year, and all have had a one-quarter course on
object-oriented programming in C++. All have taken a
networking course. They are familiar with the lower levels of
the TCP/IP stack, but few have programmed at the application
Instead of a textbook, the students rely on the abundance
of web support for Java and NetBeans including many
Session F1C
1-4244-1084-3/07/$25.00 ©2007 IEEE October 10 – 13, 2007, Milwaukee, WI
ASEE/IEEE Frontiers in Education Conference
excellent tutorials [1]-[4]. Web based lecture notes also serve
as additional resources for the students.
The lecture portion of the course begins with an
explanation of the project and then dives into a crash course in
Java. From there, the lecture presents overviews of particular
skills or concepts (graphic primitives of Graphics, Swing
components, layout managers, inheritance, event handling,
listeners, interfaces, and inner classes) as needed for the
upcoming assignment, and facilitates group discussions.

An Internet enabled version of Battleship, on the surface,
appears to be a simple assignment. It does not scare the
student, and yet it is complex enough to engage the student all
quarter long.
The choice of language is always open for discussion.
Java is readily available, supported by terrific web sites, and
most importantly, it is free, as is the integrated development
environment NetBeans. The students can download the same
tools as used in class, and can work wherever whenever they
The project is a Java application, not an Applet. The
frame contains a tabbed pane with three tabs: the placement
tab, the player setup tab, and the battle tab.
The lecture is limited to Flow, Grid and Border layout
managers, which causes more panels within panels, but it
allows more time for topics that are more important. A
motivated student can easily follow a tutorial to use a different
layout manager; and some did.
The placement tab contains a panel with two sub-panels:
one that paints the placement grid and one that contains
buttons to manipulate ship placement.
The battle tab contains a panel with many sub-panels: one
for a 10x10 grid of buttons (used to fire the salvos), one for
displaying statistics and your opponents’ progress against your
placement grid, one for sending chat, and one for displaying
received chat.
The player setup tab is a panel within a panel that
contains radio buttons for selecting type of game (single
player manual setup, single player computer setup, two player
host, and two player client), a spinner to set the host’s port
number, a text field for the host’s IP, and buttons for start, quit
and reset.
Play a game or two of Battleship. Locate an online version and
play it. Write the answers to the following questions: What are
your rules of play? What size is the game board? How many
ships exist? What size are the ships? How will you place the
ships? What is the sequence of events during a player’s turn?
When is the turn over? When is the game over? Who goes
Imagine that you are playing over the telephone and that
both players are limited to the same question: What kind of
damage does a salvo to the square at row R and column C
What are the possible replies to that question?


For all of the games to play together, they must all follow the
same rules and have the same set of replies to the salvo
question. The group must agree to a set of rules. Additional
topics to discuss: playing out of turn and servicing an invalid
Document the results of the group discussion that finalizes the
rules of play and the list of replies to the salvo question.


In this lab, you are designing and implementing:
• A class named placement grid that contains a draw
method with the following parameters: a reference to a
Graphics object on which to draw the placement grid, the
location (x and y) of the upper-left corner of the grid, and
the size of a grid cell. The grid shall be square. The grid
shall have a background color (or image) with the 10x10-
grid pattern displayed on top.
• A placement panel (extends JPanel) containing a paint
method that sizes and positions a placement grid in the
center of the panel with a minimum gap of 5% between
the grid and the panel. Pass a reference to the grid to
draw in the placement panel’s constructor.
• The game frame (extends JFrame), which is the overall
frame for the game. It instantiates the placement grid and
the placement panel, and adds the placement panel to the
• A public main method that launches the game frame



Discuss how to represent the game board. Most inexperienced
programmers gravitate towards a procedural approach and
want to implement a two-dimensional (2D) array of cells, and
initialize the cells to one of water, horizontal bow, vertical
bow, horizontal mid-section, vertical mid-section, horizontal
stern, vertical stern, a damaged ship section, or a miss.
This is the perfect time to reinforce the abstraction and
encapsulation concepts of object-oriented programming. There
is no need for the grid to have a 2D array of cells. All a grid
needs to know is its size, its list of ships and its list of misses.
From that information, it can draw the game board.
Next, examine the Ship class. What are its instance
variables? What are their data types?
Finally, address the Miss class.
Discuss the Unified Modeling Language (UML) and class
diagrams. Use them in the discussion of these classes.
Explore the UML tools of NetBeans.
Make UML class diagrams for the classes: Ship and Miss.
Use the UML tools of NetBeans to reverse engineer your
project. Print the UML diagrams created by NetBeans.
Session F1C
1-4244-1084-3/07/$25.00 ©2007 IEEE October 10 – 13, 2007, Milwaukee, WI
ASEE/IEEE Frontiers in Education Conference




In the last assignment, you made extensions to existing
classes, created a class of your own for the placement grid,
and made use of some of the Graphics methods.
In this lab assignment, you will create two new classes for
entities that belong to the placement grid: one to represent a
Ship and one to represent a Miss (a salvo that hits the water).
After creating these classes, instantiate an array of Ships
to represent the fleet in the placement grid, and instantiate an
ArrayList to hold references to Miss objects, to which Miss’
are added as they occur. Test the abilities of these classes by
writing some throwaway code that adds a Miss or two in the
placement grid constructor, and show some hits on your ships.
At a minimum, the instance variables of a Ship include
location information (row and column), length, orientation,
and damage information. The Ship constructor will provide
location, length and orientation, and initialize the ship to be
undamaged. NOTE: Temporarily construct the ship with
some damage to the first cell just to test your code.
Orientation is a two-state variable. Possibly implement as
a boolean or as an enumeration of horizontal and vertical.
Ship damage represents the state of each section of the
ship. A boolean array sized to match the length of the ship is
one method of implementation.
At a minimum, the instance variables of a Miss include
location information.
Both Ship and Miss need a draw method that receives a
reference to the Graphics object, the location of the grid, and
the cell size. These are the same parameters as those passed to
the draw method of the placement grid.
Modify the draw method of placement grid to draw all
ships and all misses.
Demonstrate your placement grid with ships (partially
damaged) and misses.




The next assignment requires a crash course in Swing
components (JButton, JRadioButton and ButtonGroup), layout
managers, events, action listeners, action events, inner classes
and interfaces. Using interfaces with Swing components
provides a foundation for the students to create their own
interfaces in a later lab.



What methods must the placement grid make public to allow
the placement buttons to accomplish their goal?
What methods must the Ship class implement to support
the ship manipulation methods of placement grid?


In the last assignment, your placement grid class had the
capability to draw the ships, to display ship damage, and to
indicate which empty cells have received fire.
In this lab assignment, you will design and implement:
• A placement buttons panel with Swing components to
select the ship to manipulate, and to command the
selected ship to move (left, right, up or down) or rotate.
• A placement tab (JPanel) that instantiates the placement
panel and placement buttons panel. NOTE: The frame no
longer instantiates the placement panel as it did in Lab #2.
• Add a JTabbedPane object to the frame.
• Instantiate the placement tab in the frame, and add it to
the tab object.

To accomplish the above:
• The ship class must provide methods for moving a ship
one cell in each direction, and for rotating a ship.
• The placement grid must provide methods for moving a
selected ship one cell, and for rotating a selected ship.
NOTE: Select the ship to manipulate by using its array
index as a parameter to these methods. (This is bad
technique because this code breaks if the order of the
ships changes; consider more sophisticated alternatives.)
• The placement buttons panel will need a reference to the
placement grid in order to command the ship
• The placement tab constructor will need a reference to the
placement grid in order to pass it to placement buttons
and the placement panel.
• After each manipulation, you will need to cause the frame
to redraw, thus the placement buttons panel needs a
reference to the JPanel portion of the battle tab so that it
can call the repaint method.


Using Homework #2, discuss and design the interface between
the battle tab and placement grid. The result should be similar
to the following:

public interface BattleInterface
public enum Reply
MISS, // no damage to any ship
HIT, // damaged a ship
SUNK2, // sunk a ship of length 2
SUNK3, // sunk a ship of length 3
SUNK4, // sunk a ship of length 4
SUNK5, // sunk a ship of length 5
YOU_WIN, // that hit sank my last ship
ILLEGAL, // illegal column or row
NOT_YOUR_TURN, // it is not your turn
TECH_DIFF // problem with network - stop
public Reply salvoDamage(int col, int row);
Session F1C
1-4244-1084-3/07/$25.00 ©2007 IEEE October 10 – 13, 2007, Milwaukee, WI
ASEE/IEEE Frontiers in Education Conference
The battle tab fires a salvo into a specified square of the
placement grid by calling the salvoDamage method of the
interface. The placement grid determines the extent of the
damage, marking the cell of a ship as damaged if appropriate
or remembering that a miss has occurred if the cell is empty.


In the last assignment, you added the tab mechanism to the
frame, and created the placement tab, which includes the
placement panel from earlier assignments and the components
(buttons, etc.) necessary to manipulate the ships. The
BorderLayout manager on the placement tab obtained the
desired arrangement of panels.
In this lab assignment, you will implement the battle
interface we designed in class, and then design and implement
the battle tab, which uses the battle interface. At the end of
this assignment, the game is almost functional as a single
player game.
To accomplish the above:
• Include the BattleInterface in your project.
• The placement grid must implement the BattleInterface.
This means you must provide a body for the methods of
that interface within your placement grid class, and
declare that your placement grid class implements
• The battle tab contains a panel that has 100 buttons. It
also contains a battle stats panel for displaying either what
is happening to your placement grid when combating a
remote opponent, or some statistics when playing alone.

Rather than implementing 100 individual listeners, use a
common listener for all 100 buttons. For a common listener to
work, some mechanism must exist for determining the row
and column of the pressed battle button. The ActionCommand
capability of a JButton and the ability of the ActionEvent to
supply a reference to the pressed JButton accomplish this goal.
Give each JButton an ActionCommand string with two
characters (one for the column and one for the row); such as
“02” for row zero, column two. Then, in the common listener,
acquire the ActionCommand string, extract the row and
column information, and use that row and column to query the
battle interface.
The reply to the query should change the appearance of
the button. For instance, change the background from white to
blue if the result is a miss, to yellow if a hit, or to red with a
digit as the legend to represent a sunken ship of that size.


The player setup tab has the means to determine which type of
game to play and to interrupt a game, but it does not have
access to the game itself. Game frame instantiates the game.
Game frame needs to supply limited access to the player setup
tab. That access includes starting the various types of games,
quitting a game, and resetting the game. All of these methods
belong in an interface implemented by game frame and used
by player setup.
Some discussion of the needs of the host and the client
will be necessary. The host needs a port, the client needs a
port and the host’s IP.
Based on the group discussion, write the interface between
game frame and player setup.
public interface Play Game
public void startClientGame(int port, String hostIP);
public void startHostGame(int port);
public void startManualGame();
public void startComputerGame();
public void resetGame();
public void quitGame();


In the last assignment, you added the battle tab complete with
100 buttons, visual feedback of the result of firing a salvo, and
some statistics for single player game.
In this lab assignment, you will add another tab that
allows the player to select the style of play: single player with
manual placement or single player with computer placement
and starts a game. (You will add two player games in a future
You will also complete some of the finer details we have
left undone:
• Disable the placement tab once a game starts
• Disable firing of salvos until the game begins
• Add a popup of “you win” or “you lose” when the game
is over
• Prevent further play when the game is over
• Add an “I quit” button that stops the game to the player
setup tab.
• Add a reset button to reset a stopped game.

To accomplish the above, you will:
• Create a player-setup tab class
• Instantiate that class in game frame and add it to the tabs
as the middle item
• Add a game state variable (placement, started, stopped) to
game frame to prevent restarting a game in progress, etc.
• Add a reset method to Placement Grid that resets all
ships, erases the misses, and resets other variables
• Add a reset method to Ship that resets the hit array to


Session F1C
1-4244-1084-3/07/$25.00 ©2007 IEEE October 10 – 13, 2007, Milwaukee, WI
ASEE/IEEE Frontiers in Education Conference
Validation of ship placement involves determining if two
ships use the same location. Students come up with a variety
of schemes. The most common is creating a 2D array of
integers that represent the cells, initialize them to zero, and
then increment the quantity if a ship uses that cell. When
done, if any cell is greater than one, the placement is invalid.
A better method would stop as soon as any cell quantity
reached two.
An even better method would not use an array. It would
check the cells of the first ship for overlap with all of the other
ships. Then, it would check the cells of the second ship for
overlaps with ships three though five. Check ship three against
ships four and five. Check ship four against ship five, and
done. At any point of overlap, return invalid.
Write pseudo-code for the overlapping ships algorithm.
For each ship J of the fleet (J = 0 to 3)
For each cell of ship J
Determine the row and column of that cell
For each remaining ship (K = J+1 to 4)
Test if the cell (row and column) is on ship K
If so, report invalid placement
Next remaining ship K
Next cell of ship J
Next ship in fleet
Report valid placement



In the last assignment, you supported single player game
selection but did not validate the game board nor support
computer generation of ship placement.
In this lab assignment, you will complete both types of
single player gaming (manual placement and computer
To accomplish the above:
• Add a computer generated (random) ship placement
method to placement grid
• Add a validate method to placement grid that implements
the algorithm from homework assignment #5

Placement grid’s validation method must examine for
overlapping ships. If there are no overlaps, return true,
otherwise return false. Use this method within game frame’s
startManualGame method before allowing play to begin.
There are two approaches to computer placement. Each
requires the Ship class to have a method for randomly placing
a ship. The first, and simplest, approach is for the placement
grid to randomize all ships in the fleet, call the validate
method, and repeat until the randomly located ship placement
is valid. This works but is not elegant.
The second approach randomizes the first ship, and then
adds one ship at a time making sure that it does not overlap
with the previously placed ships. If it does, randomize only the
new ship again.
The randomize method of the ship must randomize the
orientation and location, making sure that the ship stays within


This course uses sockets instead of remote method invocation
(RMI), because of the desire to discuss sockets, threads, and
the protocol itself. RMI would create a different discussion.
Java supports the usual socket capabilities: server sockets
that listen for and accept clients, and client sockets. The server
socket needs a port number. The client socket needs a host IP
Address string and a port number.
For the protocol, the idea is to pass strings back and forth.
Java provides InputStreamReader and BufferedReader classes
to handle the input stream, and PrintWriter to handle the
output stream.
The protocol defines the format and content of the strings.
The class must agree on the strings that represent the battle
interface. For instance, one might use the string “M” to
represent a reply of miss, and “2” to present the reply for sunk
a ship of size two.
What is the format of the query string? It contains two
values, a row and a column. If we identify the rows as 0 to 9
and the columns as 0 to 9, a two-character string could
represent the query.
The students usually want to include chat, which opens
the discussion to hacking. What happens if the chat message
were mistaken for a query?
This leads to the conclusion that the first character of the
message should indicate the type of message: usually, “Q” for
query, “R” for reply, and “C” for chat. Query messages
become “Qcr”, where “c” is the column digit, and “r” is the
row digit. Replies become “Rx”, where “x” is “H” for hit, “M”
for miss, “2” for sunk a ship of size two, etc. Chat messages
are “Ctext”, where “text” is the text taken from the text
Discuss the concept of a class (remote combat) that
communicates with your opponent. Remote combat will
instantiate a thread that listens for and interprets incoming
strings. If the string is a query, the thread checks for whose
turn it is. If it is the opponents’ turn, the thread validates the
row and column data. If the data is valid, the thread calls the
salvoDamage method of the placement grid. The thread
converts the reply from salvoDamage into a string and sends
the string to the socket.
Remote combat also has a battle interface that the battle
tab uses. When the local player fires a salvo, it calls the
salvoDamage method of the remote combat. Remote combat
converts the row and column to a string per the protocol and
sends it to the remote player. It then awaits a reply, but how
can it wait? There is no polling mechanism. How does it wait?
This opens the door for a discussion of synchronization.
Session F1C
1-4244-1084-3/07/$25.00 ©2007 IEEE October 10 – 13, 2007, Milwaukee, WI
ASEE/IEEE Frontiers in Education Conference



Document the remote battle protocol. All games must follow
the same protocol; make sure that yours matches the others.



The game frame needs to send supply certain data to and
manipulate remote combat, and remote combat needs to send
certain data to game frame.
Write the two interfaces between remote combat and
game frame. Name one ToRemote and other FromRemote.



In the last assignment, the single player game was complete.
In this lab assignment, you add the elements necessary for
remote play over the Internet by designing and implementing:
• A remote combat class that implements the battle
interface for use by the battle tab. Its constructor opens a
server socket or a client socket as the case may be, starts a
thread, and listens for incoming strings. It needs a
reference to the local grid for making calls to
• Remote combat must supply methods for game frame to
quit and reset.
• Remote combat must supply a method that accepts
outgoing chat strings.
• Remote combat needs a FromRemote interface reference
from game frame so that it can deliver the incoming chat
string and alert game frame to the need to update its panel
after an incoming salvo.

To accomplish the above:
• Implement the FromRemote interface in game frame.
• Add a set opponent method to battle tab, so that game
frame can change the opponent to either the local
placement grid or the remote combat object
• If implementing chat, add a text field to the battle tab and
cause its listener to transfer the string to the outgoing chat
method of remote combat.
• If implementing chat, add a text area to the battle tab and
cause the incoming chat method of the FromRemote
interface to append its string,
• Game frame should update the battle tab when remote
combat calls the update method of FromRemote.

Each student included a reflection on the assignment as part of
his or her final report. The following statements are
representative of the class as a whole:
“I enjoyed working on the battleship program, even
though I had to struggle with it quite a bit. I really think that
having a bigger project like the battleship game is so much
better than having individual labs that are not connected
together. By doing a project like this, it shows how a real life
project comes together even though this battleship is, I am
sure, a lot smaller than projects at companies.”
“I enjoyed this class greatly. I would prefer this type of
class over past typical programming courses, where we learn
the syntax of a portion of code and apply it to an individual
lab. I may get that lab to work, but I would not come to
understand why that code/lab worked. With this style of
course, it allowed me to understand how and why each portion
of code worked because I had to build upon each lab. Instead
of finishing a lab and forgetting its functionality until test or
exam time, this class required me to understand and build
upon a constant chunk of code and eventual create a working
“I think the thing that helped me out the most with this
class was the way we walked through what was going to be
needed to accomplish the lab assignments. By walking
through the thought process I was able to start to think and
organize things in a more efficient manner.”
“This lab was definitely worth while and in my opinion
an excellent way to help develop a students understanding of
object-oriented programming.”
“This class was a little rushed and I feel that I could have
benefited from spending more time on some of the more
complex subjects.”
“Some of the downsides to the class was that it seemed
easy to get lost with the flow of work. Oftentimes a lab would
be completed without the students being completely sure why
or how the program worked. To alleviate this problem, I
would recommend that the students complete some kind of lab
report for each week. It would be extra work, but it would
also force everyone to know what their program was doing as
any given time.”


While the student feedback is positive, those students do not
start their senior design projects until next year and thus there
is no data relative to their performance on the senior design
projects from which to draw a conclusion.
The class as a whole was interested in completing the
assignment. They pushed me rather than the other way
around. There was friendly competition as to whose game
looked better. One student used images rather than graphic
primitives to draw his ships.
In the future, I plan to incorporate the student’s
suggestion of a weekly report.

[1] "NetBeans IDE 5.5 Quick Start Guide", NetBeans Documentation, Sun
Microsystems, March 1, 2007
[2] “Object-Oriented Programming Concepts”, The Java Tutorials, Sun
Microsystems, 2006, March 1, 2007
[3] “Programmer’s Guide to the Java 2D API”, Java 2 SDK SE, Sun
Microsystems, April 24, 2001, March 9, 2007
[4] “Creating a GUI with JFC/Swing”, The Java Tutorials, Sun
Microsystems, 2006, March 10, 2007