Laba2 done

This commit is contained in:
Казначеева Елизавета 2023-12-23 13:32:09 +04:00
parent 72cf91adfd
commit b2a673367b
18 changed files with 856 additions and 175 deletions

View File

@ -1,4 +0,0 @@
<changelist name="Uncommitted_changes_before_Checkout_at_21_12_2023_16_01_[Changes]" date="1703160065503" recycled="false" toDelete="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/Uncommitted_changes_before_Checkout_at_21_12_2023_16_01_[Changes]/shelved.patch" />
<option name="DESCRIPTION" value="Uncommitted changes before Checkout at 21.12.2023 16:01 [Changes]" />
</changelist>

View File

@ -1,4 +0,0 @@
<changelist name="Uncommitted_changes_before_Checkout_at_21_12_2023_16_01_[Changes]1" date="1703160076909" recycled="true" deleted="true">
<option name="PATH" value="$PROJECT_DIR$/.idea/shelf/Uncommitted_changes_before_Checkout_at_21_12_2023_16_01_[Changes]1/shelved.patch" />
<option name="DESCRIPTION" value="Uncommitted changes before Checkout at 21.12.2023 16:01 [Changes]" />
</changelist>

View File

@ -5,39 +5,63 @@
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="29352b25-08d8-425d-8ed8-8d142cfadb63" name="Changes" comment="Laba1"> <list default="true" id="29352b25-08d8-425d-8ed8-8d142cfadb63" name="Changes" comment="Laba1">
<change afterPath="$PROJECT_DIR$/src/BlocksNumber.java" afterDir="false" /> <change afterPath="$PROJECT_DIR$/src/AbstractStrategy.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/DirectionType.java" afterDir="false" /> <change afterPath="$PROJECT_DIR$/src/DrawningObjectShip.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/DrawingBattleship.java" afterDir="false" /> <change afterPath="$PROJECT_DIR$/src/DrawningRoundBlocks.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/DrawingBlocks.java" afterDir="false" /> <change afterPath="$PROJECT_DIR$/src/DrawningShip.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/EntityBattleship.java" afterDir="false" /> <change afterPath="$PROJECT_DIR$/src/EntityShip.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/FrameBattleship.java" afterDir="false" /> <change afterPath="$PROJECT_DIR$/src/IDrawBlocks.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/Main.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/Main.java" afterDir="false" /> <change afterPath="$PROJECT_DIR$/src/IMoveableObject.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/MoveToBorder.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/MoveToCenter.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/ObjectParameters.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/Status.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/shelf/Uncommitted_changes_before_Checkout_at_21_12_2023_16_01__Changes_.xml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/shelf/Uncommitted_changes_before_Checkout_at_21_12_2023_16_01__Changes_1.xml" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/DrawingBattleship.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/DrawingBattleship.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/DrawingBlocks.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/DrawingBlocks.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/EntityBattleship.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/EntityBattleship.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/FrameBattleship.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/FrameBattleship.java" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" /> <option name="LAST_RESOLUTION" value="IGNORE" />
</component> </component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Interface" />
<option value="Class" />
</list>
</option>
</component>
<component name="Git.Settings"> <component name="Git.Settings">
<option name="RECENT_BRANCH_BY_REPOSITORY"> <option name="RECENT_BRANCH_BY_REPOSITORY">
<map> <map>
<entry key="$PROJECT_DIR$" value="master" /> <entry key="$PROJECT_DIR$" value="LabWork_01" />
</map> </map>
</option> </option>
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" /> <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component> </component>
<component name="ProjectId" id="2ZndrqDKd0BC8J1MiRrWFGjxqzn" /> <component name="ProjectId" id="2ZndrqDKd0BC8J1MiRrWFGjxqzn" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true" /> <component name="ProjectLevelVcsManager" settingsEditedManually="true">
<ConfirmationsSetting value="2" id="Add" />
</component>
<component name="ProjectViewState"> <component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" /> <option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" /> <option name="showLibraryContents" value="true" />
</component> </component>
<component name="PropertiesComponent">{ <component name="PropertiesComponent"><![CDATA[{
&quot;keyToString&quot;: { "keyToString": {
&quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;, "RunOnceActivity.OpenProjectViewOnStart": "true",
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot; "RunOnceActivity.ShowReadmeOnStart": "true",
"project.structure.last.edited": "Modules",
"project.structure.proportion": "0.15",
"project.structure.side.proportion": "0.2"
} }
}</component> }]]></component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" /> <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager"> <component name="TaskManager">
<task active="true" id="Default" summary="Default task"> <task active="true" id="Default" summary="Default task">
@ -47,8 +71,34 @@
<option name="presentableId" value="Default" /> <option name="presentableId" value="Default" />
<updated>1703061980189</updated> <updated>1703061980189</updated>
</task> </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>
<option name="localTasksCounter" value="3" />
<servers /> <servers />
</component> </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"> <component name="VcsManagerConfiguration">
<MESSAGE value="Laba1" /> <MESSAGE value="Laba1" />
<option name="LAST_COMMIT_MESSAGE" value="Laba1" /> <option name="LAST_COMMIT_MESSAGE" value="Laba1" />

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;
}
}

View File

@ -1,110 +1,24 @@
import java.awt.*; import java.awt.*;
public class DrawingBattleship { public class DrawingBattleship extends DrawningShip {
public EntityBattleship entityBattleship;
private DrawingBlocks drawingBlocks;
private int pictureWidth;
private int pictureHeight;
private int startPosX;
private int startPosY;
private final int shipWidth = 175;
private final int shipHeight = 80;
public boolean Init(int speed, double weight, Color bodyColor, Color public DrawingBattleship(int speed, double weight, Color bodyColor, Color additionalColor,boolean tower,
additionalColor, boolean turret, boolean rocketLauncher, int width, int height, int blocksNumber) { boolean section, int width, int height, int blocksType, int blocksNumber) {
if (width < shipWidth || height < shipHeight) super(speed, weight, bodyColor, width, height, blocksType, blocksNumber);
return false; if (entityShip != null)
pictureWidth = width; entityShip = new EntityBattleship(speed, weight, bodyColor, additionalColor, tower, section);
pictureHeight = height;
entityBattleship = new EntityBattleship();
entityBattleship.Init(speed, weight, bodyColor, additionalColor, turret, rocketLauncher);
drawingBlocks = new DrawingBlocks();
drawingBlocks.setNumber(blocksNumber);
return true;
}
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;
}
public void moveTransport(DirectionType direction) {
if (entityBattleship == null)
return;
switch (direction) {
//влево
case LEFT:
if (startPosX - entityBattleship.Step > 0) {
startPosX -= entityBattleship.Step;
}
break;
case UP:
if (startPosY - entityBattleship.Step > 0) {
startPosY -= entityBattleship.Step;
}
break;
case RIGHT:
if (startPosX + shipWidth + entityBattleship.Step < pictureWidth) {
startPosX += entityBattleship.Step;
}
break;
case DOWN:
if (startPosY + shipHeight + entityBattleship.Step < pictureHeight) {
startPosY += entityBattleship.Step;
}
break;
default:
break;
}
} }
public void drawTransport(Graphics2D g2d){ public void drawTransport(Graphics2D g2d){
if(entityBattleship == null) if (entityShip == null)
return; return;
BasicStroke pen = new BasicStroke(2);
g2d.setStroke(pen);
Color bodyColor = entityBattleship.BodyColor;
Color additionalColor = entityBattleship.AdditionalColor;
//основа
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);
//блоки super.drawTransport(g2d);
g2d.setColor(((EntityBattleship)entityShip).AdditionalColor);
g2d.setPaint(Color.DARK_GRAY); BasicStroke pen = new BasicStroke(2);
g2d.fillRect(startPosX + 70, startPosY + 15, 20, 40); g2d.setStroke(pen);
g2d.setPaint(Color.BLACK); //орудийная башня
g2d.drawRect(startPosX + 70, startPosY + 15, 20, 40); if (((EntityBattleship)entityShip).Tower) {
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);
}
//орудийная башня
if (entityBattleship.Tower) {
g2d.setColor(additionalColor);
g2d.fillRect(startPosX + 108, startPosY + 28, 15, 15); g2d.fillRect(startPosX + 108, startPosY + 28, 15, 15);
g2d.drawRect(startPosX + 108, startPosY + 28, 15, 15); g2d.drawRect(startPosX + 108, startPosY + 28, 15, 15);
// добавить черный цвет пушке // добавить черный цвет пушке
@ -115,16 +29,12 @@ public class DrawingBattleship {
g2d.drawRect(startPosX + 123, startPosY + 32, 55, 6); g2d.drawRect(startPosX + 123, startPosY + 32, 55, 6);
} }
//отсеки под ракеты //отсеки под ракеты
if (entityBattleship.Section) { if (((EntityBattleship)entityShip).Section) {
//добавить серый цвет
g2d.setColor(additionalColor);
g2d.fillRect(startPosX + 20, startPosY + 70, 40, 10); g2d.fillRect(startPosX + 20, startPosY + 70, 40, 10);
g2d.fillRect(startPosX + 75, startPosY + 70, 40, 10); g2d.fillRect(startPosX + 75, startPosY + 70, 40, 10);
g2d.setPaint(Color.BLACK); g2d.setPaint(Color.BLACK);
g2d.drawRect(startPosX + 20, startPosY + 70, 40, 10); g2d.drawRect(startPosX + 20, startPosY + 70, 40, 10);
g2d.drawRect(startPosX + 75, startPosY + 70, 40, 10); g2d.drawRect(startPosX + 75, startPosY + 70, 40, 10);
} }
} }
} }

View File

@ -1,6 +1,6 @@
import java.awt.*; import java.awt.*;
public class DrawingBlocks { public class DrawingBlocks implements IDrawBlocks{
private BlocksNumber number; private BlocksNumber number;
public void setNumber(int x){ public void setNumber(int x){
if(x <= 2) if(x <= 2)

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 + 50, _startY + 11, 8, 8);
graphics2D.fillOval(_startX + 50, _startY + 31, 8, 8);
if (number == BlocksNumber.FOUR || number == BlocksNumber.SIX) {
graphics2D.fillOval(_startX + 60, _startY + 11, 8, 8);
graphics2D.fillOval(_startX + 60, _startY + 31, 8, 8);
if (number == BlocksNumber.SIX) {
graphics2D.fillOval(_startX + 40, _startY + 11, 8, 8);
graphics2D.fillOval(_startX + 40, _startY + 31, 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 DrawingCrossBlocks();
// break;
// case 2:
// drawingBlocks = new DrawingRoundBlocks();
// 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

@ -1,19 +1,14 @@
import java.awt.*; import java.awt.*;
public class EntityBattleship { public class EntityBattleship extends EntityShip{
public int Speed;
public double Weight;
public Color BodyColor;
public Color AdditionalColor; public Color AdditionalColor;
public boolean Tower; public boolean Tower;
public boolean Section; public boolean Section;
public double Step = (double)Speed * 100 / Weight;
public void Init(int speed, double weight, Color bodyColor,Color public EntityBattleship(int speed, double weight, Color bodyColor, Color
additionalColor, boolean tower, boolean section){ additionalColor, boolean tower, boolean section)
Speed = speed; {
Weight = weight; super(speed, weight, bodyColor);
Step = (double)Speed * 100 / Weight;
BodyColor = bodyColor;
AdditionalColor = additionalColor; AdditionalColor = additionalColor;
Tower = tower; Tower = tower;
Section = section; 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;
}
}

View File

@ -1,3 +1,182 @@
//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.imageio.ImageIO;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
@ -7,24 +186,28 @@ import java.io.IOException;
import java.util.Random; import java.util.Random;
public class FrameBattleship extends JFrame { public class FrameBattleship extends JFrame {
private DrawingBattleship drawingBattleship; private DrawningShip drawningShip;
private JComponent pictureBox; private AbstractStrategy abstractStrategy;
private JComboBox<String> comboBoxStrategy;
private JComponent pictureBoxBattleship;
public FrameBattleship() throws IOException { public FrameBattleship() throws IOException {
super("Линкор"); super("Линкор");
setSize(new Dimension(900, 500)); setSize(new Dimension(900,500));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//components initialisation //components initialisation
pictureBox = new JComponent() { pictureBoxBattleship = new JComponent(){
public void paintComponent(Graphics graphics) { public void paintComponent(Graphics graphics){
super.paintComponent(graphics); super.paintComponent(graphics);
Graphics2D graphics2D = (Graphics2D) graphics; Graphics2D graphics2D = (Graphics2D) graphics;
if (drawingBattleship != null) drawingBattleship.drawTransport(graphics2D); if (drawningShip != null) drawningShip.drawTransport(graphics2D);
super.repaint(); super.repaint();
} }
}; };
pictureBox.setBounds(0, 0, getContentPane().getWidth(), getContentPane().getHeight()); pictureBoxBattleship.setBounds( 0, 0, getContentPane().getWidth(), getContentPane().getHeight());
JButton createButton = new JButton("Создать"); 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")))); 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)); 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")))); JButton leftButton = new JButton(new ImageIcon(ImageIO.read(new File("C:\\RPP intellij\\LabWork_01\\images\\left-arrow.png"))));
@ -32,9 +215,11 @@ public class FrameBattleship extends JFrame {
JButton upButton = new JButton(new ImageIcon(ImageIO.read(new File("C:\\RPP intellij\\LabWork_01\\images\\upper-arrow.png")))); 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)); 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")))); 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)); downButton.setPreferredSize(new Dimension(30,30));
//ActionListeners and ActionCommand addition //ActionListeners and ActionCommand addition
createButton.addActionListener(e -> buttonCreateClick()); createShipButton.addActionListener(e -> buttonCreateShipClick());
createBattleshipButton.addActionListener(e -> buttonCreateBattleshipClick());
stepButton.addActionListener(e -> buttonStepClick());
rightButton.setActionCommand("right"); rightButton.setActionCommand("right");
rightButton.addActionListener(this::buttonMoveClick); rightButton.addActionListener(this::buttonMoveClick);
leftButton.setActionCommand("left"); leftButton.setActionCommand("left");
@ -45,14 +230,19 @@ public class FrameBattleship extends JFrame {
downButton.addActionListener(this::buttonMoveClick); downButton.addActionListener(this::buttonMoveClick);
//panels and constraints initialisation //panels and constraints initialisation
JPanel panelBattleship = new JPanel(new BorderLayout()); JPanel panelBattleship = new JPanel(new BorderLayout());
JPanel createPanel = new JPanel(new BorderLayout());
createPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
JPanel movementPanel = new JPanel(new GridBagLayout());
JPanel rightPanel = 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(); GridBagConstraints constraints = new GridBagConstraints();
constraints.insets.left = constraints.insets.top = constraints.insets.bottom = constraints.insets.right = 2; constraints.insets.left = constraints.insets.top = constraints.insets.bottom = constraints.insets.right = 2;
//addition to createPanel //addition to createPanel
createPanel.add(createButton, BorderLayout.SOUTH); constraints.gridx = 0;
constraints.gridy = 0;
createPanel.add(createShipButton, constraints);
constraints.gridx = 1;
constraints.gridy = 0;
createPanel.add(createBattleshipButton, constraints);
//addition to movementPanel //addition to movementPanel
constraints.gridx = 2; constraints.gridx = 2;
constraints.gridy = 1; constraints.gridy = 1;
@ -66,53 +256,102 @@ public class FrameBattleship extends JFrame {
constraints.gridx = 1; constraints.gridx = 1;
constraints.gridy = 1; constraints.gridy = 1;
movementPanel.add(downButton, constraints); 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 //addition to frame
setLayout(new BorderLayout()); setLayout(new BorderLayout());
add(pictureBox); add(pictureBoxBattleship);
rightPanel.add(movementPanel, BorderLayout.SOUTH); rightPanel.add(movementPanel, BorderLayout.SOUTH);
rightPanel.add(stepPanel, BorderLayout.NORTH);
leftPanel.add(createPanel, BorderLayout.SOUTH);
panelBattleship.add(rightPanel, BorderLayout.EAST); panelBattleship.add(rightPanel, BorderLayout.EAST);
panelBattleship.add(createPanel, BorderLayout.WEST); panelBattleship.add(leftPanel, BorderLayout.WEST);
add(panelBattleship, BorderLayout.CENTER); add(panelBattleship,BorderLayout.CENTER);
setVisible(true); setVisible(true);
} }
private void buttonCreateBattleshipClick() {
private void buttonCreateClick() {
Random random = new Random(); Random random = new Random();
drawingBattleship = new DrawingBattleship(); pictureBoxBattleship.setBounds(0,0,getContentPane().getWidth(),getContentPane().getHeight());
pictureBox.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)),
drawingBattleship.Init(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);
new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)), random.nextBoolean(), random.nextBoolean(), pictureBox.getWidth(), pictureBox.getHeight(), (random.nextInt(3) + 1) * 2); drawningShip.SetPosition(random.nextInt(90) + 10, random.nextInt(90) + 10);
drawingBattleship.SetPosition(random.nextInt(90) + 10, random.nextInt(90) + 10);
draw(); 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) { private void buttonMoveClick(ActionEvent event) {
if (drawingBattleship == null || drawingBattleship.entityBattleship == null) if (drawningShip == null || drawningShip.getEntityShip() == null)
return; return;
switch (event.getActionCommand()) { switch (event.getActionCommand()) {
case "left": case "left":
drawingBattleship.moveTransport(DirectionType.LEFT); drawningShip.MoveTransport(DirectionType.LEFT);
break; break;
case "right": case "right":
drawingBattleship.moveTransport(DirectionType.RIGHT); drawningShip.MoveTransport(DirectionType.RIGHT);
break; break;
case "up": case "up":
drawingBattleship.moveTransport(DirectionType.UP); drawningShip.MoveTransport(DirectionType.UP);
break; break;
case "down": case "down":
drawingBattleship.moveTransport(DirectionType.DOWN); drawningShip.MoveTransport(DirectionType.DOWN);
break; break;
default: default:
break; break;
} }
draw(); draw();
} }
private void draw() { private void draw() {
if (drawingBattleship == null) { if (drawningShip == null)
{
return; return;
} }
pictureBox.repaint(); 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);
}

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
}