首页 > 编程语言 >Java Battleship Game

Java Battleship Game

时间:2022-10-24 11:23:24浏览次数:69  
标签:your Java Battleship ships should Game grid ship method

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

标签:your,Java,Battleship,ships,should,Game,grid,ship,method
From: https://www.cnblogs.com/codewriter/p/16820862.html

相关文章

  • Java中流程控制语句
    概述在一个程序执行的过程中,各条语句的执行顺序对程序的结果是有直接影响的。也就是说,程序的流程对运行结果有直接的影响。所以,我们必须清楚每条语句的执行流程。而且,很多......
  • java统计一个文本文件英文单词
    packagetest;importjava.io.*;importjava.util.*;publicclasswordCount2{publicstaticvoidmain(String[]args)throwsIOException{Filefile=n......
  • [java] html转图片方案
    纯java项目后端进行HTML转图片公司有个需求是在小程序将订单信息按一定样式整理后转成图片。客户点击按钮下载后可以将图片保存,并可以直接在微信群里分享。由于时间紧迫......
  • Java方法
    Java方法方法的定义方法包括一个方法头和一个方法体,修饰符返回值类型方法名(参数类型参数名){...方法体...return返回值;}值传递和引用传递值传......
  • .Net对接Java接口加密不通过?
    前言  相信又不少小伙伴在对接第三方接口时遇到过这种情况:参数、排序、加密方式都按照接口文档进行处理了,可就是签名不通过,然后开始怀疑是不是参数漏了?参与加密的参数不......
  • JavaScript语法注释&数据类型和JavaScript语法变量
    JavaScript语法注释&数据类型注释:1.单行注释://注释内容2.多行注释:/*注释内容*/数据类型:1.原始数据类型(基本数据类型)1.number:数字。整数/小数/NaN(not......
  • 608 Javascript_语法_—元运算符 and 609 Javascript_语法_算数&比较运算符
    Javascript_语法_—元运算符一元运算符:只有一个运算数的运算符       ++,--,+(正号),-(符号)       ++(--),自增,自减           ++(--)先自增或......
  • 【XML】Java创建XML文档
    packageexample01;importorg.w3c.dom.Document;importorg.w3c.dom.Element;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilde......
  • JavaScript发展史和JavaScript语法与html结合方式
    JavaScript发展史JavaScript发展史:1.1992年,Nombase公司,开发出第一门客户端脚本语言,专门用于表单的校验。命名为:C--,后来更名为:ScriptEase2.1995年,Netscape(网景)......
  • JavaScript简介
    JavaScript简介概念:一门客户端脚本语言运行在客户端浏览器中的。每一个浏览器都有javascript的解析引擎脚本语言:不需要编译,直接就可以被浏览器解析执行了功能:......