Java Battleship Game

Java Battleship Game

Introduction

In this programming assignment, your task is to build a simple Battleship game with a text-based
interface. There are two players: the player (you) and the opponent (computer). Both players have
a 2D grid of n x m squares, where n is the number of rows and m is the number of columns. There
are also battleships occupying some of the squares so that three adjacent squares either vertically
or horizontally form a battleship. The player can see the battleships on the player’s grid, but the
opponent cannot see them. On the other side, the opponent can see the battleships on the
opponent’s grid, but the player cannot see them. The player and the opponent will both in turns
guess the coordinates of the opposite side’s battleships. If there is a battleship in the guessed
coordinate, the result is “hit”, otherwise the result is “miss”. The game continues until either the
player or the opponent has destroyed all the ships on the opposite side. The winner is the one who
sinks all the battleships on the opposite side first. Figure 1 illustrates the game.
Figure 1. Illustration of the Battleship game..png
Figure 1. Illustration of the Battleship game.

源码传送门

传送门:https://pan.baidu.com/s/1gNMp7_R2fJZqys4BJIAGXw?pwd=1111

Report Guidance and Requirements
Your assessment code and report must conform to the below structure and include the required
content as outlined in each section. Each subtask has its own marks allocated. You must supply a
written report, along with the corresponding code, containing all distinct sections/subtasks that
provide a full critical and reflective account of the processes undertaken.
This assessment includes coding tasks and a final written task outlining the steps taken as
aforementioned. You will be provided with a template code for some of the classes to help you get
started.
While we’re not marking your use of Git in this assignment, you are strongly encouraged to do
this work inside a Git repository. By doing that you gain the benefit of rolling back your edits, or
doing work in branches, and then merging it to the main branch as you accomplish tasks along the
way.
Perhaps most importantly, by using Git and pushing your work to a remote repository on GitHub,
you provide a safe backup of your work. You would be surprised by how regularly fellow students

discover failed hard disk drives, or that the laptop they are using needs to be returned to its owner,
or it must be repaired due to some liquid being spilt on the keyboard.
If you push your work regularly to GitHub, then you can easily (a) pull it into Codio and carry on if
you lose your laptop, and (b) move it to a different device if you need to.
By the way, ‘regularly’ in this case means making a commit every 5 or 10 minutes locally, and then
pushing it to GitHub every hour. Small local commits mean you can roll back small changes without
much trouble and pushing remotely less frequently stores your work safely offsite.
To test your progress the project template includes 11 tests. They are initially commented out so
they don’t throw compilation errors because they expect certain classes that you will have to
create.
With a clean template, after running mvn clean test, you should see the following:
mvn clean test.png

Once you have completed a subtask, uncomment relevant test(s) and corresponding imports. For
example, after completing Task 1.1. your test file should look like this:
code.png

Note, we need to import the BattleShip class that is expected to be found in the tests. Then,
uncomment t1_1a and t1_1 b, after completing the Task 1.1.
code2.png

After running mvn clean test, you should see the following, if you have completed the task
correctly:
mvn clean test2.png

Note that not all tasks have tests defined. Make sure you mention in the report which tasks you
have completed.
In the later stages, you can use the command mvn package to generate a jar file that can then be
run from the target folder with:

java -jar assignment1-1.0-SNAPSHOT.jar
Alternatively, you can run the main method directly with:
mvn compile exec:java -Dexec.mainClass=“abdn.scnu.cs.RunGame” -Dexec.args= “arg1 arg2 arg
3”
When the game starts, the console output should look like the example below (the grid size and the
number of ships can be of course specified differently):
screen.png

A detailed description of each task is given below. To complete these tasks, follow the instructions
and ensure you use the provided template. All processes taken to run the final project must be
clearly described. For submission instructions refer to the later sections.
Please read all the information below carefully

Task 1: Create Battleship objects (10 points)

1.1) Create BattleShip.java that extends AbstractBattleShip class. Define a class constructor that
sets the name of the ship based on the passed method parameter, and randomly decides the ship
orientation by assigning “horizontal” or “vertical” values in the shipOrientation variable defined in
the abstract class. You can use the Random class and nextInt () to generate random integers within
certain range.
1.2) Implement the getter and setter methods defined in the AbstractBattleShip class to provide
access to the class variables, i.e., getName (), getHits(), getShipOrientation(), sethits(),
getShipCoordinates(), and setShipCoordinates().
1.3) Implement the functionality of the checkAttack () method. The method should check if the ship
has been already destroyed (i.e., received three hits) and return false if this is the case, even if the
attack coordinates match the position. If any of ship’s coordinates match the attack coordinates
represented by the row/column parameters passed to the method and the number of hits is less

than three, then the method should return true. In case of a successful attack, the method should
also increase the amount of hits registered for this ship.

Task 2: Implement the functionality to display the game grid (35 points)

2.1) Create GameGrid.java that extends the AbstractGameGrid.java. Create a class constructor
that takes three inputs width, height, and number of ships that should be created. The constructor
should create a 2D String array representing the grid, and initialize it using the initializeGrid ()
method defined in the abstract class with the initial value of every element set to “.”.
2.2) Implement the functionality of the generateShips () method to generate required number of
ships and store it in the ships array. Each ship should have assigned name “Ship 1”, “Ship 2”, etc.
2.3) Implement the functionality of placeShip () method. This method should place ships randomly
on the grid. You can utilise the Random () object and nextInt () to give you random integers within
certain range. Make sure that you respect the ship orientation (either vertical or horizontal) when
placing the ship on the grid. Overlapping ships are fine. However, make sure that the ships do not
“overspill” from the grid (e.g., last element of a horizontal ship is located beyond the last element
on the right). Update the grid so the ships are denoted by the “*” symbol. Each ship object should
have its coordinates stored in the shipCoordinates array (defined in the AbstractBattleShip) and all
ship objects should be stored in the ships array (defined in the AbstractGameGrid).
Example of two ships positioned on the grid of size 3 x 10:

.***..*...

......*...

......*...

2.4) Create PlayerGameGrid.java and OpponentGameGrid.java, both extending GameGrid class.
Within both classes define method printGrid () that will print either “Player’s grid” or “Opponent’s
Grid” message followed by the contents of the grid. Opponent’s grid should not reveal the position
of the ships (i.e., “*” symbols) but should show the hits (i.e., using the “X” symbol), misses (i.e.,
using the “%” symbol), and everything else as “.”.

Task 3: Create a mechanism for playing game in rounds and handling the attacks (35 points)

3.1) Create Game.java which should implement the GameControls interface. Define a class
constructor that will create and initialise player’s and opponent’s grids with the appropriate size of
the grid and the number of ships using the classes defined in 2.4. The constructor should take three
parameters: number of rows, number of columns, and number of ships to be placed on the grid.
Implement getter methods to retrieve player’s and opponent’s grids.

3.2) Implement the exitGame () method that ends the program if the input contains value “exit”.
The following message should be printed into the console before exiting: “Exiting game – thank you
for playing”. Note: There are no automated tests for this sub-task.
3.3) Implement checkVictory () method that checks whether either all opponent’s or player’s ships
have been destroyed (i.e. all received three hits). If all ships have been destroyed message should
printed into the console informing the player who won by printing:

“You have won!”

Or

“You have lost!”

3.4) Implement the playRound () method. The method should expect input in a form of a string
where there are two numbers separated by “,”. First number represents the row coordinate and
the second number the column coordinate on our grid (hint: you will need to split the string and
parse characters into numbers). Complete the method so the user input is used to check the
opponent’s grid for ship positions. If the coordinate matches part of the ship print “HIT !!!” into the console, update the number of hits recorded in the corresponding ship object,
and update the grid with symbol “X” denoting the hit.

0,1
HIT Ship 1!!!
.X........
..........
..........

If there is no ship in that position, print “MISS!!!” into the console and update the grid with symbol
“%” denoting the miss.

0,2
MISS!!!
.X%.......
..........
..........

After the user input is processed, the method should generate a random set of coordinates to
simulate an attack on player’s grid. It does not need to be very sophisticated (e.g., you do not need
to use the positions of partially hit ships), but if you have time, you can make your “bot” smarter.
NOTE: you can break up your code into as many helper methods as you want to avoid a code
repetition.

Task 4: Complete your code to implement remaining game controls (10 points)

Note: There are no automated tests for this task
Create a RunGame.java that starts your game. The following functionality should be implemented:
4.1) RunGame class contains the main method that starts the game with user defined inputs for
game grid width, height, and number of ships (hint: use the arguments of the main method). The
main method should create a single instance of Game class.
4.2) The code continuously plays next rounds of the game (i.e., checks for user console input) until
termination conditions are met.
4.3) There are two termination conditions:
• User types a word “exit”. Use the method from Task 3.2.
• Either player’s or opponent’s ships are destroyed. Use the method from Task 3.3
4.4) Input from the player defining attack coordinates should be passed to the playRound () method
defined in the GameControls interface and implemented in the Game class
4.5) Catch an exception thrown with an unexpected input (i.e, if users enters anything else apart
from “exit” or “row,column” coordinates. When the error occurs, print “Incorrect input”.

Task 5: Report and Code Comments (10 points)

Write a report (no more than 5 pages) listing all the tasks and their status (i.e., completed, partially
completed, not attempted). For each task, also include a short paragraph outlining your approach.
At the end of your report, include a section with instructions how to run your code. In your .java
files, please include comments explaining the purpose of individual functions.
Example Game output:
Example Game output .png

Useful Information

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值