Let us worry about your assignment instead!

We Helped With This JAVA Programming Homework: Have A Similar One?

SOLVED
CategoryProgramming
SubjectJAVA
DifficultyUndergraduate
StatusSolved
More InfoHelp With Java Assignment
44691

Short Assignment Requirements

write a code in javafx for a battleship game According to the instructions in the file. i translated instructions file to english with google because i do not have an english version. i sent you the english and the hebrew file in docx.if you need more explanation you can contant me.we did the EX1(i uploaded it) , i would like you to do EX 2 +EX 3 further to our work because we must use the code we already created in Exercise 1 and use certain classes that the lecturer wanted us to use. I also have two XML files sent by the lecturer for loading the game, one for Exercise 1 and the second for Exercise 2 and Exercise 3.i uploaded xml file thatyou need to read in the code(we did it in EX1) in order to get the information from the battleship game,. in addition you need to display the javafx game with scene builder with fxml files.i need EX2 until friday and EX 3 for about a week.

Assignment Description

The purpose of the exercise (s) rolling in the course

 

Part 1 - Realizing the game in its basic configuration as a Console application.

Part II - Realization of the game as a graphical application in JavaFX with support for advanced options that are not part of the classic submarine game.

Part 3 - Realizing the game as a web application. The client will be developed using html, javascript, css, and the server will be implemented via servlets and will be run via tomcat.

In this realization, support will be provided for the advanced game that was implemented in Part B.

In this realization each player sits in front of his own computer and is not exposed to the other player.

 

Operating instructions and basic rules of the game

Submarines - the game that is familiar to us all.

 

The game has basic rules, but for the various exercises the rules of the game will be expanded and engineered to suit the spirit of the target.

The game is suitable for 2 participants only.

 

Basic game:

Each participant in the game has a board with two squares (nXn) of squares.

One square symbolizes its "marine" area (if called the submarine board), where it places its submarines at will, while the second square symbolizes the "marine" area of ​​its enemy submarines (which is called the tracking board) and is used to monitor their discoveries.

Each slot has its own coordinates (there is a numbering on the side of the board (as a number) and at the top (as an English sign).

 

Placing the submarines

There are several rules according to which the submarines are placed on the board:

Place the submarines vertically or horizontally, not diagonally.

All tiles belonging to any submersible shall be placed continuously (without "holes").

Do not overlap the submarines (ie, one will be placed on the other fully or partially)

Do not place one submarine near the other, including diagonally.

 

** Amount, direction (row / column), shading sizes and subset placement in the game boards will be given as input to the game (of course, check the correctness of the input according to the above instructions).

 

the progress of the game

Each player in turn "attacks" the opponent in a certain box.

The same player will mark on his watch board if he has hit or missed the submarines, and will also be marked on the opponent's submarine board as a hit / miss.

If he misses, his turn will be for the second game, but if he gets hit he will be given another turn, which he will use to hit the other squares where there are submarines.

A submarine is considered "imprinted" - if all the squares in which it was stretched were damaged.

In the event that a "validated" player is a slot that has already been "attacked" in the past by him, the player will receive another turn and the position of the slot that the "Attack"

 

the Purpose of the game

The winner is the player who has succeeded in "drowning" all his opponent's submarines first

Advanced game:

In this variation we add 2 elements to the game.

 

1. New type of submarine - L-shaped submarine.

An L-shaped submarine of n size will have n slots in a row and n squares in a column.

1.      The submarine can be in 4 directions possible (in this example n = 3)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

DOWN_RIGHT

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

UP_RIGHT

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

RIGHT_UP

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

RIGHT_DOWN

      

All submarine placement laws also apply to submarines of this type.

 

2. Mine

A mine is an element the size of a single slot that the player can add to his submarine board at any stage during the game, provided that the slot he chooses to place is free and not attached to any other submarine. (Ie, the installation in accordance with the rules for placing the submarines).

 

How a mine works:

In the event that the player whose turn is attacking a slot with a mine, then the identical slot will be attacked in the coordinates on his submarine board

(Meaning that the player attacked his own tablet in practice).

Fishing scenario:

Player a player b

Player a player b

In the submarine board there is a submarine that stretches over squares

In the submarine board there is a submarine that stretches over squares

  3 / A, 3 / B, 3 / C

Different steps during the game

Different steps during the game

Places a mine in square 3 / B - loses its turn

Places a mine in square 3 / B - loses its turn

Validates slot 2 / A

Different steps during the game

1.      Different steps during the game

Validates slot 3 / B

Validates slot 3 / B

Since a mine is placed in this square on a player board, the following occurs:

 

 

Specific guidelines for implementing the "submarines" exercise

 

1. The game boards are square mXm so that 5 <= m <= 20.

2. As part of the input, a list of the submarines shall be given - each submarine shall include the type of submarine (standard or L-shaped), its size, its mark and how many times it should be placed on the board.

3. Each of the players shall be given a list of submarine positions - each placement shall include the submarine (from the list of submarines under section 2), direction (row / column / direction of the L-shaped submarine) and position The top left slot for a regular submarine, and the corner corner for a submarine in the form of a signal

For example: A normal type submarine, 3 in the direction of ROW and 2 / A, will be positioned as follows:

E

D

C

B

A

 

 

 

 

 

1

 

 

 

 

 

2

 

 

 

 

 

3

 

 

 

 

 

4

 

 

 

 

 

5

For the L-type submarine, 3 in the UP_RIGHT direction and 2 / B position

 

E

D

C

B

A

 

 

 

 

 

1

 

 

 

 

 

2

 

 

 

 

 

3

 

 

 

 

 

4

 

 

 

 

 

5

4. You must be able to monitor and display at any given moment the score and status of the players, as well as statistics (where applicable).

5. The information about the game will be uploaded from the XML file (example and explanation in Appendix B). This information shall include, inter alia:

Game variation (basic / advanced)

Table size

Details of the types of submarines and game boards - as listed in sections 2 and 3

Details of the initial quantity of mines.

6. All inputs and outputs and interaction with the user will be in English only, and from left to right (where relevant in the various UI interfaces).

 

Hints about the design and implementation

1. The main goal is to develop a component that will constitute the game engine and additional elements (in each exercise) that will form the user interface that will be run over the game engine.

The game engine will contain all the logical information about the game (s) being managed now, board mode, score, move history, etc.

2. Think about how you would describe the tiles on the game board and their design; Think about the way you manage each player's score, etc.

3. Throughout the various exercises you will develop different game configurations (basic game, advanced game, etc.). It makes sense that each game configuration will have a manager who is responsible for managing it. It would not be absurd that one manager will talk to his friend and so on.

4. It can be said that each exercise defines a fundamentally different interface layer of the game, but each exercise is ultimately conducted in front of the single game engine. It is therefore very worthwhile and desirable that starting from the beginning, the code structure and the project will reflect this issue - that is, you will have a module of the game engine that is "independent" and next to it are modules of the various interfaces (javafx, web) that know how to "talk" to the game engine. Details of such an exercise will of course be given during the course.,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Requirements-EX 1

 

1. In this exercise we will actualize the game in its original basic version (GameType = Basic), the victory index will be only according to the number of squares hit.

 

2. The game will contain exactly 2 players. No less and no more. No need to define their names. We will turn to them as the first player and second player.

In this version the two players sit in front of the same computer and games against the same screen - it is important to describe at any given moment who the relevant player is his turn and so on.

 

3. All table data - board size, submarine types, size, size, adjustment and placement in the plates shall be provided as part of the .xml file.

 

4. At any stage of the game, the user will be presented with a list of possible commands through which he will navigate the game (see below)

Note that some commands require different inputs from the user. It is important to clarify at any given moment what are the required inputs from the user in each command, and how they are expected to be received.

 

5. The game boards should be displayed and drawn to the user in the relevant commands (described below). Scales should be displayed for columns and rows (beginning with 1) as well as to ensure that the board is accurately drawn and there will be no indentation problems (if these are large scale tables).

 

6. There are orders that it is unreasonable to execute them if they have not been preceded by other orders. If this happens, an error message that is relevant to the user should be displayed and the game can be continued.

 

7. Check the integrity of the input and respond appropriately to the input that is not working properly.

 

8. The correctness tests to be performed in connection with the loading of the game file are:

8.1. File exists, and is XML type.

8.2. When uploading a new file, make sure that there is no game already played in the game (also possible by blocking command # 1 from being performed if an active game already exists in the system).

8.3. The size of the board is between 5 and 20 (inclusive).

8.4. Each submarine on the submarine list appears on the board of each player exactly as many times as it is defined.

8.5. On each board there are no submarines that violate the rules of placement (adjacent, overlapping, etc.)

8.6. Check input integrity as part of user interaction. (Eg if you expect to get the row / column number as part of a command, and the user inserts a string and not a number - you must locate it, notify the user and allow the game to proceed while selecting another command).

 

9. No matter how you present the board and the different details. Each one is entitled to choose the path that is convenient for him, and apart from the fact that this method will be informative and provide the required information to the user and will meet all the functional requirements (display the boards,

 

10. There is no need to use different colors during this exercise when printing to the console.

Also, there is no need to clean the screen between command and command.

 

11. The game ends when one of the players hits all the opponent's submarines (in all slots where the submarines are deployed). If you reach the end of the game it must be identified automatically, clearly declare the winner and show relevant statistics. At the end of the game the program ends and goes out.

It is also possible that one of the players will decide to "retire" from the game.

 

12. The orders to be supported (order of orders requires):

** Selecting the command is by entering the number of the command - meaning the input is the number of the command.

 

1. Reading a game information file from the user.

This command actually loads a game into a system that will later be played.

The file will be an XML file whose details are presented in the appendix to this exercise.

(Note that the xml file contains additional details that are not important for this exercise but only for the following exercises to simplify the process you use in the file).

The integrity of the data appearing in the file as defined in Section 8 should be ascertained.

(As part of the test, illegal files will be loaded into the system to determine the response).

The file can be found in any valid directory on your computer (including a directory with spaces, Hebrew letters, etc.). Make sure this does not fool you.

 

If this command passes successfully, a message is displayed that is relevant to the players.

As long as Command No 2 is invoked, you can continue to upload additional files to.

 

2. Starting a game

The command initializes the game and shows the players the state of the game. (As described in command 3) Once this command has been successfully executed, commands 1 and 2 should not be re-run (since the game is already running ...).

Do not allow the choice of Command 2 when there is no file loaded in the system (an error message should be displayed in this case).

 

3. Display the game mode

This command will return at any given time

i. Current player boards. The plates with scales along their lengths and widths should be drawn to allow for a precise slot on the board.

ii. Player Score.

iii. Indicates the identity of the current player.

 

4. Making a move

This command will give the user the coordinates of the tile he wants to attack.

The coordinates can come in any format you choose provided that the format you expect to receive will be clarified to the user.

 

5. Receive statistics

This command returns a number of information:

1. How many turns have been made so far (each player who played - considered one turn).

2. How much time has passed since the beginning of the game (since order 2 has been given). Time will be given in minutes and seconds.

If it is over an hour - you can continue to give the time in minutes and seconds format (e.g. 84:32)

3. For each player, a current score must be specified (some squares are valid and valid).

4. For each player, the number of misses should be indicated (some slots are valid but missed)

5. For each player, the average time required to perform a move (square attack)

 

6. Retirement / Termination from the Game

Each player can choose to finish the game proactively.

In this situation the player remaining in the game wins a technical victory, regardless of the score.

In each case of the end of the game, the status of the tables (the tables with the "maritime" area of ​​each player) will be displayed in the final of both players as well as the statistics data as described in command 5.

At the end of the command, the program will finish and finish.

There is no need to support (at this point) the continuation of another game after the end of one game (unless you are making Bonus # 3)

 

 

 

 

 

 

 

 

Bonuses

# Nature type What is worth to me? How much is it worth to me?

1 Preceding a cure for a mine ... Exercising the mine (required in exercise 2).

The mine as described above is an element the size of a single square which, when attacked, is attacked by the corresponding square on the attacking player board.

If this bonus is used, please specify this and add command number 7 - in this command we will get the coordinates for placing the mine.

This placement will be carried out in accordance with the submarine deployment rules.

If the player whose turn hits the mine, this will be considered an injury to the submarine, and if the mine hits the player board (this is the essence of the mine), the score will be awarded to a second player.

Due to the fact that the number of possible mines is not listed in Exercise Details 1, the number of mines must be limited to 2 per player in this bonus. Because it will give you an indication of how generic you have written the game engine and how much is fit to handle and contain future requirements of Exercise 2 and 3 ...

 

Because exercise 2 is what Amos is a rope ... 5 points

(Up to 100)

2. Increase the minor head to allow the program to continue running after Command No. 6.

Once a user chooses to finish the game - he returns to the initial position allowing him to load a new game, or restart the current game.

If you apply this bonus, you must add another command (say 8) that allows a real and final end of the program and an orderly exit from it. That's what-it-in-a-little-pity ... 2 points

(Up to 100)

3 Raising a handsome head Loading and saving a game.

Allow to save a game, and load it later (special commands should be added).

Once you have saved a game, choose a destination file name and save the game. The game can proceed normally after the retention point.

Once a game is claimed, it continues exactly from the position in which it was last saved.

Saving and loading the game can be done to any file format you want - your decision is cool to Allah ... 6 points

(Over 100)

Increasing Honorable Head Computer Player.

Write an algorithm that allows a computer player to play submarines.

The algorithm must be smart enough to understand the state of the game and not just to grill slots on the board.

For example, if a block has been hit then the next attacks will be in its area, and if the injured battalions are in line then continue attacking the same line next to the hit squares.

 

If you realize the bonus you must explain your algorithm in the ReadMe file.

You will also need to add a special command to do this. This command will be allowed only between commands 1 and 2 (after loading the file before the start of the game) and you will be able to choose which of the two players will be computerized.

 

The score for this bonus will be given at the discretion of the lecturer depending on the correctness and complexity of the algorithm.

Proof that algorithm algorithms may be useful in De Yuma's affairs ... 10 points

(Over 100)

 

 

 

 

 

 

RequirementsEX 2:

 

1. In this exercise you must support another game configuration: Advanced game.

This means that L-shaped submarines and landmines must be supported.

In this version, the score of the game will be changed to the score on the basis of the subscribed submarines (and not according to the number of squares hit) - so that each submarine that is scored will be given a score as called from the xml file.

This score will appear in addition to the misses and injuries (see Command 5 in Exercise 1 - Statistics Receipt)

 

2. The course of the game:

2.1. The game will be loaded from the .xml file, and a relevant message will be displayed at the end of the game.

Note: You must enable this mode to load another game file, as long as you did not press the Start Game button.

The xml file will only be loaded using the file chooser dialog! (Do not assume that the file will wait for you in a dedicated library, or that the checker will type the contents into a text box, etc.).

The file can be found in any valid directory on your computer (including a directory with spaces, Hebrew letters, etc.). Make sure this does not fool you.

2.2. Click the start button to enter active game mode, and display the first player boards

(Submarine board and player's watch panel)

2.3. In turn, the player can choose a free slot (which is not attacked in the past) to attack the opponent

(This will, of course, be done graphically by choosing with the mouse rather than by typing in a text field).

If the attack is successful and hits the submarine, the player will have another turn and his injury count will be updated.

If he misses, his missed count will be updated and the line will be transferred to the second player.

If you select a box that has been attacked in the past, you can only continue to let the player choose a free slot.

In each case, a clear indication is required.

2.4. In addition, the player can place a mine (see section 6) - placing a mine constitutes a move in the game and after placing the turn the player moves to the second player.

2.5. When a player's turn comes, he can decide to retire from the game (using a dedicated button).

2.6. The game ends according to all the procedures for completing the game from Exercise 1 Section 11, and the main points are:

When one of the players has retired

When all the submarines of one of the players are drowned

At the end of the game you must present the players and the total score they have achieved.

 

 

3. For the player whose turn it is his turn, a number of details must be presented:

3.1. An indication of who the player is.

3.2. Types of submarines and their size in the table.

For example, if the player's board has 3 submarines of size 2, this should be shown if one of them is drowned.

3.3. The types of submarines and the number of submarines remaining for each type to the opponent (similar to the previous section).

3.4. It should be displayed.

3.5. The number of hits and misses, the mean time of the move and all the other statistical data as specified in Exercise 1 should be presented.

 

4. How to calculate the score: If the player's attack resulted in a submarine ring, the point (as shown in the xml file) will be added to its score.

 

5. At any given time, you must present:

5.1. The number of the current move.

5.2. The identity of the current player.

5.3. Final score of each of the players in the game (who are not the current player).

5.4. For the player whose turn it is, his injuries and misses should be presented and the average time taken.

5.5. The number of available mines left to the player.

5.6. The types of submarines and the number of submarines remaining to each opponent.

I would like to say that the player knew how many submarines he had left to drown.

 

6. Mine

A mine is an element the size of a single slot that the player can add to his submarine board at any stage during the game, provided that the slot he chooses to place is free and not attached to any other submarine. (Ie, the installation in accordance with the rules for placing the submarines).

This will be done by dragging a mine to the submarine board (drag & drop)

Do not realize this by typing the coordinates into a text box

 

How a mine works:

If the player whose turn is attacking a slot with a mine, the same tile will be attacked in the coordinates of his submarine board.

 

Highlights:

When attacking the mine, if the opponent's submarine board has the identical slot in the empty coordinates it will be marked as a foul on both the opponent's submarine board and the player's tracking board.

When attacking the mine, if the opponent's submarine board has the same square as the submarine coordinates, this slot will be marked as hitting both the opponent's submarine board and the player's tracking board.

When attacking the mine, if the opponent's submarine board in the same square in the coordinates has a mine, this mine will be removed from the opponent's submarine board and the square will be marked as a foul on both the opponent's submarine board and the player's tracking board.

When attacking the mine, if the opponent's submarine board has already been attacked (marked as an offense or an injury), the check mark (miss / hit) will not be changed on both the opponent's submarine board and the player's tracking board.

In any event, damage to the mine will not score a player, but the mine injury will be recorded as an injury to the submarine and not as an error in the statistics counters.

If the mine causes a submarine to be painted, it will be awarded to the second player, but its vulnerability counter will not be updated.

Placing a mine is part of the player's turn and then the turn will be passed on to the other player (similar to the foul)

The number of mines each player has is limited and equal, there is no obligation to place them or use them all - each player can choose whether or not to use the mines in his possession.

The player who hit the mine will lose his turn (similar to the foul).

A mine that has been hit will be marked as an impact on the board - it will not be possible to place a new mine in the same place.

 

 

7. L-shaped submarine

Advanced game support L-shaped submarines,

A n-size submarine will have n slots in a row and n slots in a column, the submarine can be in 4 directions (as described).

Of course, all submarine placement rules also apply to submarines of this type.

Note that in the xml file, the reference point for placing an L-shaped submarine is the corner where the row and column squares meet.

8. When the game ends, allow it to "stay in the air" and allow the user to navigate through the various moves using two dedicated buttons: prev and next.

Clicking on each button will roll the game board one row back or forward (depending on) and will be able to see what was the situation in each move.

In each move you have to show who the player is, his turn, his points, his updated plates for the same move, and highlight the move he made (attack / mine) and what were the results of that move.

You must also allow the user to load a new game file at this time or restart the current game.

Do not show the moves by using snapshots or screen shots or by displaying images - but you must present the move on the boards you created for the game in the JavaFX interface.

 

9. As part of the game test, the screen size will be changed and your system will be checked in different screen sizes. You must ensure that the UI components are properly organized and that they are also properly sized. It is highly recommended to use a scroll pane to view large content within a small screen area. In particular, you have to make sure to show the game board (which can reach different sizes) in a proper manner so that none of its components will be hidden because of the size of the screen is too small. Also consider how not to hide the game boards as well as the ability to move and progress in the game.

To remove any doubt (!), Do not "handle" the resize by simply preventing the screen from being resizable.

 

If you have used bonuses in the previous exercise, it is not necessary to make them work in this exercise, but if this is possible, it will warm my heart (for the avoidance of doubt, heating my heart is not translated into raising points).

 

Bonuses

Where it's relevant (bonus 2) Bonuses should be "off" to begin with so that the examiner will "open" them only for the sake of their testing.

# Nature type What is worth to me? How much is it worth to me?

1 Increase the handsome head and skin replacement option for the game. This bonus will realize (at least) 2 additional color schemes on the dipole kit, allowing the user to replace the color schemes. Please note that the color scheme includes (at the very least):

1. Change the background of the entire screen

2. Replacing the appearance of the buttons and panels on the screen

3. Replacing the font and size of each label on the screen because it is nevertheless an exercise in the graphical interface - and what is more graphic than that ??? 5 points

(Up to 100)

2 Raising a light head Simulates the following animations:

Animation to attack a slot - missed and damaged

Animation for embedding a submarine.

Animation and mine impact.

Any other animation you see fit will be welcomed ...

Animation should be done at most for 2 seconds

You can also disable these animations so that it will not slow the progress of the game ... so easy ... 5 points

(Over 100)

3 Increase the light head Load the xml file using the task mechanism, including the status of the task at any given moment (file opening, loading, error validation, dictionary processing, etc.) Quite simple 4 points

(Up to 100)

4. Increasing a respectable head by allowing a player to edit his own submarine board rather than using the existing figure.

In this exercise, the size of the board, the number of submarines and their points will be according to the number in the xml file, but the board itself will be according to the player's discretion.

If this bonus is realized, the board will be edited before clicking on the game start button and after loading a valid xml file.

Editing the board will be possible for each player, but it is not mandatory - that is, a player may remain with the board from the xml file while a player will edit the board.

Editing the clipboard will of course be graphical (do not realize this by typing the coordinates into a text box) and oblige the editing player to comply with all rules for placing the submarines

Cool to Allah ... 8 points

(Over 100)

 

RequirementsEX 3:

1. In this exercise you must develop a multiplayer mode.

Each user (= player) who enters the channel goes through a sign up process and can upload a game file to which a player wants to play. When the required conditions are fulfilled, the players who have registered for a particular game meet and the game takes place.

The game configuration will be as in Exercise 2, with its rules and conduct as defined in Exercise 2 (including L-shaped submarine, mine, and submarine darting method)

 

2. In this exercise every player plays from his browser, sees only his board, and his interaction with the other player is actually done only by the server.

 

3. Formally, a normal gaming experience should be supported above chrome only.

Even if you've developed over FF or IE (tfu ..) - make sure you're working well over chrome - the app will only be checked over chrome. In short, chrome, kapish?

 

4. As a general rule, all information in the system must be updated automatically for each player (each browser) in the form of Pull as we learned in the final example.

 

5. There is no need to support the back as a means of switching between the different screens. Also assume that we will not abuse the application and will not change the address bar, cookies will not be deleted, etc. The test will be performed only by using the functionality that will be available in the various game screens.

 

6. There is no need to save data beyond the current instance of the server. That is when the server drops all the data disappear. Do not keep registered users, completed games, etc.

 

7. Make sure that the game screens are a good type of resize and do not miss any detail (as in Exercise 2).

 

 

8. In this exercise there are 3 main steps:

 

1. Sign up screen

This screen should allow the user to register for the system. The user has his own name. There will be several participants with the same name. Of course, you should make sure this is alerted if something tries to register under a name that already exists.

After successful registration you will be taken to screen 2.

 

2. Screen concentration of all existing games

This screen will have two main lists:

List all players currently active in the system

List all possible games in the system

Any registered player can upload and publish their own game.

The game file is of course the xml file (infamous) both in Exercise format 1 and in Exercise 2.

The player must give a title / title to the game he has uploaded - there can not be 2 games under the same name title.

 

Input tests must be performed on the file, and if it is improper to alert the user and not load the game.

In particular, check the following:

1. Each game has a name / title. Do not allow to load a game with a name that already exists in the system.

2. All correct tests performed in Exercise 1 and 2 should also be expressed.

 

A user can choose to upload a game to the system.

Once a game is uploaded, it will appear in the list of possible games.

For each such game on the list, please provide the following details:

•           Name of the game

The name of the user who uploaded the game.

The size of the board (in number).

The type of game - Basic (as in Exercise 1) or Advanced (as in Exercise 2).

Is there a registered user for the game.

Both the list of players listed in the system and the list of possible games in the system must automatically be updated up to a maximum of 2 seconds. (Must be pulled in the form of pull from the server, as demonstrated in the class in the final example).

If a logout is executed, it is deleted from the system records and can be re-registered (also in the same name) .If there are several different browsers from which the user is connected, then from now on he no longer exists in the system. It will also disconnect from it in all other browsers.

Each player can decide that he / she has entered a single game only. It does this by selecting the relevant game from the list and clicking on the login button.

A player may choose to play a game that he or she has uploaded, or any other player's game.

 

A player can retire from a game recorded (from screen number 3) and return to the game screen.

As long as the game has not started - he can subscribe to the same game (or any other game) as he wants.

Once a game starts, you can not register or access it anymore.

 

Once a player chooses to enter the game he is immediately transferred to screen 3.

Once there are 2 players in the game - it starts automatically. (At this stage the players listed in it are already on screen number 3)

 

A game that begins is marked as "active" on screen 2.

 

When a game is over (one way or another) it has to be turned into a re-available game, to be re-registered as a regular game for anything.

 

If one of the players withdraws during the game, the game returns to the list of possible games and is reset like the game ends.

 

The player who uploaded the game must be allowed to delete it if the game is inactive and no users are registered.

 

3. Single play room screen for several participants

This screen will play a single game as exercised in Exercise 1 or 2.

The first player entering the room sees the submarine board of player 1, while the second board the submarine of the second player.

Once there are 2 players in a game (in a room) - it starts automatically.

This must be clearly stated to the players (who are waiting for the second player, the game has started, etc.)

At any given moment, the game type (normal / advanced) must be displayed and the player is his turn.

For each player, his / her name must be displayed at any given time.

 

the progress of the game

As long as it is not the turn of the player - he can only look at the boards and can not change them.

Once his turn comes he can make a move as defined in Exercise 2.

 

End game

As part of the orders a player can perform, while it is his turn alone, he can also choose to retire from the game

(As in Exercise 2).

In this situation the game is over, and you have to present a summary that includes statistics - similar to Exercise 2.

At the end of the game, in one form or another, after receiving the summary, users are taken

back to screen 2

 

Bonuses

# Nature type What is worth to me? How much is it worth to me?

1 Increase the handsome head and allow the player to participate in more than one game. In this mode the player must be allowed to enter the TV again, this time as a login user, and then he can reach the second screen and can choose to register for another game. not Standart. 10 points

(Up to 100)

2 Increase the handsome head Enable the playing of the game by the ability to run all the steps performed The player should be allowed to play the game from start to finish and reverse: from the end to the beginning.

Playing the game does not change the current board mode - it only displays replay.

Playing the game can be done by the user during the whole game, even when it is not his turn.If his turn comes during the playing of a game - he gets a signal on it.

Play The game will be played using 2 buttons of prev and next.

A third button, exit replay mode, allows you to exit the play mode and return to the normal game mode.

In the final of the game, allow the player (s) to run the game backwards or return back to screen 2 when he wishes (f). If you have realized it correctly, it should be small and be cool to Allah ... 7 points

(Up to 100)

3 Increasing the head of Haviva allowed the player to participate in the game as an observer from the side. In this situation, a player can still enter the game room of a game that has already started, and can see the course of the game but he is not an active player himself and can not play.

The player from the side will see at any given time the game boards - all four boards (2 per player)

The side-view player will receive all the animations received by all the active players (such as injury, miss, placement and mine explosion, etc.).

In this situation, it is necessary to show in addition to the list of active players in the game a list of all the players watching from the side.

The two lists above should be shown both for the active player and for the side-view observer.

In the active games room screen you must add an extra column for each game that shows how many players watching from the side are currently in it

You can join and watch the game before it starts.

A side-view player should be allowed to retire from his side and return to the active games screen.

(Of course, you must update the number of watching players from the side, as well as the lists of players in the relevant places). Cool functionality, right! 10 points

(Over 100)

4 Increasing the cool head! Allow players to chat, including the game itself.

The chat should be conducted entirely against the server, of course, in the way everyone sees what everyone is writing. (Mowooooooood is like the final sample)

The chat is only between players who are registered for the game (and not the players watching if someone has played the bonus 3). 10 points

(Up to 100)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

The description of the game on its various bikes is given using an XML file.

During the test, the system will be tested using several different files, some of which are valid and some of them are faulty, in order to see if and how the system responds to the errors.

Examine the sample files uploaded to the Mama page and make sure you understand their details and structures.

GameType Definition - GameType:

This is an element that defines the type of game:

 

The contents of the element have several possible values:

BASIC - Basic game will be played in Exercise 1 and 3.

ADVANCE - Advanced game will be played in Exercise 2 and 3.

Board size - BoardSize:

This is the element that defines the size of game boards.

<boardSize> 5 </ boardSize>

 

Possible sizes 5 - 20 inclusive

Specifying Submarine Types - ShipTypes:

This is an element that contains the list of submarines to be placed • Each submarine is defined as:

o id - Submarine type

o category - submarine category - REGULAR or L_SHAPE

o amount - The amount of submarines of this type to be placed on the submarine board.

o length - The size of the submarine - the number of squares that this submarine is interpreted.

o score - the scoring value for this submarine ring (we'll use an advanced game)

 

Setting the number of mines:

This element contains the number of mines available to each player.

 

Possible sizes - any positive integer.

Defining Boards Game Boards:

This element contains 2 panels (first board for player 1, s

econd board for player 2)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Each board contains a list of submarines

Each submarine contains the following settings:

o Submarine type - this value should equal one of the names in the submarine list (shipTypeId)

o Position of the submarine on the board (row X and column Y)

o Direction of the submarine

במשחק In this basic game, the value will be COLUM / ROW

במשחק In an advanced game, for L-shaped submarines, this value will be:

RIGHT_DOWN / RIGHT_UP / UP_RIGHT / DOWN_RIGHT

 

 

Appendix C - Schema file for verifying the XML file

 

The XML file is linked to a schema that defines its various parts and their legality.

We recommend that you use a schema to verify that you have set the file to correct.

(Agreement was raised to the Mama system).

 

 

Below is a diagram that describes the file structure as defined by consent .

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Assignment Code



package BattleShipJAXB;

import javax.annotation.Generated;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Java class for anonymous complex type.
 *
 * <p>The following schema fragment specifies the expected content contained within this class.
 *
 * <pre>
 * &lt;complexType>
 *   &lt;complexContent>
 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       &lt;sequence>
 *         &lt;element name="GameType">
 *           &lt;simpleType>
 *             &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *               &lt;enumeration value="BASIC"/>
 *               &lt;enumeration value="ADVANCE"/>
 *             &lt;/restriction>
 *           &lt;/simpleType>
 *         &lt;/element>
 *         &lt;element name="boardSize" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         &lt;element name="shipTypes">
 *           &lt;complexType>
 *             &lt;complexContent>
 *               &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 &lt;sequence>
 *                   &lt;element name="shipType" maxOccurs="unbounded">
 *                     &lt;complexType>
 *                       &lt;complexContent>
 *                         &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                           &lt;sequence>
 *                             &lt;element name="category">
 *                               &lt;simpleType>
 *                                 &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *                                   &lt;enumeration value="REGULAR"/>
 *                                   &lt;enumeration value="L_SHAPE"/>
 *                                 &lt;/restriction>
 *                               &lt;/simpleType>
 *                             &lt;/element>
 *                             &lt;element name="amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *                             &lt;element name="length" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *                             &lt;element name="score" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *                           &lt;/sequence>
 *                           &lt;attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
 *                         &lt;/restriction>
 *                       &lt;/complexContent>
 *                     &lt;/complexType>
 *                   &lt;/element>
 *                 &lt;/sequence>
 *               &lt;/restriction>
 *             &lt;/complexContent>
 *           &lt;/complexType>
 *         &lt;/element>
 *         &lt;element name="mine" minOccurs="0">
 *           &lt;complexType>
 *             &lt;complexContent>
 *               &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 &lt;sequence>
 *                   &lt;element name="amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *                 &lt;/sequence>
 *               &lt;/restriction>
 *             &lt;/complexContent>
 *           &lt;/complexType>
 *         &lt;/element>
 *         &lt;element name="boards">
 *           &lt;complexType>
 *             &lt;complexContent>
 *               &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 &lt;sequence>
 *                   &lt;element name="board" maxOccurs="2" minOccurs="2">
 *                     &lt;complexType>
 *                       &lt;complexContent>
 *                         &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                           &lt;sequence>
 *                             &lt;element name="ship" maxOccurs="unbounded">
 *                               &lt;complexType>
 *                                 &lt;complexContent>
 *                                   &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                                     &lt;sequence>
 *                                       &lt;element name="shipTypeId" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *                                       &lt;element name="position">
 *                                         &lt;complexType>
 *                                           &lt;complexContent>
 *                                             &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                                               &lt;attribute name="x" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
 *                                               &lt;attribute name="y" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
 *                                             &lt;/restriction>
 *                                           &lt;/complexContent>
 *                                         &lt;/complexType>
 *                                       &lt;/element>
 *                                       &lt;element name="direction">
 *                                         &lt;simpleType>
 *                                           &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *                                             &lt;enumeration value="ROW"/>
 *                                             &lt;enumeration value="COLUMN"/>
 *                                             &lt;enumeration value="RIGHT_DOWN"/>
 *                                             &lt;enumeration value="RIGHT_UP"/>
 *                                             &lt;enumeration value="UP_RIGHT"/>
 *                                             &lt;enumeration value="DOWN_RIGHT"/>
 *                                           &lt;/restriction>
 *                                         &lt;/simpleType>
 *                                       &lt;/element>
 *                                     &lt;/sequence>
 *                                   &lt;/restriction>
 *                                 &lt;/complexContent>
 *                               &lt;/complexType>
 *                             &lt;/element>
 *                           &lt;/sequence>
 *                         &lt;/restriction>
 *                       &lt;/complexContent>
 *                     &lt;/complexType>
 *                   &lt;/element>
 *                 &lt;/sequence>
 *               &lt;/restriction>
 *             &lt;/complexContent>
 *           &lt;/complexType>
 *         &lt;/element>
 *       &lt;/sequence>
 *     &lt;/restriction>
 *   &lt;/complexContent>
 * &lt;/complexType>
 * </pre>
 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
        "gameType",
        "boardSize",
        "shipTypes",
        "mine",
        "boards"
})
@XmlRootElement(name = "BattleShipGame")
@Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
public class BattleShipGame {

    @XmlElement(name = "GameType", required = true)
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    protected String gameType;
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    protected int boardSize;
    @XmlElement(required = true)
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    protected BattleShipGame.ShipTypes shipTypes;
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    protected BattleShipGame.Mine mine;
    @XmlElement(required = true)
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    protected BattleShipGame.Boards boards;

    /**
     * Gets the value of the gameType property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public String getGameType() {
        return gameType;
    }

    /**
     * Sets the value of the gameType property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public void setGameType(String value) {
        this.gameType = value;
    }

    /**
     * Gets the value of the boardSize property.
     *
     */
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public int getBoardSize() {
        return boardSize;
    }

    /**
     * Sets the value of the boardSize property.
     *
     */
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public void setBoardSize(int value) {
        this.boardSize = value;
    }

    /**
     * Gets the value of the shipTypes property.
     *
     * @return
     *     possible object is
     *     {@link BattleShipGame.ShipTypes }
     *
     */
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public BattleShipGame.ShipTypes getShipTypes() {
        return shipTypes;
    }

    /**
     * Sets the value of the shipTypes property.
     *
     * @param value
     *     allowed object is
     *     {@link BattleShipGame.ShipTypes }
     *
     */
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public void setShipTypes(BattleShipGame.ShipTypes value) {
        this.shipTypes = value;
    }

    /**
     * Gets the value of the mine property.
     *
     * @return
     *     possible object is
     *     {@link BattleShipGame.Mine }
     *
     */
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public BattleShipGame.Mine getMine() {
        return mine;
    }

    /**
     * Sets the value of the mine property.
     *
     * @param value
     *     allowed object is
     *     {@link BattleShipGame.Mine }
     *
     */
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public void setMine(BattleShipGame.Mine value) {
        this.mine = value;
    }

    /**
     * Gets the value of the boards property.
     *
     * @return
     *     possible object is
     *     {@link BattleShipGame.Boards }
     *
     */
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public BattleShipGame.Boards getBoards() {
        return boards;
    }

    /**
     * Sets the value of the boards property.
     *
     * @param value
     *     allowed object is
     *     {@link BattleShipGame.Boards }
     *
     */
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public void setBoards(BattleShipGame.Boards value) {
        this.boards = value;
    }
    /**
     * <p>Java class for anonymous complex type.
     *
     * <p>The following schema fragment specifies the expected content contained within this class.
     *
     * <pre>
     * &lt;complexType>
     *   &lt;complexContent>
     *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       &lt;sequence>
     *         &lt;element name="board" maxOccurs="2" minOccurs="2">
     *           &lt;complexType>
     *             &lt;complexContent>
     *               &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *                 &lt;sequence>
     *                   &lt;element name="ship" maxOccurs="unbounded">
     *                     &lt;complexType>
     *                       &lt;complexContent>
     *                         &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *                           &lt;sequence>
     *                             &lt;element name="shipTypeId" type="{http://www.w3.org/2001/XMLSchema}string"/>
     *                             &lt;element name="position">
     *                               &lt;complexType>
     *                                 &lt;complexContent>
     *                                   &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *                                     &lt;attribute name="x" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
     *                                     &lt;attribute name="y" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
     *                                   &lt;/restriction>
     *                                 &lt;/complexContent>
     *                               &lt;/complexType>
     *                             &lt;/element>
     *                             &lt;element name="direction">
     *                               &lt;simpleType>
     *                                 &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
     *                                   &lt;enumeration value="ROW"/>
     *                                   &lt;enumeration value="COLUMN"/>
     *                                   &lt;enumeration value="RIGHT_DOWN"/>
     *                                   &lt;enumeration value="RIGHT_UP"/>
     *                                   &lt;enumeration value="UP_RIGHT"/>
     *                                   &lt;enumeration value="DOWN_RIGHT"/>
     *                                 &lt;/restriction>
     *                               &lt;/simpleType>
     *                             &lt;/element>
     *                           &lt;/sequence>
     *                         &lt;/restriction>
     *                       &lt;/complexContent>
     *                     &lt;/complexType>
     *                   &lt;/element>
     *                 &lt;/sequence>
     *               &lt;/restriction>
     *             &lt;/complexContent>
     *           &lt;/complexType>
     *         &lt;/element>
     *       &lt;/sequence>
     *     &lt;/restriction>
     *   &lt;/complexContent>
     * &lt;/complexType>
     * </pre>
     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
            "board"
    })
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public static class Boards {

        @XmlElement(required = true)
        @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
        protected List<BattleShipGame.Boards.Board> board;

        /**
         * Gets the value of the board property.
         *
         * <p>
         * This accessor method returns a reference to the live list,
         * not a snapshot. Therefore any modification you make to the
         * returned list will be present inside the JAXB object.
         * This is why there is not a <CODE>set</CODE> method for the board property.
         *
         * <p>
         * For example, to add a new item, do as follows:
         * <pre>
         *    getBoard().add(newItem);
         * </pre>
         *
         *
         * <p>
         * Objects of the following type(s) are allowed in the list
         * {@link BattleShipGame.Boards.Board }
         *
         *
         */
        @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
        public List<BattleShipGame.Boards.Board> getBoard() {
            if (board == null) {
                board = new ArrayList<BattleShipGame.Boards.Board>();
            }
            return this.board;
        }
        /**
         * <p>Java class for anonymous complex type.
         *
         * <p>The following schema fragment specifies the expected content contained within this class.
         *
         * <pre>
         * &lt;complexType>
         *   &lt;complexContent>
         *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
         *       &lt;sequence>
         *         &lt;element name="ship" maxOccurs="unbounded">
         *           &lt;complexType>
         *             &lt;complexContent>
         *               &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
         *                 &lt;sequence>
         *                   &lt;element name="shipTypeId" type="{http://www.w3.org/2001/XMLSchema}string"/>
         *                   &lt;element name="position">
         *                     &lt;complexType>
         *                       &lt;complexContent>
         *                         &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
         *                           &lt;attribute name="x" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
         *                           &lt;attribute name="y" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
         *                         &lt;/restriction>
         *                       &lt;/complexContent>
         *                     &lt;/complexType>
         *                   &lt;/element>
         *                   &lt;element name="direction">
         *                     &lt;simpleType>
         *                       &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
         *                         &lt;enumeration value="ROW"/>
         *                         &lt;enumeration value="COLUMN"/>
         *                         &lt;enumeration value="RIGHT_DOWN"/>
         *                         &lt;enumeration value="RIGHT_UP"/>
         *                         &lt;enumeration value="UP_RIGHT"/>
         *                         &lt;enumeration value="DOWN_RIGHT"/>
         *                       &lt;/restriction>
         *                     &lt;/simpleType>
         *                   &lt;/element>
         *                 &lt;/sequence>
         *               &lt;/restriction>
         *             &lt;/complexContent>
         *           &lt;/complexType>
         *         &lt;/element>
         *       &lt;/sequence>
         *     &lt;/restriction>
         *   &lt;/complexContent>
         * &lt;/complexType>
         * </pre>
         *
         *
         */
        @XmlAccessorType(XmlAccessType.FIELD)
        @XmlType(name = "", propOrder = {
                "ship"
        })
        @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
        public static class Board {

            @XmlElement(required = true)
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            protected List<BattleShipGame.Boards.Board.Ship> ship;

            /**
             * Gets the value of the ship property.
             *
             * <p>
             * This accessor method returns a reference to the live list,
             * not a snapshot. Therefore any modification you make to the
             * returned list will be present inside the JAXB object.
             * This is why there is not a <CODE>set</CODE> method for the ship property.
             *
             * <p>
             * For example, to add a new item, do as follows:
             * <pre>
             *    getShip().add(newItem);
             * </pre>
             *
             *
             * <p>
             * Objects of the following type(s) are allowed in the list
             * {@link BattleShipGame.Boards.Board.Ship }
             *
             *
             */
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            public List<BattleShipGame.Boards.Board.Ship> getShip() {
                if (ship == null) {
                    ship = new ArrayList<BattleShipGame.Boards.Board.Ship>();
                }
                return this.ship;
            }
            /**
             * <p>Java class for anonymous complex type.
             *
             * <p>The following schema fragment specifies the expected content contained within this class.
             *
             * <pre>
             * &lt;complexType>
             *   &lt;complexContent>
             *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
             *       &lt;sequence>
             *         &lt;element name="shipTypeId" type="{http://www.w3.org/2001/XMLSchema}string"/>
             *         &lt;element name="position">
             *           &lt;complexType>
             *             &lt;complexContent>
             *               &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
             *                 &lt;attribute name="x" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
             *                 &lt;attribute name="y" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
             *               &lt;/restriction>
             *             &lt;/complexContent>
             *           &lt;/complexType>
             *         &lt;/element>
             *         &lt;element name="direction">
             *           &lt;simpleType>
             *             &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
             *               &lt;enumeration value="ROW"/>
             *               &lt;enumeration value="COLUMN"/>
             *               &lt;enumeration value="RIGHT_DOWN"/>
             *               &lt;enumeration value="RIGHT_UP"/>
             *               &lt;enumeration value="UP_RIGHT"/>
             *               &lt;enumeration value="DOWN_RIGHT"/>
             *             &lt;/restriction>
             *           &lt;/simpleType>
             *         &lt;/element>
             *       &lt;/sequence>
             *     &lt;/restriction>
             *   &lt;/complexContent>
             * &lt;/complexType>
             * </pre>
             *
             *
             */
            @XmlAccessorType(XmlAccessType.FIELD)
            @XmlType(name = "", propOrder = {
                    "shipTypeId",
                    "position",
                    "direction"
            })
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            public static class Ship {

                @XmlElement(required = true)
                @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                protected String shipTypeId;
                @XmlElement(required = true)
                @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                protected BattleShipGame.Boards.Board.Ship.Position position;
                @XmlElement(required = true)
                @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                protected String direction;

                /**
                 * Gets the value of the shipTypeId property.
                 *
                 * @return
                 *     possible object is
                 *     {@link String }
                 *
                 */
                @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                public String getShipTypeId() {
                    return shipTypeId;
                }

                /**
                 * Sets the value of the shipTypeId property.
                 *
                 * @param value
                 *     allowed object is
                 *     {@link String }
                 *
                 */
                @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                public void setShipTypeId(String value) {
                    this.shipTypeId = value;
                }

                /**
                 * Gets the value of the position property.
                 *
                 * @return
                 *     possible object is
                 *     {@link BattleShipGame.Boards.Board.Ship.Position }
                 *
                 */
                @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                public BattleShipGame.Boards.Board.Ship.Position getPosition() {
                    return position;
                }

                /**
                 * Sets the value of the position property.
                 *
                 * @param value
                 *     allowed object is
                 *     {@link BattleShipGame.Boards.Board.Ship.Position }
                 *
                 */
                @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                public void setPosition(BattleShipGame.Boards.Board.Ship.Position value) {
                    this.position = value;
                }

                /**
                 * Gets the value of the direction property.
                 *
                 * @return
                 *     possible object is
                 *     {@link String }
                 *
                 */
                @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                public String getDirection() {
                    return direction;
                }

                /**
                 * Sets the value of the direction property.
                 *
                 * @param value
                 *     allowed object is
                 *     {@link String }
                 *
                 */
                @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                public void setDirection(String value) {
                    this.direction = value;
                }
                /**
                 * <p>Java class for anonymous complex type.
                 *
                 * <p>The following schema fragment specifies the expected content contained within this class.
                 *
                 * <pre>
                 * &lt;complexType>
                 *   &lt;complexContent>
                 *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
                 *       &lt;attribute name="x" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
                 *       &lt;attribute name="y" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
                 *     &lt;/restriction>
                 *   &lt;/complexContent>
                 * &lt;/complexType>
                 * </pre>
                 *
                 *
                 */
                @XmlAccessorType(XmlAccessType.FIELD)
                @XmlType(name = "")
                @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                public static class Position {

                    @XmlAttribute(name = "x", required = true)
                    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                    protected int x;
                    @XmlAttribute(name = "y", required = true)
                    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                    protected int y;

                    /**
                     * Gets the value of the x property.
                     *
                     */
                    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                    public int getX() {
                        return x;
                    }

                    /**
                     * Sets the value of the x property.
                     *
                     */
                    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                    public void setX(int value) {
                        this.x = value;
                    }

                    /**
                     * Gets the value of the y property.
                     *
                     */
                    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                    public int getY() {
                        return y;
                    }

                    /**
                     * Sets the value of the y property.
                     *
                     */
                    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
                    public void setY(int value) {
                        this.y = value;
                    }

                }

            }

        }

    }
    /**
     * <p>Java class for anonymous complex type.
     *
     * <p>The following schema fragment specifies the expected content contained within this class.
     *
     * <pre>
     * &lt;complexType>
     *   &lt;complexContent>
     *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       &lt;sequence>
     *         &lt;element name="amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
     *       &lt;/sequence>
     *     &lt;/restriction>
     *   &lt;/complexContent>
     * &lt;/complexType>
     * </pre>
     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
            "amount"
    })
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public static class Mine {

        @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
        protected int amount;

        /**
         * Gets the value of the amount property.
         *
         */
        @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
        public int getAmount() {
            return amount;
        }

        /**
         * Sets the value of the amount property.
         *
         */
        @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
        public void setAmount(int value) {
            this.amount = value;
        }

    }
    /**
     * <p>Java class for anonymous complex type.
     *
     * <p>The following schema fragment specifies the expected content contained within this class.
     *
     * <pre>
     * &lt;complexType>
     *   &lt;complexContent>
     *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       &lt;sequence>
     *         &lt;element name="shipType" maxOccurs="unbounded">
     *           &lt;complexType>
     *             &lt;complexContent>
     *               &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *                 &lt;sequence>
     *                   &lt;element name="category">
     *                     &lt;simpleType>
     *                       &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
     *                         &lt;enumeration value="REGULAR"/>
     *                         &lt;enumeration value="L_SHAPE"/>
     *                       &lt;/restriction>
     *                     &lt;/simpleType>
     *                   &lt;/element>
     *                   &lt;element name="amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
     *                   &lt;element name="length" type="{http://www.w3.org/2001/XMLSchema}int"/>
     *                   &lt;element name="score" type="{http://www.w3.org/2001/XMLSchema}int"/>
     *                 &lt;/sequence>
     *                 &lt;attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
     *               &lt;/restriction>
     *             &lt;/complexContent>
     *           &lt;/complexType>
     *         &lt;/element>
     *       &lt;/sequence>
     *     &lt;/restriction>
     *   &lt;/complexContent>
     * &lt;/complexType>
     * </pre>
     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
            "shipType"
    })
    @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
    public static class ShipTypes {

        @XmlElement(required = true)
        @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
        protected List<BattleShipGame.ShipTypes.ShipType> shipType;

        /**
         * Gets the value of the shipType property.
         *
         * <p>
         * This accessor method returns a reference to the live list,
         * not a snapshot. Therefore any modification you make to the
         * returned list will be present inside the JAXB object.
         * This is why there is not a <CODE>set</CODE> method for the shipType property.
         *
         * <p>
         * For example, to add a new item, do as follows:
         * <pre>
         *    getShipType().add(newItem);
         * </pre>
         *
         *
         * <p>
         * Objects of the following type(s) are allowed in the list
         * {@link BattleShipGame.ShipTypes.ShipType }
         *
         *
         */
        @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
        public List<BattleShipGame.ShipTypes.ShipType> getShipType() {
            if (shipType == null) {
                shipType = new ArrayList<BattleShipGame.ShipTypes.ShipType>();
            }
            return this.shipType;
        }
        /**
         * <p>Java class for anonymous complex type.
         *
         * <p>The following schema fragment specifies the expected content contained within this class.
         *
         * <pre>
         * &lt;complexType>
         *   &lt;complexContent>
         *     &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
         *       &lt;sequence>
         *         &lt;element name="category">
         *           &lt;simpleType>
         *             &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string">
         *               &lt;enumeration value="REGULAR"/>
         *               &lt;enumeration value="L_SHAPE"/>
         *             &lt;/restriction>
         *           &lt;/simpleType>
         *         &lt;/element>
         *         &lt;element name="amount" type="{http://www.w3.org/2001/XMLSchema}int"/>
         *         &lt;element name="length" type="{http://www.w3.org/2001/XMLSchema}int"/>
         *         &lt;element name="score" type="{http://www.w3.org/2001/XMLSchema}int"/>
         *       &lt;/sequence>
         *       &lt;attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
         *     &lt;/restriction>
         *   &lt;/complexContent>
         * &lt;/complexType>
         * </pre>
         *
         *
         */
        @XmlAccessorType(XmlAccessType.FIELD)
        @XmlType(name = "", propOrder = {
                "category",
                "amount",
                "length",
                "score"
        })
        @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
        public static class ShipType {

            @XmlElement(required = true)
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            protected String category;
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            protected int amount;
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            protected int length;
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            protected int score;
            @XmlAttribute(name = "id", required = true)
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            protected String id;

            /**
             * Gets the value of the category property.
             *
             * @return
             *     possible object is
             *     {@link String }
             *
             */
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            public String getCategory() {
                return category;
            }

            /**
             * Sets the value of the category property.
             *
             * @param value
             *     allowed object is
             *     {@link String }
             *
             */
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            public void setCategory(String value) {
                this.category = value;
            }

            /**
             * Gets the value of the amount property.
             *
             */
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            public int getAmount() {
                return amount;
            }

            /**
             * Sets the value of the amount property.
             *
             */
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            public void setAmount(int value) {
                this.amount = value;
            }

            /**
             * Gets the value of the length property.
             *
             */
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            public int getLength() {
                return length;
            }

            /**
             * Sets the value of the length property.
             *
             */
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            public void setLength(int value) {
                this.length = value;
            }

            /**
             * Gets the value of the score property.
             *
             */
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            public int getScore() {
                return score;
            }

            /**
             * Sets the value of the score property.
             *
             */
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            public void setScore(int value) {
                this.score = value;
            }

            /**
             * Gets the value of the id property.
             *
             * @return
             *     possible object is
             *     {@link String }
             *
             */
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            public String getId() {
                return id;
            }

            /**
             * Sets the value of the id property.
             *
             * @param value
             *     allowed object is
             *     {@link String }
             *
             */
            @Generated(value = "com.sun.tools.internal.xjc.Driver", date = "2017-08-18T07:53:29+03:00", comments = "JAXB RI v2.2.8-b130911.1802")
            public void setId(String value) {
                this.id = value;
            }

        }

    }

}

Assignment Code



package BattleShipJAXB;

import javax.xml.bind.annotation.XmlRegistry;
/**
 * This object contains factory methods for each 
 * Java content interface and Java element interface 
 * generated in the BattleShipJAXB package. 
 * <p>An ObjectFactory allows you to programatically 
 * construct new instances of the Java representation 
 * for XML content. The Java representation of XML 
 * content can consist of schema derived interfaces 
 * and classes representing the binding of schema 
 * type definitions, element declarations and model 
 * groups.  Factory methods for each of these are 
 * provided in this class.
 * 
 */
@XmlRegistry
public class ObjectFactory {
    /**
     * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: BattleShipJAXB
     * 
     */
    public ObjectFactory() {
    }

    /**
     * Create an instance of {@link BattleShipGame }
     * 
     */
    public BattleShipGame createBattleShipGame() {
        return new BattleShipGame();
    }

    /**
     * Create an instance of {@link BattleShipGame.Boards }
     * 
     */
    public BattleShipGame.Boards createBattleShipGameBoards() {
        return new BattleShipGame.Boards();
    }

    /**
     * Create an instance of {@link BattleShipGame.Boards.Board }
     * 
     */
    public BattleShipGame.Boards.Board createBattleShipGameBoardsBoard() {
        return new BattleShipGame.Boards.Board();
    }

    /**
     * Create an instance of {@link BattleShipGame.Boards.Board.Ship }
     * 
     */
    public BattleShipGame.Boards.Board.Ship createBattleShipGameBoardsBoardShip() {
        return new BattleShipGame.Boards.Board.Ship();
    }

    /**
     * Create an instance of {@link BattleShipGame.ShipTypes }
     * 
     */
    public BattleShipGame.ShipTypes createBattleShipGameShipTypes() {
        return new BattleShipGame.ShipTypes();
    }

    /**
     * Create an instance of {@link BattleShipGame.Mine }
     * 
     */
    public BattleShipGame.Mine createBattleShipGameMine() {
        return new BattleShipGame.Mine();
    }

    /**
     * Create an instance of {@link BattleShipGame.Boards.Board.Ship.Position }
     * 
     */
    public BattleShipGame.Boards.Board.Ship.Position createBattleShipGameBoardsBoardShipPosition() {
        return new BattleShipGame.Boards.Board.Ship.Position();
    }

    /**
     * Create an instance of {@link BattleShipGame.ShipTypes.ShipType }
     * 
     */
    public BattleShipGame.ShipTypes.ShipType createBattleShipGameShipTypesShipType() {
        return new BattleShipGame.ShipTypes.ShipType();
    }

}

Assignment Code


package BattleShipLogic;

import java.awt.*;

public class Action {
    private GameTime m_GameTime;
    private BattleShipLogic.Moves m_GameMove;
    private Point m_Point;

    public Action(BattleShipLogic.Moves m_GameMove){

        this.m_GameMove = m_GameMove;
    }

    public void SetTime(GameTime gameTime){

        this.m_GameTime = gameTime;
    }

    public void SetPoint(Point point){

        this.m_Point = point;
    }

}

Assignment Code


package BattleShipLogic;

import java.awt.*;

public class BattleShip extends BoardItems {
    private String m_ShipID;
    private eDirection m_Direction;
    private int m_LengthAfterHit;
    private int m_Length;
    private int m_Score;

    public BattleShip(String shipID, int length, int score) throws GameException {
        super(eItems.Ship.getChar());
        if(length >= 1) {
            this.m_ShipID = shipID;
            this.m_Length = length;
            this.m_Score = score;
            m_LengthAfterHit = length;
            this.m_SpreadingItemPoints = new Point[length];
            for (int i = 0; i< length; i++)
                m_SpreadingItemPoints[i]=new Point();
        }
        else{
            throw new GameException("The size of the ship must be a positive integer");
        }
    }

    public void SetStartPositionPoint(Point startPositionPoint){
        this.m_StartPositionPoint = startPositionPoint;

        this.BuildItem();
    }

    public void SetDirection(eDirection Direction){
        this.m_Direction = Direction;
    }

    public String GetShipID(){return m_ShipID;}

    public boolean CheckPositionInitialized(){return m_StartPositionPoint.y!=-1;}

    public boolean CheckShipSank(){
        return m_LengthAfterHit ==0;
    }

    public boolean CheckHitOnBoard(Point pointOnBoard){
        boolean isHitSucceeded = false;

        for (Point point: this.m_SpreadingItemPoints) {
            if(point.y == pointOnBoard.y && point.x == pointOnBoard.x){
                isHitSucceeded = true;
                break;
            }
        }

        return isHitSucceeded;
    }

    @Override
    public void BuildItem(){
        int x = m_StartPositionPoint.x;
        int y = m_StartPositionPoint.y;
        for (Point point: this.m_SpreadingItemPoints) {
            point.x = x;
            point.y = y;
            if(m_Direction == m_Direction.Row){
                x++;
            }
            else if(m_Direction == m_Direction.Column){
                y++;
            }
        }
    }

    public boolean PlaceHitAndCheckSink(Point pointOnBoard){
        for (Point point: this.m_SpreadingItemPoints) {
            if(point.y == pointOnBoard.y && point.x == pointOnBoard.x){
                m_LengthAfterHit--;
                break;
            }
        }

        return CheckShipSank();
    }
}

Assignment Code


package BattleShipLogic;

import BattleShipJAXB.BattleShipGame;

public final class BattleShipFactory {

    private BattleShipFactory(){}

    private static BattleShip PullOutShip(Object pullingOutShip) throws GameException{
        BattleShip pulledBattleShip;

        BattleShipGame.ShipTypes.ShipType ship = (BattleShipGame.ShipTypes.ShipType)pullingOutShip;
        pulledBattleShip = new BattleShip(ship.getId(),ship.getLength(),ship.getScore());

        return pulledBattleShip;
    }

    public static Object PullOutObject(Object pullingOutObject) throws GameException {
        Object pulledObject = null;

        if(pullingOutObject instanceof BattleShipGame.ShipTypes.ShipType){
            BattleShipGame.ShipTypes.ShipType ship = (BattleShipGame.ShipTypes.ShipType)pullingOutObject;
            if (ship.getCategory().equals("REGULAR")) {
                pulledObject = PullOutShip(pullingOutObject);
            }
            if (ship.getCategory().equals("L_SHAPE")) {
                pulledObject = PullOutShip(pullingOutObject);
                //TODO
            }
        }

        return pulledObject;
    }
}

Assignment Code


package BattleShipLogic;

import BattleShipJAXB.BattleShipGame;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.List;

public class BattleShipLogic {
    public enum Moves{Trap, Hit}
    private int m_PlayerOnBreak =1;
    private int m_AttackerPlayer =0;
    private int m_BoardSize;
    private List<Player> m_PlayersList;
    private final static int k_NoWinners =-1;
    private final static int k_NumOfTraps =2;
    private final static int k_NumOfPlayers =2;
    private final static String k_JAXBXmlPackageName = "BattleShipJAXB";
    private eStatusGame m_e_StatusGame = eStatusGame.BeforeLoadXml;
    private Date m_StartTime;
    private Date m_StartMoveTime;
    
    public BattleShipLogic(){
        m_PlayersList =new ArrayList<>(k_NumOfPlayers);
    }

    public int getAttackerPlayer() {
        return m_AttackerPlayer;
    }

    public int getPlayerOnBreak() { return m_PlayerOnBreak;}

    public int getAttackerPlayerScore(){return m_PlayersList.get(m_AttackerPlayer).GetPlayerScore();}

    public char[][] getAttackerPlayerShipBoard(){
        return m_PlayersList.get(m_AttackerPlayer).GetShipsBoard().GetBoardGame();
    }

    public char[][] getPlayerOnBreakShipBoard(){
        return m_PlayersList.get(m_PlayerOnBreak).GetShipsBoard().GetBoardGame();
    }

    public char[][] getAttackerPlayerTrackBoard(){
        return m_PlayersList.get(m_AttackerPlayer).GetTrackBoard().GetBoardGame();
    }

    public int getBoardSize(){return m_BoardSize;}

    public eStatusGame getStatusGame() {
        return m_e_StatusGame;
    }

    public boolean SetTrapOnBoard(Point point)
    {
        Trap trap=new Trap(point);
        boolean isSetSucceed=false;

        try {
            trap.SetTrapOnBoard(point);
            isSetSucceed= m_PlayersList.get(m_AttackerPlayer).SetTrapOnAttackerBoard(trap);
            ChangePlayers();
        }
        catch (GameException e) {}

        return isSetSucceed;
    }

    public void StartMoveTime(){
        m_StartMoveTime =new Date();
    }

    public void StartTheGame(){
        m_e_StatusGame = eStatusGame.GameStarted;
        eMenuType.LoadXmlFile.setIsMenuTypeActive(false);
        eMenuType.StartTheGame.setIsMenuTypeActive(false);
        eMenuType.GameStatus.setIsMenuTypeActive(true);
        eMenuType.AttackOpponent.setIsMenuTypeActive(true);
        eMenuType.GameStatistics.setIsMenuTypeActive(true);
        eMenuType.EndCurrentGame.setIsMenuTypeActive(true);
        eMenuType.Trap.setIsMenuTypeActive(true);
        m_StartTime =new Date();
    }
    public eInputProblems CheckUserChoice(eMenuType action) {
        if (m_e_StatusGame.equals(eStatusGame.BeforeLoadXml)) {
            if (!action.getIsMenuTypeActive())
                return eInputProblems.OperateOtherCommandBeforeLoading;
            else {
                eMenuType.StartTheGame.setIsMenuTypeActive(true);
            }
        }
        else if (m_e_StatusGame.equals(eStatusGame.AfterLoadXml)) {
            if (!action.getIsMenuTypeActive())
                return eInputProblems.OperateGameActionBeforeStarted;
        }
        else if (m_e_StatusGame.equals(eStatusGame.GameStarted)) {
            if (!action.getIsMenuTypeActive())
                return eInputProblems.OperateSettingsCommandWhenGameIsOn;

        }

        return eInputProblems.IsChoiceValid;
    }

    //checks if the ships locations are valid and creating m_PlayersList
    private boolean CheckShipLocationsValidation(BattleShipGame xmlClasses){
        boolean isShipLocationsValid=true;
        int boardSize=xmlClasses.getBoardSize();

        try {
            m_PlayersList.add(new Player(boardSize, k_NumOfTraps));
            m_PlayersList.add(new Player(boardSize, k_NumOfTraps));
        }
        catch (GameException e){}
        List<List<BoardItems>> shipLists = new ArrayList<>(2);
        List<BoardItems> list1 = new ArrayList<>();
        List<BoardItems> list2 = new ArrayList<>();
        shipLists.add(list1);
        shipLists.add(list2);
        for (BattleShipGame.ShipTypes.ShipType shipType: xmlClasses.getShipTypes().getShipType())
        {
            try {
                shipLists.get(0).add((BattleShip) BattleShipFactory.PullOutObject(shipType));
                shipLists.get(1).add((BattleShip) BattleShipFactory.PullOutObject(shipType));
            }
            catch (GameException e) {
                isShipLocationsValid=false;
            }
        }

        for (int i = 0; i < k_NumOfPlayers; i++) {
            for (BattleShipGame.Boards.Board.Ship ship: xmlClasses.getBoards().getBoard().get(i).getShip()){
                for (BoardItems myObj: shipLists.get(i)) {
                    if (myObj instanceof BattleShip)
                    {
                        BattleShip myBattleShip =(BattleShip)(myObj);
                        if (ship.getShipTypeId().equals(myBattleShip.GetShipID()) && !myBattleShip.CheckPositionInitialized()){
                            myBattleShip.SetDirection(eDirection.StringToDirection(ship.getDirection()));
                            myBattleShip.SetStartPositionPoint(new Point(ship.getPosition().getY()-1, ship.getPosition().getX()-1));
                        }
                    }
                }
            }

            m_PlayersList.get(i).SetShipsList(shipLists.get(i));
            try {
                m_PlayersList.get(i).AddShipsToGameBoard();
            } catch (GameException e) {
                isShipLocationsValid=false;
            }
        }

        return isShipLocationsValid;
    }

    //checks if the number of ships in xml file is valid
    private boolean CheckShipInstancesNumberValidation(BattleShipGame xmlClasses) {
        boolean isInstancesNumberValid=true;
        Map<String, Integer> shipsMap = new HashMap<>();
        
        for (int i = 0; i < k_NumOfPlayers; i++) {
            for (BattleShipGame.ShipTypes.ShipType shipType : xmlClasses.getShipTypes().getShipType()) {
                shipsMap.put(shipType.getId(), shipType.getAmount());
            }
            
            for (BattleShipGame.Boards.Board.Ship ship: xmlClasses.getBoards().getBoard().get(i).getShip()){
                int newAmount = shipsMap.get(ship.getShipTypeId())-1;
                shipsMap.put((ship.getShipTypeId()),newAmount);
            }
            
            for (Map.Entry<String,Integer> entry:shipsMap.entrySet()) {
                if (entry.getValue() != 0) {
                    return false;
                }
            }
            
            shipsMap.clear();
        }
        
        return isInstancesNumberValid;
    }

    public void ClearAllBoards()
    {
        for (Player player:m_PlayersList) {
            player.GetShipsBoard().ClearBoard();
            player.GetTrackBoard().ClearBoard();
        }
    }

    public eAttackResults AttackOpponent(Point point)
    {
        Action attack = new Action(Moves.Hit);
        attack.SetPoint(point);
        boolean isChangePlayers = false;
        boolean isHitShip=false;
        eAttackResults attackResult=eAttackResults.AttackEndedWithMiss;

        if (!m_PlayersList.get(m_AttackerPlayer).GetShipsBoard().CheckPointInRange(point))
            return eAttackResults.OutOfRange;
        if (m_PlayersList.get(m_AttackerPlayer).HitBefore(point))
            return eAttackResults.HitBefore;
        try {
            char ch= m_PlayersList.get(m_PlayerOnBreak).CheckHitOnBoard(point);

            if (ch==eItems.Ship.getChar()){//attacking ship
                AttackShip(point);
                isHitShip=true;
                attackResult=eAttackResults.AttackEndedWithHit;
            }
            else if (ch==eItems.Trap.getChar()){ //if attacking trap and there is an object in the same place
                if (m_PlayersList.get(m_AttackerPlayer).GetShipsBoard().GetSignOnBoardByPoint(point)!='~'
                        && m_PlayersList.get(m_AttackerPlayer).GetShipsBoard().GetSignOnBoardByPoint(point)!= eItems.Miss.getChar()){
                   isChangePlayers= AttackTrapWithObject(point, isChangePlayers);
                   attackResult=eAttackResults.AttackTrapWithObject;
                }
                else { //attacking trap and there is no object at the same place
                    isChangePlayers=AttackTrapWithoutObject(point, isChangePlayers);
                    attackResult=eAttackResults.AttackTrapWithOutObject;
                }
            }
            else {//miss attack
                 isChangePlayers=AttackMiss(isChangePlayers,point);
                 attackResult=eAttackResults.AttackEndedWithMiss;
            }
        }
        catch (GameException e1){}
        endAttack(attack);
        if(isChangePlayers){
            ChangePlayers();
        }
        if (FindWinners() != k_NoWinners)
        {
            attackResult= eAttackResults.Win;
        }

        return attackResult;
    }

    private void AttackShip(Point point)
    {
        m_PlayersList.get(m_AttackerPlayer).IncreaseHitsCounter();
        m_PlayersList.get(m_AttackerPlayer).GetTrackBoard().UpdateHitOnBoard(point);
    }

    private boolean AttackTrapWithObject(Point point, boolean isChangePlayers) throws GameException
    {
            m_PlayersList.get(m_AttackerPlayer).IncreaseHitsCounter();
            m_PlayersList.get(m_AttackerPlayer).GetTrackBoard().UpdateMissOnBoard(point);
            m_PlayersList.get(m_PlayerOnBreak).IncreaseHitsCounter();
            if(m_PlayersList.get(m_AttackerPlayer).GetSignFromShipBoard(point) == eItems.Ship.getChar())
            {
                m_PlayersList.get(m_PlayerOnBreak).GetTrackBoard().UpdateHitOnBoard(point);
                m_PlayersList.get(m_PlayerOnBreak).GetShipsBoard().UpdateHitOnBoard(point);
            }
            else //hit  a trap
            {
                m_PlayersList.get(m_PlayerOnBreak).GetTrackBoard().UpdateMissOnBoard(point);
                m_PlayersList.get(m_PlayerOnBreak).GetShipsBoard().UpdateMissOnBoard(point);
            }

            isChangePlayers = true;

            return isChangePlayers;
    }

    public boolean AttackMiss(boolean isChangePlayers, Point point)
    {
        m_PlayersList.get(m_AttackerPlayer).GetTrackBoard().UpdateMissOnBoard(point);
        m_PlayersList.get(m_PlayerOnBreak).GetShipsBoard().UpdateMissOnBoard(point);
        m_PlayersList.get(m_AttackerPlayer).IncreaseMissCounter();
        isChangePlayers = true;

        return  isChangePlayers;
    }

    public boolean AttackTrapWithoutObject(Point point, boolean isChangePlayers)
    {
        m_PlayersList.get(m_AttackerPlayer).IncreaseHitsCounter();
        m_PlayersList.get(m_AttackerPlayer).GetTrackBoard().UpdateMissOnBoard(point);
        m_PlayersList.get(m_PlayerOnBreak).GetShipsBoard().UpdateMissOnBoard(point);//////
        m_PlayersList.get(m_PlayerOnBreak).GetTrackBoard().UpdateMissOnBoard(point);
        m_PlayersList.get(m_PlayerOnBreak).IncreaseMissCounter();
        isChangePlayers=true;

        return isChangePlayers;
    }

    private void endAttack(Action attack){
        m_PlayersList.get(m_AttackerPlayer).IncreaseAttacksCounter();
        Date endAttack = new Date();
        GameTime attackGameTime = new GameTime(m_StartMoveTime, endAttack);
        m_PlayersList.get(m_AttackerPlayer).AddTime(attackGameTime);
        attack.SetTime(attackGameTime);
        m_PlayersList.get(m_AttackerPlayer).AddAttack(attack);
    }

    public Object[] GetStatisticsInfo(){
        Date currentTime = new Date();
        Object[] statisticsInfo = new Object[8];

        statisticsInfo[0] = m_PlayersList.get(1).GetAttacksCounter() + m_PlayersList.get(0).GetAttacksCounter();
        statisticsInfo[1] = new GameTime(m_StartTime, currentTime);
        statisticsInfo[2] = m_PlayersList.get(0).GetPlayerScore();
        statisticsInfo[3] = m_PlayersList.get(0).GetMissCounter();
        statisticsInfo[4] = m_PlayersList.get(0).GetAverageAttacksTime();
        statisticsInfo[5] = m_PlayersList.get(1).GetPlayerScore();
        statisticsInfo[6] = m_PlayersList.get(1).GetMissCounter();
        statisticsInfo[7] = m_PlayersList.get(1).GetAverageAttacksTime();

        return statisticsInfo;
    }
    public int FindWinners()
    {
        for(int i = 0; i< k_NumOfPlayers; i++){
            if (m_PlayersList.get(i).CheckLMissOnBoard())
                return i^=1;
        }

        return k_NoWinners;
    }

    private void ChangePlayers(){
        int tempPlayer;

        tempPlayer= m_PlayerOnBreak;
        m_PlayerOnBreak=m_AttackerPlayer;
        m_AttackerPlayer =tempPlayer;
    }

    private BattleShipGame FromXmlFileToObject(String xmlLocation) throws JAXBException {
        JAXBContext jc = JAXBContext.newInstance(k_JAXBXmlPackageName);
        Unmarshaller u = jc.createUnmarshaller();

        return (BattleShipGame) u.unmarshal(new File(xmlLocation));
    }

    public eProblemsXML LoadItemsFromXML(String path){
        BattleShipGame xmlData = null ;

        try {
            xmlData = FromXmlFileToObject(path);
        }catch (JAXBException e) {
            return eProblemsXML.XmlDoesNotExist;
        }

        m_BoardSize = xmlData.getBoardSize();
        if(!BoardGame.CheckBoardSizeValidation(m_BoardSize))
            return eProblemsXML.XmlBoardSizeInvalid;
        if (!CheckShipInstancesNumberValidation(xmlData))
            return eProblemsXML.XmlShipItemsNumberInvalid;
        if (!CheckShipLocationsValidation(xmlData))
            return eProblemsXML.XmlShipPositionInvalid;

        return eProblemsXML.XmlIsValid;
    }
}

Assignment Code


package BattleShipLogic;

import java.awt.*;

public class BoardGame {
    private final int k_BoardSize;
    static private final int k_MaxBoardSize = 20;
    static private final int k_MinBoardSize = 5;
    private char m_BoardGame[][];

    public BoardGame(int n) throws GameException {
        if(CheckBoardSizeValidation(n)){
            k_BoardSize = n;
            m_BoardGame =new char[n][n];
            ClearBoard();
        }
        else{
            throw new GameException(String.format("BoardGame's size must be between {0} - {1}", k_MinBoardSize, k_MaxBoardSize));
        }
    }

    public char[][] GetBoardGame(){
        return this.m_BoardGame;
    }

    public char GetSignOnBoardByPoint(Point pointOnBoard) throws GameException{
        if (!CheckPointInRange(pointOnBoard)){
            throw new GameException("The Point is Out of Range");
        }
        else{
            return this.m_BoardGame[pointOnBoard.y][pointOnBoard.x];
        }
    }

    public void ClearBoard(){
        for(int i = 0; i < k_BoardSize; i++){
            for(int j = 0; j < k_BoardSize; j++){
                this.m_BoardGame[i][j] = '~';
            }
        }
    }

    public void UpdateBoard(Point updatePoint, char ch) throws GameException {

        if(CheckPointInRange(updatePoint)) {
            m_BoardGame[updatePoint.y][updatePoint.x] = ch;
        }
        else{
            throw new GameException("Point is out of range");
        }
    }

    private void UpdateBoardBySign(Point pointOnBoard, char sign){
        this.m_BoardGame[pointOnBoard.y][pointOnBoard.x] = sign;
    }

    public void UpdateHitOnBoard(Point pointOnBoard){
        UpdateBoardBySign(pointOnBoard,eItems.Hit.getChar());
    }

    public void UpdateMissOnBoard(Point pointOnBoard){
        UpdateBoardBySign(pointOnBoard,eItems.Miss.getChar());
    }

    // This function adds the item to the board of game
    public boolean AddItemToBoardGame(BoardItems boardItem){
        boolean isAdditionSucceeded = false;

        // checks if all the points of the item are valid
        for (Point point: boardItem.m_SpreadingItemPoints) {
            isAdditionSucceeded = checkPointValidation(point);
            if (!isAdditionSucceeded) {
                break;
            }
        }

        // if the points of the object are valid add the object to the m_BoardGame
        if (isAdditionSucceeded) {
            for (Point point : boardItem.m_SpreadingItemPoints) {
                m_BoardGame[point.y][point.x] = boardItem.m_Sign;
            }
        }

        return isAdditionSucceeded;
    }

    public void HitBoardByPoint(Point pointOnBoard){
        this.m_BoardGame[pointOnBoard.y][pointOnBoard.x]=eItems.Hit.getChar();
    }

    protected boolean CheckPointInRange(Point checkPoint){
        boolean isPointInRange = true;

        if(checkPoint.x < 0 || checkPoint.y < 0 || checkPoint.x >= k_BoardSize || checkPoint.y >= k_BoardSize){
            isPointInRange = false;
        }

        return isPointInRange;
    }

    static public boolean CheckBoardSizeValidation(int boardSize){
        boolean isBoardSizeValid = false;

        if(boardSize >= k_MinBoardSize && boardSize <= k_MaxBoardSize){
            isBoardSizeValid = true;
        }
        return isBoardSizeValid;
    }

    // This function check if the Point is valid
    private boolean checkPointValidation(Point pointOnBoard){
        boolean isPointValid = true;

        // Not in the range of the m_BoardGame
        isPointValid = CheckPointInRange(pointOnBoard);
        if(isPointValid && m_BoardGame[pointOnBoard.y][pointOnBoard.x] != '~'){
            isPointValid = false;
        }
        else if(isPointValid){
            isPointValid = checkSquareValidation(pointOnBoard);
        }
        
        return isPointValid;
    }

    // This function helps to check if the Point is valid
    private  boolean checkSquareValidation(Point pointOnBoard) {
        boolean isSquareValid = true;
        
        for (int x = pointOnBoard.x - 1; x < pointOnBoard.x + 2 && isSquareValid; x++){
            for (int y = pointOnBoard.y - 1; y < pointOnBoard.y + 2 && isSquareValid; y++) {
                if (x >= 0 && x < k_BoardSize && y >= 0 && y < k_BoardSize) {
                    if (m_BoardGame[y][x] != '~') {
                        isSquareValid = false;
                    }
                }
            }
        }
        
        return isSquareValid;
    }

    public boolean CheckIfHitBefore(Point pointOnBoard){
        char ch= this.m_BoardGame[pointOnBoard.y][pointOnBoard.x];
        if (ch!='~')
            return true;
        return false;
    }
}

Assignment Code


package BattleShipLogic;

import java.awt.*;

public abstract  class BoardItems {
    protected Point[] m_SpreadingItemPoints;
    protected Point m_StartPositionPoint = new Point();
    protected char m_Sign;

    public abstract void BuildItem();

    public BoardItems(char sign) {
        m_StartPositionPoint.x = -1;
        m_StartPositionPoint.y = -1;
        this.m_Sign = sign;
    }
}


Assignment Code


package BattleShipLogic;

public enum eAttackResults {
    Win,
    OutOfRange,
    HitBefore,
    AttackEndedWithHit,
    AttackEndedWithMiss,
    AttackTrapWithObject,
    AttackTrapWithOutObject,
}

Assignment Code


package BattleShipLogic;

public enum eDirection {
    Row("ROW"),
    Column("COLUMN"),
    UpRight("UP_RIGHT"),
    DownRight("DOWN_RIGHT"),
    RightDowm("RIGHT_DOWN"),
    RightUp("RIGHT_UP");

    private  String m_Direction;

    private eDirection(String direction)
    {
        this.m_Direction = direction;
    }

    static public eDirection StringToDirection(String Direction)
    {
        switch (Direction)
        {
            case "ROW": return Row;
            case "COLUMN": return Column;
            case "RIGHT_UP": return RightUp;
            case "DOWN_RIGHT": return DownRight;
            case "RIGHT_DOWN":return RightDowm;
            case "UP_RIGHT": return UpRight;
            default: return null;
        }
    }

    public String toString() {
        return this.m_Direction;
    }

    public boolean EqualsDirection(String directionToCheck) {
        // (otherName == null) check is not needed because name.equals(null) returns false
        return m_Direction.equals(directionToCheck);
    }
}


Assignment Code


package BattleShipLogic;

public enum eInputProblems {
    TrapsUsedUp,
    IsChoiceValid,
    OperateOtherCommandBeforeLoading,
    OperateSettingsCommandWhenGameIsOn,
    OperateGameActionBeforeStarted;
}

Assignment Code


package BattleShipLogic;

public enum eItems {
    Ship('$'),
    Trap('@'),
    Hit('X'),
    Miss('*'),;

    private final char m_Item;

    private eItems(char sign){
        m_Item =sign;
    }
    public char getChar(){return m_Item;}
}

Assignment Code


package BattleShipLogic;

import java.util.HashMap;
import java.util.Map;

public enum eMenuType {
    LoadXmlFile(1, "Load the game from XMl file", true),
    StartTheGame(2, "Start the amazing game!", false),
    GameStatus(3, "Show game status", false),
    AttackOpponent(4, "Attack the opponent", false),
    GameStatistics(5, "Show game satistics", false),
    EndCurrentGame(6, "End current game", false),
    Trap(7, "Place trap in board", false),
    ExitGame(8, "Exit game", true),
    WaitingForAction(0, "", false);

    private final String k_MenuTypeDescription;
    private final int k_MenuTypeNumber;
    private static Map<Integer, eMenuType> m_MyMenu = new HashMap<>();
    private boolean m_IsMenuTypeActive = false;

    static {
        for (eMenuType menuType : eMenuType.values()) {
            m_MyMenu.put(menuType.k_MenuTypeNumber, menuType);
        }
    }

    private eMenuType(int menuTypeNumber, String menuTypeDescription, boolean isMenuTypeActive) {
        this.k_MenuTypeNumber = menuTypeNumber;
        this.k_MenuTypeDescription = menuTypeDescription;
        this.m_IsMenuTypeActive = isMenuTypeActive;
    }

    public boolean getIsMenuTypeActive() {
        return m_IsMenuTypeActive;
    }

    public String getMenuTypeDescription() {
        return k_MenuTypeDescription;
    }

    public static eMenuType getMenuType(int num) {
        return m_MyMenu.get(num);
    }

    public int getMenuTypeNumber() {
        return k_MenuTypeNumber;
    }

    public void setIsMenuTypeActive(boolean isActive) {
        m_IsMenuTypeActive = isActive;
    }
}

Assignment Code


package BattleShipLogic;

public enum eProblemsXML {
    XmlDoesNotExist,
    XmlShipItemsNumberInvalid,
    XmlBoardSizeInvalid,
    XmlShipPositionInvalid,
    XmlIsValid;
}

Assignment Code


package BattleShipLogic;

public enum eStatusGame {
        WinnerFound,
        GameStarted,
        BeforeLoadXml,
        AfterLoadXml;
}

Assignment Code


package BattleShipLogic;

public class GameException extends Exception {

    public GameException(){
        super();
    }

    public GameException(String messageToThrow){
        super(messageToThrow);
    }

    public GameException(String messageToThrow, Throwable reason) {
        super(messageToThrow, reason); }

    public GameException(Throwable reason) {
        super(reason); }
}

Assignment Code


package BattleShipLogic;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class GameTime {
    private byte m_SecondsOfPlaying;
    private int m_MinutesOfPlaying;

    public GameTime(){
        m_MinutesOfPlaying = 0;
        m_SecondsOfPlaying = 0;
    }

    public GameTime(Date beginTime, Date endTime){
        CalculateTime(beginTime, endTime);
    }

    public void SetGameTime(int minutesToSet, byte secondsToSet){
        this.m_MinutesOfPlaying = minutesToSet;
        this.m_SecondsOfPlaying = secondsToSet;
    }

    @Override
    public String toString() {
        return String.format("%dM:%dS", m_MinutesOfPlaying, m_SecondsOfPlaying);
    }
    public void CalcAverageTime(GameTime gameTime, int attacksCount){
        long playingSeconds = ConvertTimeToSeconds(gameTime);

        if (attacksCount!=0)
            playingSeconds /= attacksCount;
        else
            playingSeconds=0;
        AddTime(playingSeconds);
    }

    public void CalculateTime(Date beginTime, Date endTime){
        long seconds = CalcAttackTimeInSeconds(beginTime.getTime(), endTime.getTime());
        SetGameTime((int)(seconds/60), (byte) (seconds%60));
    }

    // This function calculates the move time by getting the starting time and ending time
    // in milliseconds.
    // It returns the time in m_SecondsOfPlaying.
    public long CalcAttackTimeInSeconds(long beginTime, long endTime){
        beginTime = TimeUnit.MILLISECONDS.toSeconds(beginTime);
        endTime = TimeUnit.MILLISECONDS.toSeconds(endTime);

        return (endTime - beginTime);
    }

    public static long ConvertTimeToSeconds(GameTime gameTime){

        long newSeconds;

        newSeconds = gameTime.m_SecondsOfPlaying + (gameTime.m_MinutesOfPlaying * 60);

        return newSeconds;
    }

    public static GameTime ConvertSecondToTime(long secondsToConvert){
        GameTime newTime = new GameTime();

        if(secondsToConvert > 0) {
            newTime.m_SecondsOfPlaying = (byte)(secondsToConvert % 60);
            newTime.m_MinutesOfPlaying = (int)(secondsToConvert / 60);
        }

        return newTime;
    }

    public void AddTime(GameTime timeToAdd){
        this.m_MinutesOfPlaying += timeToAdd.m_MinutesOfPlaying;
        this.m_SecondsOfPlaying += timeToAdd.m_SecondsOfPlaying;
        if(m_SecondsOfPlaying >= 60){
            this.m_SecondsOfPlaying %= 60;
            this.m_MinutesOfPlaying++;
        }
    }

    public void AddTime(long secondsToAdd){
        this.m_MinutesOfPlaying += secondsToAdd / 60;
        this.m_SecondsOfPlaying += secondsToAdd % 60;
        if(secondsToAdd >= 60){
            this.m_SecondsOfPlaying %= 60;
            this.m_MinutesOfPlaying++;
        }
    }
}

Assignment Code


package BattleShipLogic;

import java.awt.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

public class Player {
    private static final char k_HitOnBoard ='X';
    private BoardGame m_ShipsBoard;
    private BoardGame m_TrackBoard;
    private GameTime m_PlayingTime;
    private int m_PlayerIndex;
    private int m_PlayerScore;
    private int m_AttacksCounter;
    private int m_NumberOfTraps;
    private int m_HitsCounter;
    private int m_MissCounter;
    private List<BoardItems> m_ShipsList;
    private Stack<Action> m_AttacksStack;

    public Player(int boardSize,int numberOfTraps) throws GameException {
        this.m_ShipsList = new LinkedList<BoardItems>();
        this.m_PlayingTime = new GameTime();
        m_AttacksStack = new Stack<Action>();
        this.m_ShipsBoard = new BoardGame(boardSize);
        this.m_TrackBoard = new BoardGame(boardSize);
        this.m_NumberOfTraps = numberOfTraps;
        this.m_PlayerIndex = m_PlayerIndex;
        this.m_PlayerScore = 0;
        this.m_AttacksCounter = 0;
        this.m_HitsCounter = 0;
        this.m_MissCounter = 0;
    }

    public BoardGame GetShipsBoard(){return m_ShipsBoard;}

    public BoardGame GetTrackBoard(){return m_TrackBoard;}

    public int GetMissCounter(){
        return m_MissCounter;
    }

    public int GetPlayerScore(){
        return m_PlayerScore;
    }

    public int GetAttacksCounter(){
        return m_AttacksCounter;
    }

    public GameTime GetAverageAttacksTime(){
        GameTime averageTime = new GameTime();

        averageTime.CalcAverageTime(m_PlayingTime, m_AttacksCounter);

        return averageTime;
    }
    public void SetShipsList(List<BoardItems> shipsListToSet){
        this.m_ShipsList = shipsListToSet;
    }

    public boolean SetTrapOnAttackerBoard(Trap trap) throws GameException {
        boolean isSetSucceed=false;

        isSetSucceed= m_ShipsBoard.AddItemToBoardGame(trap);

        return isSetSucceed;
    }

    public char GetSignFromShipBoard(Point pointOnBoard) throws GameException{
        return m_ShipsBoard.GetSignOnBoardByPoint(pointOnBoard);
    }

    public void IncreaseAttacksCounter(){ m_AttacksCounter++;}

    public void IncreaseHitsCounter(){
        m_HitsCounter++;
        m_PlayerScore++;}///////////////////////////change in excersie2

    public void IncreaseMissCounter(){
        m_MissCounter++;}

    public void AddTime(GameTime timeToAdd){
        this.m_PlayingTime.AddTime(timeToAdd);
    }

    public boolean AddTraps(Point pointOnBoard) throws GameException{
        boolean isTrapAdded =true;

        if(m_NumberOfTraps > 0) {
            m_NumberOfTraps--;
            Trap trapToAdd = new Trap(pointOnBoard);
           // trapToAdd.SetTrapOnBoard(pointOnBoard);
            if (!(m_ShipsBoard.AddItemToBoardGame(trapToAdd))) {
                throw new GameException("Disable to add the mine to the board");
            }
        }
        else
            isTrapAdded=false;

        return isTrapAdded;
    }

    public void AddShipsToGameBoard() throws GameException{
        boolean isAdditionSucceeded = true;

        for (BoardItems ship: this.m_ShipsList) {
            isAdditionSucceeded = m_ShipsBoard.AddItemToBoardGame(ship);
            if(!isAdditionSucceeded){
                m_ShipsBoard.ClearBoard();
                throw new GameException("Disable to add the ship to the board");
            }
        }
    }

    public void AddAttack(Action attackToAdd){
        m_AttacksStack.add(attackToAdd);
    }

    public void SaveAttack(Action attack){
        m_AttacksStack.add(attack);
    }

    public boolean HitBefore(Point pointOnBoard) {
        return m_TrackBoard.CheckIfHitBefore(pointOnBoard);
    }

    public boolean PlaceHitOnBoard(Point pointOnBoard){
        for (BoardItems ship: m_ShipsList){
            if (ship instanceof BattleShip){
                if (((BattleShip) ship).CheckHitOnBoard(pointOnBoard)){
                    ((BattleShip) ship).PlaceHitAndCheckSink(pointOnBoard);
                    return true;
                }
            }
        }

        return false;
    }

    public boolean CheckLMissOnBoard(){
        for (BoardItems ship: m_ShipsList){
            if (ship instanceof BattleShip){
                if (!((BattleShip) ship).CheckShipSank()){
                    return false;
                }
            }
        }

        return true;
    }

    public char CheckHitOnBoard(Point pointOnBoard) throws GameException{
        char signOnBoard= m_ShipsBoard.GetSignOnBoardByPoint(pointOnBoard);

        if (signOnBoard!= k_HitOnBoard && signOnBoard!='~' && signOnBoard!=eItems.Trap.getChar()) {
            m_ShipsBoard.UpdateHitOnBoard(pointOnBoard);
        PlaceHitOnBoard(pointOnBoard);
    }

        return signOnBoard;
    }
}

Assignment Code


package BattleShipLogic;

import java.awt.Point;

public class Trap extends BoardItems {
    public Trap(Point point) {
        super(eItems.Trap.getChar());
        this.m_SpreadingItemPoints = new Point[1];
        this.m_SpreadingItemPoints[0]=new Point(point);
    }

    public void BuildItem(){}

    public void SetTrapOnBoard(Point point){
        this.m_SpreadingItemPoints[0].setLocation(point);
    }
}

Assignment Code


package BattleShipUI;

import BattleShipLogic.*;

import java.awt.*;
import java.util.Scanner;
public class BattleShipUI {
    private Menu m_Menu =new Menu();
    private BattleShipLogic m_BattleShipGame =new BattleShipLogic();
    private eMenuType m_UserChoice =eMenuType.WaitingForAction;
    private String m_PathXmlFile;
    private boolean m_IsXmlFileLoaded = false;

    public void RunBattleShipGame(){
        eInputProblems inputProblems=eInputProblems.IsChoiceValid;
        while (m_UserChoice !=eMenuType.ExitGame){
            GetUserChoice();
            OperateChoice(m_UserChoice);
            if (m_UserChoice ==eMenuType.StartTheGame)
            {
                while (m_UserChoice !=eMenuType.ExitGame && m_UserChoice !=eMenuType.EndCurrentGame){
                    GetUserChoice();
                    OperateChoice(m_UserChoice);
                }
            }
            if(m_UserChoice ==eMenuType.ExitGame)
                printByeBye();
        }
    }

    public void GetUserChoice(){
        eInputProblems inputProblems=eInputProblems.IsChoiceValid;
        m_Menu.PrintMenu();
        do {
            m_UserChoice = eMenuType.getMenuType(ReadUserChoice());
            inputProblems = m_BattleShipGame.CheckUserChoice(m_UserChoice);
            if (inputProblems!=eInputProblems.IsChoiceValid)
                PrintInputProblem(inputProblems);
        }while (!inputProblems.equals(eInputProblems.IsChoiceValid));
    }

    public int ReadUserChoice(){
        int userChoice=0;
        Scanner s;
        int maxNumUserChoice= m_Menu.m_ArrMenuTypes.size();
        boolean isInputValid=false;

        System.out.println(String.format("Please type number of command from this menu list, 1-%d",maxNumUserChoice));
        while (!isInputValid) {
            s = new Scanner(System.in);
            if (s.hasNextInt())
            {
                userChoice=s.nextInt();
                if (userChoice<1 || userChoice>maxNumUserChoice)
                    System.out.println(String.format("User choice is out of range! Please enter a number BETWEEN 1 to %d!",maxNumUserChoice));
                else {
                    isInputValid=true;
                }
            }
            else
            {
                System.out.println("You have to type a command's NUMBER!");
            }
        }

        return userChoice;
    }

    private void SetIsXmlFileLoaded()
    {
        m_IsXmlFileLoaded =true;
    }

    private void DisplayGameStatistics(){
        Object[] statusInfo = m_BattleShipGame.GetStatisticsInfo();

        System.out.println("Statistics Of The Game:");
        System.out.println(String.format("Attacks counter: %d", (int)statusInfo[0]));
        System.out.println(String.format("Time of game that has passed: %s", (GameTime)statusInfo[1]));
        System.out.println("Statistics of Player A:");
        System.out.println(String.format("  Player score: %d", (int)statusInfo[2]));
        System.out.println(String.format("  Number of miss: %d", (int)statusInfo[3]));
        System.out.println(String.format("  Average time of attacks in the game: %s", (GameTime)statusInfo[4]));
        System.out.println("Statistics of Player B:");
        System.out.println(String.format("  Player Score: %d", (int)statusInfo[5]));
        System.out.println(String.format("  Number of miss: %d", (int)statusInfo[6]));
        System.out.println(String.format("  Average time of attacks in the game: %s", (GameTime)statusInfo[7]));
    }

    private void OperateChoice(eMenuType menuType)
    {
        boolean isWin=false;

        if (m_BattleShipGame.getStatusGame().equals(eStatusGame.GameStarted) && menuType!=eMenuType.ExitGame && menuType!=eMenuType.EndCurrentGame){
            PrintBoards();
        }
        
        switch (menuType)
        {
            case LoadXmlFile:
                OperateLoadXmlFile();
                break;
            case StartTheGame:
                CheckRestart();
                m_BattleShipGame.StartTheGame();
                SetIsXmlFileLoaded();
                PrintBoards();
                break;
            case GameStatus:
                PrintScore();
                break;
            case AttackOpponent:
                m_BattleShipGame.StartMoveTime();
                isWin= OperateAttackOpponent();
                break;
            case GameStatistics:
                DisplayGameStatistics();
                break;
            case Trap:
                SetTrapOnBoard();
                break;
            case EndCurrentGame:
                PrintEndGame();
                break;
        }

       if(isWin)
       {
           eMenuType.StartTheGame.setIsMenuTypeActive(true);
       }
    }
    private boolean OperateAttackOpponent(){
        Scanner s;
        boolean isAttackValid=false;
        eAttackResults attackResults;
        int x=0;
        int y=0;
        Point point;
        boolean isWin=false;

        System.out.println(String.format("Please choose a square (two numbers between 1 to %d) for attacking the opponent ", m_BattleShipGame.getBoardSize()));
        while (!isAttackValid){
            s=new Scanner(System.in);
            System.out.print("Row: ");
            if (s.hasNextInt() && x==0 )
                x=s.nextInt();
            System.out.print("Column: ");
            if (s.hasNextInt()&& y==0)
                y=s.nextInt();
            if (y==0 || x==0)
                System.out.println(String.format("You have to enter a NUMBER between 1 to %d", m_BattleShipGame.getBoardSize()));
            point=new Point(y-1,x-1);
            attackResults= m_BattleShipGame.AttackOpponent(point);
            switch (attackResults){
                case AttackEndedWithHit:
                    System.out.println("
Well Done! You hit a ship! ^_^
");
                    isAttackValid=true;
                    break;
                case AttackEndedWithMiss:
                    System.out.println("
You miss the ships :( ...Maybe next time
");
                    isAttackValid=true;
                    break;
                case AttackTrapWithObject:
                    System.out.println("
You attack the trap and there is an object
");//change TODO
                    isAttackValid=true;
                    break;
                case AttackTrapWithOutObject:
                    System.out.println("
You attack the trap and there is not an object
");//chang TODO
                    isAttackValid=true;
                    break;
                case HitBefore:
                    System.out.println("You hit this square before! Please choose a new square");
                    x=0;y=0;
                    break;
                case OutOfRange:
                    System.out.println(String.format("The square you chose is out of range!Please choose a new square(two numbers between 1 to %d) to attack", m_BattleShipGame.getBoardSize()));
                    x=0;y=0;
                    break;
                case Win:
                    System.out.println(String.format("Player %c Win!!!", m_BattleShipGame.FindWinners()+'A'));
                    isAttackValid=true;
                    isWin=true;
                    m_UserChoice =eMenuType.EndCurrentGame;
                    break;
            }
        }

        return isWin;
    }

    private void SetTrapOnBoard() {
        Scanner s;
        boolean isSetValid = false;
        eAttackResults trapResults;
        int x = 0;
        int y = 0;
        Point point;
        boolean isUserChoicePointValid=true;

        System.out.println(String.format("Please choose a square (two numbers between 1 to %d) for setting the trap ", m_BattleShipGame.getBoardSize()));
        while (!isSetValid) {
            s = new Scanner(System.in);
            System.out.print("Row: ");
            if (s.hasNextInt() && x == 0)
                x = s.nextInt();
            System.out.print("Column: ");
            if (s.hasNextInt() && y == 0)
                y = s.nextInt();
            if (y == 0 || x == 0)
                System.out.println(String.format("You have to enter a NUMBER between 1 to %d", m_BattleShipGame.getBoardSize()));
            point = new Point(y - 1, x - 1);
            isUserChoicePointValid = m_BattleShipGame.SetTrapOnBoard(point);
            if(!isUserChoicePointValid)
            {
                System.out.println(String.format("Your point is not valid , you have to choose a point ,You must select a point with a distance of one square  from the object "));
                x=0;
                y=0;
            }
            else
                isSetValid=true;
        }
    }
    private void OperateLoadXmlFile(){
        Scanner s;
        boolean isPathForXmlValid=false;
        String xmlSuffix=".xml";
        
        System.out.println("Please enter the full path for the xml with the xml suffix:");
        while (!isPathForXmlValid) {
            s = new Scanner(System.in);
           m_PathXmlFile = s.nextLine();
            if (!m_PathXmlFile.endsWith(xmlSuffix))
                System.out.println("You have to enter xml path with xml suffix! This is not a Xml file!! ");
            else{
                isPathForXmlValid= LoadXmlFile(isPathForXmlValid);
            }
        }
        System.out.println("Xml file Loaded successfully!!
");
    }

    private boolean LoadXmlFile(boolean isPathValid)
    {
        eProblemsXML problemsXml;

        problemsXml= m_BattleShipGame.LoadItemsFromXML(m_PathXmlFile);
        if (problemsXml== eProblemsXML.XmlIsValid)
            isPathValid=true;
        else PrintXmlProblems(problemsXml);

        return  isPathValid;
    }

    private void CheckRestart()
    {
        boolean isValid=false;

        if(m_IsXmlFileLoaded)
        {
            m_BattleShipGame.ClearAllBoards();
            isValid= LoadXmlFile(isValid);
        }
    }

    public void PrintScore()
    {
        System.out.println(String.format("Player %c score: %d
", m_BattleShipGame.getAttackerPlayer()+'A', m_BattleShipGame.getAttackerPlayerScore()));
    }

    public void PrintInputProblem(eInputProblems inputProblems){
        switch (inputProblems){
            case OperateOtherCommandBeforeLoading:
                System.out.println("You have to choose load from xml or load from file FIRST!");
                break;
            case OperateGameActionBeforeStarted:
                System.out.println("You have to choose to play against computer or one of the load options!");
                break;
            case OperateSettingsCommandWhenGameIsOn:
                System.out.println("You have to choose another command! This is a pregame command!!");
                break;
        }
    }

    private void PrintXmlProblems(eProblemsXML xmlProblems){
        switch (xmlProblems){
            case XmlDoesNotExist:
                System.out.println("Xml file does not exist in this PATH!");
                break;
            case XmlBoardSizeInvalid:
                System.out.println("The size of the board in xml file file is illegal! It has to be BETWEEN 5-20!");
                break;
            case XmlShipItemsNumberInvalid:
                System.out.println("The number of ship items in xml file is not the same as the amount in the specific xml file!");
                break;
            case XmlShipPositionInvalid:
                System.out.println("The ship positions in the xml file is illegal!");
                break;
        }
    }

    public void PrintEndGame()
    {
        printTechnicalVictory();
        PrintShipBoardAttackerPlayer();
        PrintShipBoardPlayerOnBreak();
        DisplayGameStatistics();
        printByeBye();
        eMenuType.StartTheGame.setIsMenuTypeActive(true);
    }

    private void PrintGameBoard(char[][] board)
    {
        System.out.print("\ ");
        for (int i = 0; i< m_BattleShipGame.getBoardSize(); i++) {
            System.out.print(' ');
            System.out.print((char)('A'+i));
            System.out.print(' ');
            System.out.print(' ');
        }
        System.out.println();
        for (int i = 0; i< m_BattleShipGame.getBoardSize(); i++)
        {
            System.out.print(String.format("%d ",i+1));
            for (int j = 0; j< m_BattleShipGame.getBoardSize(); j++){
                System.out.print(String.format("|%c| ",board[i][j]));
            }
            System.out.println();
        }
        System.out.println();
    }

    private void PrintShipBoardAttackerPlayer(){
        System.out.println(String.format("Player %c:", m_BattleShipGame.getAttackerPlayer()+'A'));
        System.out.println("ship board:");
        PrintGameBoard(m_BattleShipGame.getAttackerPlayerShipBoard());
    }

    private void PrintShipBoardPlayerOnBreak(){
        System.out.println(String.format("Player %c:", m_BattleShipGame.getPlayerOnBreak()+'A'));
        System.out.println("ship board:");
        PrintGameBoard(m_BattleShipGame.getPlayerOnBreakShipBoard());
    }

    private void PrintTrackBoard(){
        System.out.println("Track board:");
        PrintGameBoard(m_BattleShipGame.getAttackerPlayerTrackBoard());
    }

    private void printTechnicalVictory()
    {
        System.out.println(String.format("Player %c win because player %c left the game", m_BattleShipGame.getPlayerOnBreak()+'A', m_BattleShipGame.getAttackerPlayer()+'A'));
    }

    private void printByeBye()
    {
        System.out.println("Thanks for playing!
 Bye! Bye! ;)");
    }

    private void PrintBoards(){
        System.out.println(String.format("Player %c", m_BattleShipGame.getAttackerPlayer()+'A'));
        PrintShipBoardAttackerPlayer();
        PrintTrackBoard();
    }
}

Assignment Code


package BattleShipUI;
// C:UsersgalhdDesktopBattleShipGameattleShip_5_basic_advance.xml

public class Main {

    public static void main(String[] args) {
        BattleShipUI m_Game = new BattleShipUI();

        m_Game.RunBattleShipGame();
    }
}

Assignment Code


package BattleShipUI;

import BattleShipLogic.eMenuType;

import java.util.ArrayList;

public class Menu {
    ArrayList<eMenuType> m_ArrMenuTypes = new ArrayList();
    String m_MenuTitle ="Battle BattleShip Menu:";

    public ArrayList<eMenuType> getArrMenuTypes() {
        return m_ArrMenuTypes;
    }

    public Menu()
    {
        m_ArrMenuTypes.add(eMenuType.LoadXmlFile);
        m_ArrMenuTypes.add(eMenuType.StartTheGame);
        m_ArrMenuTypes.add(eMenuType.GameStatus);
        m_ArrMenuTypes.add(eMenuType.AttackOpponent);
        m_ArrMenuTypes.add(eMenuType.GameStatistics);
        m_ArrMenuTypes.add(eMenuType.EndCurrentGame);
        m_ArrMenuTypes.add(eMenuType.Trap);
        m_ArrMenuTypes.add(eMenuType.ExitGame);
    }

    public void PrintMenu()
    {
        System.out.println(m_MenuTitle);
        System.out.println("===========================");
        for (eMenuType menuType: m_ArrMenuTypes)
        {
            System.out.println(String.format("%d) %s",menuType.getMenuTypeNumber(),menuType.getMenuTypeDescription()));
        }
    }
}

Assignment Code


package FXML;

public class BattleShipGameFXMLController {
}

Frequently Asked Questions

Is it free to get my assignment evaluated?

Yes. No hidden fees. You pay for the solution only, and all the explanations about how to run it are included in the price. It takes up to 24 hours to get a quote from an expert. In some cases, we can help you faster if an expert is available, but you should always order in advance to avoid the risks. You can place a new order here.

How much does it cost?

The cost depends on many factors: how far away the deadline is, how hard/big the task is, if it is code only or a report, etc. We try to give rough estimates here, but it is just for orientation (in USD):

Regular homework$20 - $150
Advanced homework$100 - $300
Group project or a report$200 - $500
Mid-term or final project$200 - $800
Live exam help$100 - $300
Full thesis$1000 - $3000

How do I pay?

Credit card or PayPal. You don't need to create/have a Payal account in order to pay by a credit card. Paypal offers you "buyer's protection" in case of any issues.

Why do I need to pay in advance?

We have no way to request money after we send you the solution. PayPal works as a middleman, which protects you in case of any disputes, so you should feel safe paying using PayPal.

Do you do essays?

No, unless it is a data analysis essay or report. This is because essays are very personal and it is easy to see when they are written by another person. This is not the case with math and programming.

Why there are no discounts?

It is because we don't want to lie - in such services no discount can be set in advance because we set the price knowing that there is a discount. For example, if we wanted to ask for $100, we could tell that the price is $200 and because you are special, we can do a 50% discount. It is the way all scam websites operate. We set honest prices instead, so there is no need for fake discounts.

Do you do live tutoring?

No, it is simply not how we operate. How often do you meet a great programmer who is also a great speaker? Rarely. It is why we encourage our experts to write down explanations instead of having a live call. It is often enough to get you started - analyzing and running the solutions is a big part of learning.

What happens if I am not satisfied with the solution?

Another expert will review the task, and if your claim is reasonable - we refund the payment and often block the freelancer from our platform. Because we are so harsh with our experts - the ones working with us are very trustworthy to deliver high-quality assignment solutions on time.

Customer Feedback

"Thanks for explanations after the assignment was already completed... Emily is such a nice tutor! "

Order #13073

Find Us On

soc fb soc insta


Paypal supported