Compare commits

...

4 Commits

Author SHA1 Message Date
b5b8a7fdbe правки 2023-12-23 14:30:48 +04:00
b2a673367b Laba2 done 2023-12-23 13:32:09 +04:00
72cf91adfd Laba1 2023-12-21 16:08:03 +04:00
3fbab7e641 Laba1 2023-12-21 16:07:51 +04:00
20 changed files with 1066 additions and 10 deletions

View File

@ -1,27 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="29352b25-08d8-425d-8ed8-8d142cfadb63" name="Changes" comment="" />
<list default="true" id="29352b25-08d8-425d-8ed8-8d142cfadb63" name="Changes" comment="Laba2 done">
<change afterPath="$PROJECT_DIR$/src/DrawningTriangularBlocks.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/DrawningRoundBlocks.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/DrawningRoundBlocks.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/DrawningShip.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/DrawningShip.java" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Interface" />
<option value="Class" />
</list>
</option>
</component>
<component name="Git.Settings">
<option name="RECENT_BRANCH_BY_REPOSITORY">
<map>
<entry key="$PROJECT_DIR$" value="LabWork_01" />
</map>
</option>
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="ProjectId" id="2ZndrqDKd0BC8J1MiRrWFGjxqzn" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true">
<ConfirmationsSetting value="2" id="Add" />
</component>
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
"RunOnceActivity.OpenProjectViewOnStart": "true",
"RunOnceActivity.ShowReadmeOnStart": "true"
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;project.structure.last.edited&quot;: &quot;Modules&quot;,
&quot;project.structure.proportion&quot;: &quot;0.15&quot;,
&quot;project.structure.side.proportion&quot;: &quot;0.2&quot;
}
}]]></component>
}</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
@ -31,6 +57,44 @@
<option name="presentableId" value="Default" />
<updated>1703061980189</updated>
</task>
<task id="LOCAL-00001" summary="Laba1">
<created>1703160472180</created>
<option name="number" value="00001" />
<option name="presentableId" value="LOCAL-00001" />
<option name="project" value="LOCAL" />
<updated>1703160472180</updated>
</task>
<task id="LOCAL-00002" summary="Laba1">
<created>1703160484223</created>
<option name="number" value="00002" />
<option name="presentableId" value="LOCAL-00002" />
<option name="project" value="LOCAL" />
<updated>1703160484223</updated>
</task>
<task id="LOCAL-00003" summary="Laba2 done">
<created>1703323929322</created>
<option name="number" value="00003" />
<option name="presentableId" value="LOCAL-00003" />
<option name="project" value="LOCAL" />
<updated>1703323929322</updated>
</task>
<option name="localTasksCounter" value="4" />
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
<option name="TAB_STATES">
<map>
<entry key="MAIN">
<value>
<State />
</value>
</entry>
</map>
</option>
</component>
<component name="VcsManagerConfiguration">
<MESSAGE value="Laba1" />
<MESSAGE value="Laba2 done" />
<option name="LAST_COMMIT_MESSAGE" value="Laba2 done" />
</component>
</project>

123
src/AbstractStrategy.java Normal file
View File

@ -0,0 +1,123 @@
public abstract class AbstractStrategy {
/// <summary>
/// Перемещаемый объект
/// </summary>
private IMoveableObject _moveableObject;
/// <summary>
/// Статус перемещения
/// </summary>
private Status _state = Status.NotInit;
/// <summary>
/// Ширина поля
/// </summary>
private int fieldWidth;
protected int getFieldWidth() {return fieldWidth;}
/// <summary>
/// Высота поля
/// </summary>
private int fieldHeight;
protected int getFieldHeight(){return fieldHeight;}
/// <summary>
/// Статус перемещения
/// </summary>
public Status GetStatus() { return _state; }
/// <summary>
/// Установка данных
/// </summary>
/// <param name="moveableObject">Перемещаемый объект</param>
/// <param name="width">Ширина поля</param>
/// <param name="height">Высота поля</param>
public void SetData(IMoveableObject moveableObject, int width, int
height)
{
if (moveableObject == null)
{
_state = Status.NotInit;
return;
}
_state = Status.InProgress;
_moveableObject = moveableObject;
fieldWidth = width;
fieldHeight = height;
}
/// <summary>
/// Шаг перемещения
/// </summary>
public void MakeStep()
{
if (_state != Status.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = Status.Finish;
return;
}
MoveToTarget();
}
/// <summary>
/// Перемещение влево
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться, false - неудача)</returns>
protected boolean MoveLeft() { return MoveTo(DirectionType.LEFT);}
/// <summary>
/// Перемещение вправо
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</returns>
protected boolean MoveRight() { return MoveTo(DirectionType.RIGHT);}
/// <summary>
/// Перемещение вверх
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</returns>
protected boolean MoveUp() { return MoveTo(DirectionType.UP);}
/// <summary>
/// Перемещение вниз
/// </summary>
/// <returns>Результат перемещения (true - удалось переместиться,false - неудача)</returns>
protected boolean MoveDown() { return MoveTo(DirectionType.DOWN);}
/// <summary>
/// Параметры объекта
/// </summary>
protected ObjectParameters getObjectParameters() { return _moveableObject.GetObjectPosition(); }
/// <summary>
/// Шаг объекта
/// </summary>
/// <returns></returns>
protected int GetStep()
{
if (_state != Status.InProgress)
{
return 0;
}
return _moveableObject.GetStep();
}
/// <summary>
/// Перемещение к цели
/// </summary>
protected abstract void MoveToTarget();
/// <summary>
/// Достигнута ли цель
/// </summary>
/// <returns></returns>
protected abstract boolean IsTargetDestinaion();
/// <summary>
/// Попытка перемещения в требуемом направлении
/// </summary>
/// <param name="Direction">Направление</param>
/// <returns>Результат попытки (true - удалось переместиться, false - неудача)</returns>
private boolean MoveTo(DirectionType Direction)
{
if (_state != Status.InProgress)
{
return false;
}
if (_moveableObject.CheckCanMove(Direction))
{
_moveableObject.MoveObject(Direction);
return true;
}
return false;
}
}

5
src/BlocksNumber.java Normal file
View File

@ -0,0 +1,5 @@
public enum BlocksNumber {
TWO,
FOUR,
SIX
}

6
src/DirectionType.java Normal file
View File

@ -0,0 +1,6 @@
public enum DirectionType {
UP,
DOWN,
LEFT,
RIGHT
}

View File

@ -0,0 +1,40 @@
import java.awt.*;
public class DrawingBattleship extends DrawningShip {
public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor,boolean tower,
boolean section, int width, int height, int blocksType, int blocksNumber) {
super(speed, weight, bodyColor, width, height, blocksType, blocksNumber);
if (entityShip != null)
entityShip = new EntityBattleship(speed, weight, bodyColor, additionalColor, tower, section);
}
public void drawTransport(Graphics2D g2d){
if (entityShip == null)
return;
super.drawTransport(g2d);
g2d.setColor(((EntityBattleship)entityShip).AdditionalColor);
BasicStroke pen = new BasicStroke(2);
g2d.setStroke(pen);
//орудийная башня
if (((EntityBattleship)entityShip).Tower) {
g2d.fillRect(startPosX + 108, startPosY + 28, 15, 15);
g2d.drawRect(startPosX + 108, startPosY + 28, 15, 15);
// добавить черный цвет пушке
Color gunColor = Color.BLACK;
g2d.setColor(gunColor);
g2d.setStroke(pen);
g2d.fillRect(startPosX + 123, startPosY + 32, 47, 6);
g2d.drawRect(startPosX + 123, startPosY + 32, 55, 6);
}
//отсеки под ракеты
if (((EntityBattleship)entityShip).Section) {
g2d.fillRect(startPosX + 20, startPosY + 70, 40, 10);
g2d.fillRect(startPosX + 75, startPosY + 70, 40, 10);
g2d.setPaint(Color.BLACK);
g2d.drawRect(startPosX + 20, startPosY + 70, 40, 10);
g2d.drawRect(startPosX + 75, startPosY + 70, 40, 10);
}
}
}

25
src/DrawingBlocks.java Normal file
View File

@ -0,0 +1,25 @@
import java.awt.*;
public class DrawingBlocks implements IDrawBlocks{
private BlocksNumber number;
public void setNumber(int x){
if(x <= 2)
number = BlocksNumber.TWO;
if(x == 4)
number = BlocksNumber.FOUR;
if(x >= 6)
number = BlocksNumber.SIX;
}
public void drawBlocks(Graphics2D graphics2D, int _startX, int _startY){
graphics2D.fillRect(_startX+45, _startY+15, 5, 5);
graphics2D.fillRect(_startX+45, _startY+50, 5, 5);
if (number == BlocksNumber.FOUR || number == BlocksNumber.SIX){
graphics2D.fillRect(_startX+55, _startY+15, 5, 5);
graphics2D.fillRect(_startX+55, _startY+50, 5, 5);
if (number == BlocksNumber.SIX){
graphics2D.fillRect(_startX+35, _startY+15, 5, 5);
graphics2D.fillRect(_startX+35, _startY+50, 5, 5);
}
}
}
}

View File

@ -0,0 +1,19 @@
public class DrawningObjectShip implements IMoveableObject {
private DrawningShip drawingShip = null;
public DrawningObjectShip(DrawningShip _drawingShip)
{
drawingShip = _drawingShip;
}
public ObjectParameters GetObjectPosition(){
if (drawingShip == null || drawingShip.getEntityShip() == null)
{
return null;
}
return new ObjectParameters(drawingShip.GetPosX(),
drawingShip.GetPosY(), drawingShip.GetWidth(), drawingShip.GetHeight());
}
public int GetStep(){ return (int)drawingShip.getEntityShip().Step; }
public boolean CheckCanMove(DirectionType direction) { return drawingShip.CanMove(direction);}
public void MoveObject(DirectionType direction) { drawingShip.MoveTransport(direction); }
}

View File

@ -0,0 +1,28 @@
import java.awt.*;
public class DrawningRoundBlocks implements IDrawBlocks {
private BlocksNumber number;
@Override
public void setNumber(int x) {
if (x <= 2)
number = BlocksNumber.TWO;
if (x == 4)
number = BlocksNumber.FOUR;
if (x >= 6)
number = BlocksNumber.SIX;
}
@Override
public void drawBlocks(Graphics2D graphics2D, int _startX, int _startY){
graphics2D.fillOval(_startX+45, _startY+15, 8, 8);
graphics2D.fillOval(_startX+45, _startY+50, 8, 8);
if (number == BlocksNumber.FOUR || number == BlocksNumber.SIX){
graphics2D.fillOval(_startX+55, _startY+15, 8, 8);
graphics2D.fillOval(_startX+55, _startY+50, 8, 8);
if (number == BlocksNumber.SIX){
graphics2D.fillOval(_startX+35, _startY+15, 8, 8);
graphics2D.fillOval(_startX+35, _startY+50, 8, 8);
}
}
}
}

185
src/DrawningShip.java Normal file
View File

@ -0,0 +1,185 @@
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.*;
public class DrawningShip {
private IDrawBlocks drawingBlocks;
protected EntityShip entityShip;
public EntityShip getEntityShip(){return entityShip;}
/// <summary>
/// Ширина окна
/// </summary>
protected int _pictureWidth;
/// <summary>
/// Высота окна
/// </summary>
protected int _pictureHeight;
/// <summary>
/// Левая координата прорисовки локомотива
/// </summary>
protected int startPosX;
/// <summary>
/// Верхняя кооридната прорисовки локомотива
/// </summary>
protected int startPosY;
/// <summary>
/// Координата X объекта
/// </summary>
public int GetPosX (){return startPosX;}
/// <summary>
/// Координата Y объекта
/// </summary>
public int GetPosY (){return startPosY;}
/// <summary>
/// Ширина объекта
/// </summary>
public int GetWidth (){return shipWidth;}
/// <summary>
/// Высота объекта
/// </summary>
public int GetHeight (){return shipHeight;}
/// <summary>
/// Ширина прорисовки локомотива
/// </summary>
protected int shipWidth = 175;
protected int shipHeight = 80;
/// <summary>
/// Инициализация свойств
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес</param>
/// <param name="bodyColor">Цвет кузова</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawningShip(int speed, double weight, Color bodyColor, int width, int height, int blocksType, int blocksNumber)
{
_pictureWidth = width;
_pictureHeight = height;
if (width < shipWidth || height < shipHeight)
return;
entityShip = new EntityShip(speed, weight, bodyColor);
Random random = new Random();
switch(blocksType){
case 0:
drawingBlocks = new DrawingBlocks();
break;
case 1:
drawingBlocks = new DrawningRoundBlocks();
break;
case 2:
drawingBlocks = new DrawningTriangularBlocks();
break;
default:
drawingBlocks = new DrawingBlocks();
break;
}
drawingBlocks.setNumber(blocksNumber);
}
/// <summary>
/// Установка позиции
/// </summary>
/// <param name="x">Координата X</param>
/// <param name="y">Координата Y</param>
public void SetPosition(int x, int y)
{
if (x < 0 || y < 0 || x + shipWidth > _pictureWidth || y + shipHeight > _pictureHeight) {
x = 0;
y = 0;
}
startPosX = x;
startPosY = y;
}
/// <summary>
/// Проверка, что объект может переместится по указанному направлению
/// </summary>
/// <param name="direction">Направление</param>
/// <returns>true - можно переместится по указанному направлению</returns>
public boolean CanMove(DirectionType direction)
{
if (entityShip == null)
{
return false;
}
switch (direction)
{
case LEFT:
return startPosX - entityShip .Step > 0;
case RIGHT:
return startPosX + shipWidth + entityShip .Step < _pictureWidth;
case UP:
return startPosY - entityShip .Step > 0;
case DOWN:
return startPosY + shipHeight + entityShip .Step < _pictureHeight;
default:
return false;
}
}
public void MoveTransport(DirectionType direction)
{
if (!CanMove(direction) || entityShip == null)
{
return;
}
switch (direction)
{
//влево
case LEFT:
startPosX -= (int)entityShip.Step;
break;
//вверх
case UP:
startPosY -= (int)entityShip.Step;
break;
// вправо
case RIGHT:
startPosX += (int)entityShip.Step;
break;
//вниз
case DOWN:
startPosY += (int)entityShip.Step;
break;
}
}
public void drawTransport(Graphics2D g2d) {
if (entityShip == null) {
return;
}
BasicStroke pen = new BasicStroke(2);
g2d.setStroke(pen);
Color bodyColor = entityShip.BodyColor;
//основа
int[] xPoints = {startPosX + 5, startPosX + 120, startPosX + 160, startPosX + 120, startPosX + 5};
int[] yPoints = {startPosY + 0, startPosY + 0, startPosY + 35, startPosY + 70, startPosY + 70};
g2d.setColor(bodyColor);
g2d.fillPolygon(xPoints, yPoints, 5);
g2d.setPaint(Color.BLACK);
g2d.drawPolygon(xPoints, yPoints, 5);
//блоки
g2d.setPaint(Color.DARK_GRAY);
g2d.fillRect(startPosX + 70, startPosY + 15, 20, 40);
g2d.setPaint(Color.BLACK);
g2d.drawRect(startPosX + 70, startPosY + 15, 20, 40);
g2d.setPaint(Color.DARK_GRAY);
g2d.fillRect(startPosX + 40, startPosY + 25, 30, 20);
g2d.setPaint(Color.BLACK);
g2d.drawRect(startPosX + 40, startPosY + 25, 30, 20);
g2d.setPaint(Color.DARK_GRAY);
g2d.fillOval(startPosX + 100, startPosY + 20, 30, 30);
g2d.setPaint(Color.BLACK);
g2d.drawOval(startPosX + 100, startPosY + 20, 30, 30);
//для ускорения
g2d.setPaint(Color.YELLOW);
g2d.fillRect(startPosX + 0, startPosY + 10, 5, 20);
g2d.fillRect(startPosX + 0, startPosY + 40, 5, 20);
g2d.setPaint(Color.BLACK);
g2d.drawRect(startPosX + 0, startPosY + 40, 5, 20);
g2d.drawRect(startPosX + 0, startPosY + 10, 5, 20);
//блоки
if (drawingBlocks != null) {
drawingBlocks.drawBlocks(g2d, startPosX, startPosY);
}
}
}

View File

@ -0,0 +1,45 @@
import java.awt.*;
public class DrawningTriangularBlocks implements IDrawBlocks{
private BlocksNumber number;
public void setNumber(int x) {
if (x <= 2)
number = BlocksNumber.TWO;
if (x == 4)
number = BlocksNumber.FOUR;
if (x >= 6)
number = BlocksNumber.SIX;
}
public void drawBlocks(Graphics2D graphics2D, int _startX, int _startY){
int[] xPoints = {_startX+45, _startX+50, _startX+40};
int[] yPoints = {_startY+15, _startY+20, _startY+20};
int[] xPoints1 = {_startX+45, _startX+50, _startX+40};
int[] yPoints1 = {_startY+50, _startY+55, _startY+55};
graphics2D.fillPolygon(xPoints, yPoints, 3);
graphics2D.fillPolygon(xPoints, yPoints, 3);
graphics2D.fillPolygon(xPoints1, yPoints1, 3);
graphics2D.fillPolygon(xPoints1, yPoints1, 3);
if (number == BlocksNumber.FOUR || number == BlocksNumber.SIX){
xPoints = new int[]{_startX+55, _startX+60, _startX+50};
yPoints = new int[]{_startY+15, _startY+20, _startY+20};
xPoints1 = new int[]{_startX+55, _startX+60, _startX+50};
yPoints1 = new int[]{_startY+50, _startY+55, _startY+55};
graphics2D.fillPolygon(xPoints, yPoints, 3);
graphics2D.fillPolygon(xPoints, yPoints, 3);
graphics2D.fillPolygon(xPoints1, yPoints1, 3);
graphics2D.fillPolygon(xPoints1, yPoints1, 3);
if (number == BlocksNumber.SIX){
xPoints = new int[]{_startX+35, _startX+40, _startX+30};
yPoints = new int[]{_startY+15, _startY+20, _startY+20};
xPoints1 = new int[]{_startX+35, _startX+40, _startX+30};
yPoints1 = new int[]{_startY+50, _startY+55, _startY+55};
graphics2D.fillPolygon(xPoints, yPoints, 3);
graphics2D.fillPolygon(xPoints, yPoints, 3);
graphics2D.fillPolygon(xPoints1, yPoints1, 3);
graphics2D.fillPolygon(xPoints1, yPoints1, 3);
}
}
}
}

16
src/EntityBattleship.java Normal file
View File

@ -0,0 +1,16 @@
import java.awt.*;
public class EntityBattleship extends EntityShip{
public Color AdditionalColor;
public boolean Tower;
public boolean Section;
public EntityBattleship(int speed, double weight, Color bodyColor, Color
additionalColor, boolean tower, boolean section)
{
super(speed, weight, bodyColor);
AdditionalColor = additionalColor;
Tower = tower;
Section = section;
}
}

33
src/EntityShip.java Normal file
View File

@ -0,0 +1,33 @@
import java.awt.*;
public class EntityShip {
/// <summary>
/// Скорость
/// </summary>
public int Speed;
/// <summary>
/// Вес
/// </summary>
public double Weight;
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor;
/// <summary>
/// Шаг перемещения поезда
/// </summary>
public double Step;
/// <summary>
/// Инициализация полей объекта-класса Локомотива
/// </summary>
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес автомобиля</param>
/// <param name="bodyColor">Основной цвет</param>
public EntityShip(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
Step = (double)Speed * 100 / Weight;
}
}

357
src/FrameBattleship.java Normal file
View File

@ -0,0 +1,357 @@
//import javax.imageio.ImageIO;
//import javax.swing.*;
//import java.awt.*;
//import java.awt.event.ActionEvent;
//import java.io.File;
//import java.io.IOException;
//import java.util.Random;
//
//public class FrameBattleship extends JFrame {
// private DrawingBattleship drawingBattleship;
// private DrawningShip drawningShip;
// private AbstractStrategy abstractStrategy;
// private JComboBox<String> comboBoxStrategy;
// private JComponent pictureBox;
//
// public FrameBattleship() throws IOException {
// super("Линкор");
// setSize(new Dimension(900, 500));
// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// //components initialisation
// pictureBox = new JComponent() {
// public void paintComponent(Graphics graphics) {
// super.paintComponent(graphics);
// Graphics2D graphics2D = (Graphics2D) graphics;
// if (drawingBattleship != null) drawingBattleship.drawTransport(graphics2D);
// super.repaint();
// }
// };
// pictureBox.setBounds(0, 0, getContentPane().getWidth(), getContentPane().getHeight());
// comboBoxStrategy = new JComboBox<>(new String[]{"К центру", "К границе"});
// JButton stepButton = new JButton("Шаг");
// JButton createShipButton = new JButton("Создать корабль");
// JButton createBattleshipButton = new JButton("Создать военный корабль");
// JButton rightButton = new JButton(new ImageIcon(ImageIO.read(new File("C:\\RPP intellij\\LabWork_01\\images\\right-arrow.png"))));
// rightButton.setPreferredSize(new Dimension(30, 30));
// JButton leftButton = new JButton(new ImageIcon(ImageIO.read(new File("C:\\RPP intellij\\LabWork_01\\images\\left-arrow.png"))));
// leftButton.setPreferredSize(new Dimension(30, 30));
// JButton upButton = new JButton(new ImageIcon(ImageIO.read(new File("C:\\RPP intellij\\LabWork_01\\images\\upper-arrow.png"))));
// upButton.setPreferredSize(new Dimension(30, 30));
// JButton downButton = new JButton(new ImageIcon(ImageIO.read(new File("C:\\RPP intellij\\LabWork_01\\images\\down-arrow.png"))));
// downButton.setPreferredSize(new Dimension(30, 30));
// //ActionListeners and ActionCommand addition
// createShipButton.addActionListener(e -> buttonCreateShipClick());
// createBattleshipButton.addActionListener(e -> buttonCreateBattleshipClick());
// stepButton.addActionListener(e -> buttonStepClick());
// rightButton.setActionCommand("right");
// rightButton.addActionListener(this::buttonMoveClick);
// leftButton.setActionCommand("left");
// leftButton.addActionListener(this::buttonMoveClick);
// upButton.setActionCommand("up");
// upButton.addActionListener(this::buttonMoveClick);
// downButton.setActionCommand("down");
// downButton.addActionListener(this::buttonMoveClick);
// //panels and constraints initialisation
// JPanel panelBattleship = new JPanel(new BorderLayout());
// JPanel rightPanel = new JPanel(new BorderLayout());
// JPanel leftPanel = new JPanel(new BorderLayout());
// JPanel createPanel = new JPanel(new BorderLayout());
// JPanel movementPanel = new JPanel(new GridBagLayout());
// GridBagConstraints constraints = new GridBagConstraints();
// constraints.insets.left = constraints.insets.top = constraints.insets.bottom = constraints.insets.right = 2;
// //addition to createPanel
// constraints.gridx = 0;
// constraints.gridy = 0;
// createPanel.add(createShipButton, BorderLayout.SOUTH);
// constraints.gridx = 1;
// constraints.gridy = 0;
// createPanel.add(createBattleshipButton, constraints);
// //addition to movementPanel
// constraints.gridx = 2;
// constraints.gridy = 1;
// movementPanel.add(rightButton, constraints);
// constraints.gridx = 0;
// constraints.gridy = 1;
// movementPanel.add(leftButton, constraints);
// constraints.gridx = 1;
// constraints.gridy = 0;
// movementPanel.add(upButton, constraints);
// constraints.gridx = 1;
// constraints.gridy = 1;
// movementPanel.add(downButton, constraints);
// //addition to stepPanel
// JPanel stepPanel = new JPanel(new GridBagLayout());
// constraints.gridx = 0;
// constraints.gridy = 0;
// stepPanel.add(comboBoxStrategy, constraints);
// constraints.gridx = 0;
// constraints.gridy = 1;
// stepPanel.add(stepButton, constraints);
// //addition to frame
// setLayout(new BorderLayout());
// add(pictureBox);
// rightPanel.add(movementPanel, BorderLayout.SOUTH);
// rightPanel.add(stepPanel, BorderLayout.NORTH);
// leftPanel.add(createPanel, BorderLayout.SOUTH);
// panelBattleship.add(rightPanel, BorderLayout.EAST);
// panelBattleship.add(leftPanel, BorderLayout.WEST);
// add(panelBattleship, BorderLayout.CENTER);
// setVisible(true);
// }
//
// private void buttonCreateShipClick() {
// Random random = new Random();
// pictureBox.setBounds(0,0,getContentPane().getWidth(),getContentPane().getHeight());
// drawningShip = new DrawningShip(random.nextInt(200) + 100, random.nextInt(2000) + 1000, new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)),
// pictureBox.getWidth(), pictureBox.getHeight(), random.nextInt(3),(random.nextInt(3)+1)*2);
// drawingBattleship.SetPosition(random.nextInt(90) + 10, random.nextInt(90) + 10);
// draw();
// }
// private void buttonCreateBattleshipClick() {
// Random random = new Random();
// pictureBox.setBounds(0,0,getContentPane().getWidth(),getContentPane().getHeight());
// drawingBattleship = new DrawingBattleship(random.nextInt(200) + 100, random.nextInt(2000) + 1000, new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)),
// new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)), random.nextBoolean(), random.nextBoolean(), pictureBox.getWidth(), pictureBox.getHeight(), random.nextInt(3),(random.nextInt(3)+1)*2);
// drawingBattleship.SetPosition(random.nextInt(90) + 10, random.nextInt(90) + 10);
// draw();
// }
//
// private void buttonStepClick(){
// if (drawingBattleship == null) {
// return;
// }
// if (comboBoxStrategy.isEnabled()) {
//// switch (comboBoxStrategy.getSelectedIndex()) {
//// case 0 -> abstractStrategy = new MoveToCenter();
//// case 1 -> abstractStrategy = new MoveToBorder();
//// default -> abstractStrategy = null;
//// }
// if (abstractStrategy == null) {
// return;
// }
// abstractStrategy.SetData(new DrawningObjectShip(drawingBattleship), pictureBox.getWidth(), pictureBox.getHeight());
// comboBoxStrategy.setEnabled(false);
// }
// if (abstractStrategy == null) {
// return;
// }
// abstractStrategy.MakeStep();
// draw();
// if (abstractStrategy.GetStatus() == Status.Finish)
// {
// comboBoxStrategy.setEnabled(true);
// abstractStrategy = null;
// }
// }
// private void buttonMoveClick(ActionEvent event) {
// if (drawingBattleship == null || drawingBattleship.getEntityShip() == null)
// return;
// switch (event.getActionCommand()) {
// case "left":
// drawingBattleship.MoveTransport(DirectionType.LEFT);
// break;
// case "right":
// drawingBattleship.MoveTransport(DirectionType.RIGHT);
// break;
// case "up":
// drawingBattleship.MoveTransport(DirectionType.UP);
// break;
// case "down":
// drawingBattleship.MoveTransport(DirectionType.DOWN);
// break;
// default:
// break;
// }
// draw();
// }
//
// private void draw() {
// if (drawingBattleship == null) {
// return;
// }
// pictureBox.repaint();
// }
//
//}
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.Random;
public class FrameBattleship extends JFrame {
private DrawningShip drawningShip;
private AbstractStrategy abstractStrategy;
private JComboBox<String> comboBoxStrategy;
private JComponent pictureBoxBattleship;
public FrameBattleship() throws IOException {
super("Линкор");
setSize(new Dimension(900,500));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//components initialisation
pictureBoxBattleship = new JComponent(){
public void paintComponent(Graphics graphics){
super.paintComponent(graphics);
Graphics2D graphics2D = (Graphics2D) graphics;
if (drawningShip != null) drawningShip.drawTransport(graphics2D);
super.repaint();
}
};
pictureBoxBattleship.setBounds( 0, 0, getContentPane().getWidth(), getContentPane().getHeight());
comboBoxStrategy = new JComboBox<>(new String[]{"к центру", "к границе"});
JButton stepButton = new JButton("Шаг");
JButton createShipButton = new JButton("Создать корабль");
JButton createBattleshipButton = new JButton("Создать военный корабль");
JButton rightButton = new JButton(new ImageIcon(ImageIO.read(new File("C:\\RPP intellij\\LabWork_01\\images\\right-arrow.png"))));
rightButton.setPreferredSize(new Dimension(30, 30));
JButton leftButton = new JButton(new ImageIcon(ImageIO.read(new File("C:\\RPP intellij\\LabWork_01\\images\\left-arrow.png"))));
leftButton.setPreferredSize(new Dimension(30, 30));
JButton upButton = new JButton(new ImageIcon(ImageIO.read(new File("C:\\RPP intellij\\LabWork_01\\images\\upper-arrow.png"))));
upButton.setPreferredSize(new Dimension(30, 30));
JButton downButton = new JButton(new ImageIcon(ImageIO.read(new File("C:\\RPP intellij\\LabWork_01\\images\\down-arrow.png"))));
downButton.setPreferredSize(new Dimension(30,30));
//ActionListeners and ActionCommand addition
createShipButton.addActionListener(e -> buttonCreateShipClick());
createBattleshipButton.addActionListener(e -> buttonCreateBattleshipClick());
stepButton.addActionListener(e -> buttonStepClick());
rightButton.setActionCommand("right");
rightButton.addActionListener(this::buttonMoveClick);
leftButton.setActionCommand("left");
leftButton.addActionListener(this::buttonMoveClick);
upButton.setActionCommand("up");
upButton.addActionListener(this::buttonMoveClick);
downButton.setActionCommand("down");
downButton.addActionListener(this::buttonMoveClick);
//panels and constraints initialisation
JPanel panelBattleship = new JPanel(new BorderLayout());
JPanel rightPanel = new JPanel(new BorderLayout());
JPanel leftPanel = new JPanel(new BorderLayout());
JPanel createPanel = new JPanel(new GridBagLayout());
JPanel movementPanel = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets.left = constraints.insets.top = constraints.insets.bottom = constraints.insets.right = 2;
//addition to createPanel
constraints.gridx = 0;
constraints.gridy = 0;
createPanel.add(createShipButton, constraints);
constraints.gridx = 1;
constraints.gridy = 0;
createPanel.add(createBattleshipButton, constraints);
//addition to movementPanel
constraints.gridx = 2;
constraints.gridy = 1;
movementPanel.add(rightButton, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
movementPanel.add(leftButton, constraints);
constraints.gridx = 1;
constraints.gridy = 0;
movementPanel.add(upButton, constraints);
constraints.gridx = 1;
constraints.gridy = 1;
movementPanel.add(downButton, constraints);
//addition to stepPanel
JPanel stepPanel = new JPanel(new GridBagLayout());
constraints.gridx = 0;
constraints.gridy = 0;
stepPanel.add(comboBoxStrategy, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
stepPanel.add(stepButton, constraints);
//addition to frame
setLayout(new BorderLayout());
add(pictureBoxBattleship);
rightPanel.add(movementPanel, BorderLayout.SOUTH);
rightPanel.add(stepPanel, BorderLayout.NORTH);
leftPanel.add(createPanel, BorderLayout.SOUTH);
panelBattleship.add(rightPanel, BorderLayout.EAST);
panelBattleship.add(leftPanel, BorderLayout.WEST);
add(panelBattleship,BorderLayout.CENTER);
setVisible(true);
}
private void buttonCreateBattleshipClick() {
Random random = new Random();
pictureBoxBattleship.setBounds(0,0,getContentPane().getWidth(),getContentPane().getHeight());
drawningShip = new DrawingBattleship(random.nextInt(200) + 100, random.nextInt(2000) + 1000, new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)),
new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)), random.nextBoolean(), random.nextBoolean(), pictureBoxBattleship.getWidth(), pictureBoxBattleship.getHeight(), random.nextInt(3),(random.nextInt(3)+1)*2);
drawningShip.SetPosition(random.nextInt(90) + 10, random.nextInt(90) + 10);
draw();
}
private void buttonCreateShipClick(){
Random random = new Random();
pictureBoxBattleship.setBounds(0,0,getContentPane().getWidth(),getContentPane().getHeight());
drawningShip = new DrawningShip(random.nextInt(200) + 100, random.nextInt(2000) + 1000, new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)),
pictureBoxBattleship.getWidth(), pictureBoxBattleship.getHeight(), random.nextInt(3),(random.nextInt(3)+1)*2);
drawningShip.SetPosition(random.nextInt(90) + 10, random.nextInt(90) + 10);
draw();
}
private void buttonStepClick(){
if (drawningShip == null) {
return;
}
if (comboBoxStrategy.isEnabled()) {
switch (comboBoxStrategy.getSelectedIndex())
{
case 0:
abstractStrategy = new MoveToCenter();
break;
case 1:
abstractStrategy = new MoveToBorder();
break;
default:
abstractStrategy = null;
break;
};
if (abstractStrategy == null) {
return;
}
abstractStrategy.SetData(new DrawningObjectShip(drawningShip), pictureBoxBattleship.getWidth(), pictureBoxBattleship.getHeight());
comboBoxStrategy.setEnabled(false);
}
if (abstractStrategy == null) {
return;
}
abstractStrategy.MakeStep();
draw();
if (abstractStrategy.GetStatus() == Status.Finish)
{
comboBoxStrategy.setEnabled(true);
abstractStrategy = null;
}
}
private void buttonMoveClick(ActionEvent event) {
if (drawningShip == null || drawningShip.getEntityShip() == null)
return;
switch (event.getActionCommand()) {
case "left":
drawningShip.MoveTransport(DirectionType.LEFT);
break;
case "right":
drawningShip.MoveTransport(DirectionType.RIGHT);
break;
case "up":
drawningShip.MoveTransport(DirectionType.UP);
break;
case "down":
drawningShip.MoveTransport(DirectionType.DOWN);
break;
default:
break;
}
draw();
}
private void draw() {
if (drawningShip == null)
{
return;
}
pictureBoxBattleship.repaint();
}
}

5
src/IDrawBlocks.java Normal file
View File

@ -0,0 +1,5 @@
import java.awt.*;
public interface IDrawBlocks {
void setNumber(int x);
void drawBlocks(Graphics2D graphics2D, int _startX, int _startY);
}

6
src/IMoveableObject.java Normal file
View File

@ -0,0 +1,6 @@
public interface IMoveableObject {
ObjectParameters GetObjectPosition();
int GetStep();
boolean CheckCanMove(DirectionType direction);
void MoveObject(DirectionType direction);
}

View File

@ -1,5 +1,8 @@
import javax.swing.*;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
public static void main(String[] args) throws IOException { new FrameBattleship();
}
}
}

37
src/MoveToBorder.java Normal file
View File

@ -0,0 +1,37 @@
public class MoveToBorder extends AbstractStrategy {
@Override
protected boolean IsTargetDestinaion() {
ObjectParameters objParams = getObjectParameters();
if (objParams == null) {
return false;
}
return objParams.RightBorder() <= getFieldWidth() &&
objParams.RightBorder() + GetStep() >= getFieldWidth() &&
objParams.DownBorder() <= getFieldHeight() &&
objParams.DownBorder() + GetStep() >= getFieldHeight();
}
@Override
protected void MoveToTarget() {
ObjectParameters objParams = getObjectParameters();
if (objParams == null) {
return;
}
double diffX = objParams.RightBorder() - getFieldWidth();
if (Math.abs(diffX) > GetStep()) {
if (diffX > 0) {
MoveLeft();
} else {
MoveRight();
}
}
double diffY = objParams.DownBorder() - getFieldHeight();
if (Math.abs(diffY) > GetStep()) {
if (diffY > 0) {
MoveUp();
} else {
MoveDown();
}
}
}
}

36
src/MoveToCenter.java Normal file
View File

@ -0,0 +1,36 @@
public class MoveToCenter extends AbstractStrategy {
@Override
protected boolean IsTargetDestinaion() {
ObjectParameters objParams = getObjectParameters();
if (objParams == null) {
return false;
}
return objParams.ObjectMiddleHorizontal() <= getFieldWidth() / 2 &&
objParams.ObjectMiddleHorizontal() + GetStep() >= getFieldWidth() / 2 &&
objParams.ObjectMiddleVertical() <= getFieldHeight() / 2 &&
objParams.ObjectMiddleVertical() + GetStep() >= getFieldHeight() / 2;
}
@Override
protected void MoveToTarget() {
ObjectParameters objParams = getObjectParameters();
if (objParams == null) {
return;
}
double diffX = objParams.ObjectMiddleHorizontal() - getFieldWidth() / 2;
if (Math.abs(diffX) > GetStep()) {
if (diffX > 0) {
MoveLeft();
} else {
MoveRight();
}
}
double diffY = objParams.ObjectMiddleVertical() - getFieldHeight() / 2;
if (Math.abs(diffY) > GetStep()) {
if (diffY > 0) {
MoveUp();
} else {
MoveDown();
}
}
}
}

18
src/ObjectParameters.java Normal file
View File

@ -0,0 +1,18 @@
public class ObjectParameters {
private final int POS_X;
private final int POS_Y;
private final int WIDTH;
private final int HEIGHT;
public int LeftBorder() {return POS_X;}
public int TopBorder() {return POS_Y;}
public int RightBorder() {return POS_X + WIDTH;}
public int DownBorder() {return POS_Y + HEIGHT;}
public int ObjectMiddleHorizontal() {return POS_X + this.WIDTH / 2;}
public int ObjectMiddleVertical() {return POS_Y + this.HEIGHT / 2;}
public ObjectParameters(int x, int y, int width, int height) {
POS_X = x;
POS_Y = y;
WIDTH = width;
HEIGHT = height;
}
}

5
src/Status.java Normal file
View File

@ -0,0 +1,5 @@
public enum Status {
NotInit,
InProgress,
Finish
}