Compare commits

...

10 Commits

23 changed files with 959 additions and 0 deletions

3
.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

11
.idea/Catamarans.iml generated Normal file
View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

6
.idea/misc.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/Catamarans.iml" filepath="$PROJECT_DIR$/.idea/Catamarans.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

Binary file not shown.

After

Width:  |  Height:  |  Size: 244 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 249 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 254 B

BIN
Resources/30px_arrow_up.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 257 B

173
src/AbstractMap.java Normal file
View File

@ -0,0 +1,173 @@
package src;
import java.awt.*;
import java.util.Random;
public abstract class AbstractMap {
private IDrawingObject __drawingObject = null;
protected int[][] _map = null;
protected int _width;
protected int _height;
protected float _size_x;
protected float _size_y;
protected Random _random;
protected int _freeWater = 0;
protected int _barrier = 1;
protected Graphics graphics;
public void CreateMap(Graphics g, int width, int height, IDrawingObject drawingObject) {
graphics = g;
_width = width;
_height = height;
__drawingObject = drawingObject;
GenerateMap();
while (!SetObjectOnMap()) {
GenerateMap();
}
DrawMapWithObject();
}
/// <summary>
/// Функция для передвижения объекта по карте
/// </summary>
/// <param name="direction"></param>
/// <returns>Bitmap карты с объектом</returns>
public void MoveObject(EnumDirection enumDirection) {
// Проверка, что объект может переместится в требуемом направлении
// Получаем текщую позицию объекта
Position objectPosition = __drawingObject.GetCurrentPosition();
float currentX = objectPosition.Left;
float currentY = objectPosition.Top;
// В зависимости от направления уставналиваем dx, dy
float dx = 0;
float dy = 0;
// TODO дописать код
switch (enumDirection) {
case (EnumDirection.None):
break;
case (EnumDirection.Up): {
dy = -__drawingObject.Step();
}
break;
case (EnumDirection.Down): {
dy = __drawingObject.Step();
}
break;
case (EnumDirection.Left): {
dx = -__drawingObject.Step();
}
break;
case (EnumDirection.Right): {
dx = __drawingObject.Step();
}
break;
default:
break;
}
// ЕСли нет коллизии, то перемещаем объект
if (!CheckCollision(currentX + dx, currentY + dy)) {
__drawingObject.MoveObject(enumDirection);
}
DrawMapWithObject();
}
/// <summary>
/// Функция пытается поместить объект на карту
/// </summary>
/// <returns>Если удачно возвращает true, иначе - false</returns>
private boolean SetObjectOnMap() {
if (__drawingObject == null || _map == null) {
return false;
}
// Генерируем новые координаты объекта
int x = _random.nextInt(100, 200);
int y = _random.nextInt(100, 200);
__drawingObject.SetObject(x, y, _width, _height);
// Проверка, что объект не "накладывается" на закрытые участки
return !CheckCollision(x, y);
}
/// <summary>
/// Функция для проверки коллизии объекта с препятствиями на карте.
/// </summary>
/// <param name="x">Координата x объекта</param>
/// <param name="y">Координата y объекта</param>
/// <returns>Возвращает true если есть коллизия и false - если ее нет</returns>
protected boolean CheckCollision(float x, float y) {
// Получаем ширину и высоту отображаемого объекта
var objectPosition = __drawingObject.GetCurrentPosition();
float objectWidth = objectPosition.Right - objectPosition.Left;
float objectHeight = objectPosition.Bottom - objectPosition.Top;
// Теперь узнаем сколько клеток в ширину и высоту объект занимает на карте
int objectCellsCountX = (int) Math.ceil(objectWidth / _size_x);
int objectCellsCountY = (int) Math.ceil(objectHeight / _size_y);
// Получим координаты объекта в сетке карты
int objectMapX = (int) Math.floor((float) x / _size_x);
int objectMapY = (int) Math.floor((float) y / _size_y);
// В цикле проверяем все клетки карты на коллизию с объектом
int dy = 0;
int mapCellsX = _map[0].length;
int mapCellsY = _map.length;
int mapState = _freeWater;
while (objectMapY + dy < mapCellsY && dy <= objectCellsCountY) {
int dx = 0;
while (objectMapX + dx < mapCellsX && dx <= objectCellsCountX) {
mapState = _map[objectMapX + dx, objectMapY + dy];
if (mapState == _barrier) {
return true;
}
dx++;
}
dy++;
}
return false;
}
/// <summary>
/// Функция для отрисовки карты с объектом
/// </summary>
/// <returns></returns>
private void DrawMapWithObject() {
if (__drawingObject == null || _map == null) {
return;
}
for (int i = 0; i < _map.length; ++i) {
for (int j = 0; j < _map[0].length; ++j) {
if (_map[i][j] == _freeWater) {
DrawWaterPart(graphics, i, j);
} else if (_map[i][j] == _barrier) {
DrawBarrierPart(graphics, i, j);
}
}
}
__drawingObject.DrawingObject(graphics);
}
/// <summary>
/// Метод для генерации карты
/// </summary>
protected abstract void GenerateMap();
/// <summary>
/// Метод для отрисовки свободного участка на экране
/// </summary>
/// <param name="g"></param>
/// <param name="i"></param>
/// <param name="j"></param>
protected abstract void DrawWaterPart(Graphics g, int i, int j);
/// <summary>
/// Метод для отрисовки закрытого участка на экране
/// </summary>
/// <param name="g"></param>
/// <param name="i"></param>
/// <param name="j"></param>
protected abstract void DrawBarrierPart(Graphics g, int i, int j);
}

210
src/DrawingBoat.java Normal file
View File

@ -0,0 +1,210 @@
package src;
import java.awt.*;
import java.util.Random;
public class DrawingBoat {
// Объект-сущность лодки
public EntityBoat entityBoat;
// Объект отрисовки весел лодки
private DrawingBoatPaddle __drawingBoatPaddle;
// Координата X верхнего левого угла лодки
private float __startPosX;
// Координата Y верхнего левого угла лодки
private float __startPosY;
// Ширина отрисовки лодки
private int __boatWidth = 100;
// Высота отрисовки лодки
private int __boatHeight = 60;
// Ширина области отрисовки
private Integer __pictureWidth = null;
// Высота области отрисовки
private Integer __pictureHeight = null;
// Инициализатор класса
public DrawingBoat(int speed, float weight, Color bodyColor) {
entityBoat = new EntityBoat(speed, weight, bodyColor);
__drawingBoatPaddle = new DrawingBoatPaddle();
SetPaddlesCount();
}
// Инициализатор свойств
protected DrawingBoat(int speed, float weight, Color bodyColor, int boatWidth, int boatHeight) {
this(speed, weight, bodyColor);
__boatWidth = boatWidth;
__boatHeight = boatHeight;
}
// Метод для установки количества весел лодки
public void SetPaddlesCount() {
Random rnd = new Random();
int paddlesCount = rnd.nextInt(1, 4);
__drawingBoatPaddle.SetEnumNumber(paddlesCount);
}
// Метод установки позиции и размеров объекта
public void SetPosition(int x, int y, int width, int height) {
if (x > 0 && x < width - __boatWidth && y > 0 && y < height - __boatHeight) {
__startPosX = x;
__startPosY = y;
__pictureWidth = width;
__pictureHeight = height;
}
}
// Метод перемешения обхекта
public void MoveTransport(EnumDirection enumDirection) {
// Если не установлен объект-сущность - выходим
if (entityBoat == null) {
return;
}
// Если не назначены границы области отрисовки - выходим
if (__pictureWidth == null || __pictureHeight == null) {
return;
}
// Проверяем возможность перемещения и перемещаем обхект по заданному направлению
switch (enumDirection) {
case Right:
if (__startPosX + __boatWidth + entityBoat.Step() < __pictureWidth) {
__startPosX += entityBoat.Step();
}
break;
case Left:
if (__startPosX - entityBoat.Step() > 0) {
__startPosX -= entityBoat.Step();
}
break;
case Up:
if (__startPosY - entityBoat.Step() > 0) {
__startPosY -= entityBoat.Step();
}
break;
case Down:
if (__startPosY + __boatHeight + entityBoat.Step() < __pictureHeight) {
__startPosY += entityBoat.Step();
}
break;
}
}
// Метод отрисовки объекта
public void DrawTransport(Graphics g) {
// Если не установлен объект-сущность - выходим
if (entityBoat == null) {
return;
}
// Если координаты не валидны или размер области отрисовки не установлен - выходим
if (__startPosX < 0 || __startPosY < 0
|| __pictureHeight == null || __pictureWidth == null) {
return;
}
Graphics2D g2d = (Graphics2D) g;
int height = __boatHeight - 30;
// Промежуточные переменные, чтобы не писать каждый раз (int)
int startX = (int) __startPosX;
int startY = (int) __startPosY + 15;
// Рисуем корпус лодки
// Задаем цвет корпуса
g2d.setColor(entityBoat.BodyColor);
// Массив координат X для полигона корпуса лодки
int[] xPoints = new int[]{
startX,
startX + __boatWidth - __boatWidth / 4,
startX + __boatWidth,
startX + __boatWidth - __boatWidth / 4,
startX
};
// Массив координат Y для полигона корпуса лодки
int[] yPoints = new int[]{
startY,
startY,
startY + height / 2,
startY + height,
startY + height
};
// Заполняем полигон
g2d.fillPolygon(xPoints, yPoints, 5);
// Рисуем окантовку
g2d.setColor(Color.BLACK);
g2d.drawPolygon(xPoints, yPoints, 5);
// Рисуем палубу
// Левая дуга
g2d.drawArc(
startX + __boatWidth / 10,
startY + height / 5,
height - height / 5 - height / 5,
height - height / 5 - height / 5,
90, 180
);
// Правая дуга
g2d.drawArc(
startX + __boatWidth - __boatWidth / 4 - __boatWidth / 10 - height / 5,
startY + height / 5,
height - height / 5 - height / 5,
height - height / 5 - height / 5,
-90, 180
);
// Верхняя линия
g2d.drawLine(
startX + __boatWidth / 10 + (height - height / 2) / 2,
startY + height / 5,
startX + __boatWidth - __boatWidth / 4 - __boatWidth / 10 - height / 5 + (height - height / 2) / 2,
startY + height / 5
);
// Нижняя линия
g2d.drawLine(
startX + __boatWidth / 10 + (height - height / 2) / 2,
startY + height - height / 5,
startX + __boatWidth - __boatWidth / 4 - __boatWidth / 10 - height / 5 + (height - height / 2) / 2,
startY + height - height / 5
);
// Отрисовка весел лодки
__drawingBoatPaddle.DrawBoatPaddles(g, entityBoat.BodyColor, __startPosX, startY, __boatWidth, height);
}
// Метод изменения границ области отрисовки
public void ChangeBorders(int width, int height) {
__pictureWidth = width;
__pictureHeight = height;
// Если новые размеры области отрисовки меньше, чем размеры отрисовки лодки,
// то обнуляем размеры области отрисовки - рисовать не можем
if (__pictureWidth <= __boatWidth || __pictureHeight <= __boatHeight) {
__pictureWidth = null;
__pictureHeight = null;
return;
}
// Если выходим за правую границу, то сдвигаемся влево
if (__startPosX + __boatWidth > __pictureWidth) {
__startPosX = __pictureWidth - __boatWidth;
}
// Если выходим за нижнюю границу, то сдвигаемся вверх
if (__startPosY + __boatHeight > __pictureHeight) {
__startPosY = __pictureHeight - __boatHeight;
}
}
// Метод для получения текущих координат объекта
Position GetCurrentPosition() {
return new Position(__startPosX, __startPosY, __startPosX + __boatWidth, __startPosY + __boatHeight);
}
}

View File

@ -0,0 +1,49 @@
package src;
import java.awt.*;
public class DrawingBoatPaddle {
private EnumPaddlesCount __enumPaddlesCount;
private final BasicStroke __paddleStroke = new BasicStroke(3);
public void SetEnumNumber(int paddlesCount) {
for (EnumPaddlesCount val : __enumPaddlesCount.values()) {
if (val.enumNumber == paddlesCount) {
__enumPaddlesCount = val;
return;
}
}
}
public void DrawBoatPaddles(Graphics g, Color color,
float startPosX, float startPosY, int boatWidth, int boatHeight) {
int startX = (int) startPosX;
int startY = (int) startPosY;
Graphics2D g2d = (Graphics2D) g;
// Задаем цвет как у лодки
g2d.setColor(color);
// Задаем толщину линии побольше
g2d.setStroke(__paddleStroke);
// Промежуточная переменная, чтобы уменьшить расчеты
float t = boatWidth - (float) boatWidth / 4 - (float) boatWidth / 15;
for (int i = 0; i < __enumPaddlesCount.enumNumber; i++) {
// Рисуем верхнее весло
g2d.drawLine(
(int) (startX + t - t / 3 * i),
startY,
(int) (startX + t - t / 3 * (i + 1)),
startY - 15
);
// Рисуем нижнее весло
g2d.drawLine(
(int) (startX + t - t / 3 * i),
startY + boatHeight,
(int) (startX + t - t / 3 * (i + 1)),
startY + boatHeight + 15
);
}
}
}

23
src/DrawingCatamaran.java Normal file
View File

@ -0,0 +1,23 @@
package src;
import java.awt.*;
public class DrawingCatamaran extends DrawingBoat {
public DrawingCatamaran(int speed, float weight, Color bodyColor, Color dopColor, boolean bobbers, boolean sail) {
super(speed, weight, bodyColor, 110, 80);
entityBoat = new EntityCatamaran(speed, weight, bodyColor, dopColor, bobbers, sail);
}
@Override
public void DrawTransport(Graphics g) {
// Если объект-сущность не того класса - выходим
if (!(entityBoat instanceof EntityCatamaran)) {
return;
}
// Передаем управление отрисовкой родительскому классу
super.DrawTransport(g);
// TODO дописать отрисовку поплавков и паруса
}
}

View File

@ -0,0 +1,46 @@
package src;
import java.awt.*;
public class DrawingObjectBoat implements IDrawingObject {
private DrawingBoat __drawingBoat = null;
public DrawingObjectBoat(DrawingBoat drawingBoat) {
__drawingBoat = drawingBoat;
}
@Override
public Position GetCurrentPosition() {
if (__drawingBoat == null)
return null;
return __drawingBoat.GetCurrentPosition();
}
@Override
public void MoveObject(EnumDirection enumDirection) {
if (__drawingBoat == null)
return;
__drawingBoat.MoveTransport(enumDirection);
}
@Override
public float Step() {
if (__drawingBoat == null)
return 0;
if (__drawingBoat.entityBoat == null)
return 0;
return __drawingBoat.entityBoat.Step();
}
@Override
public void SetObject(int x, int y, int width, int height) {
__drawingBoat.SetPosition(x, y, width, height);
}
@Override
public void DrawingObject(Graphics g) {
if (__drawingBoat == null)
return;
__drawingBoat.DrawTransport(g);
}
}

25
src/EntityBoat.java Normal file
View File

@ -0,0 +1,25 @@
package src;
import java.awt.*;
import java.util.Random;
public class EntityBoat {
// Скорость лодки
public int Speed;
// Вес лодки
public float Weight;
// Цвет корпуса
public Color BodyColor;
// Шаг перемещения
public float Step() {
return Speed * 100 / Weight;
}
public EntityBoat(int speed, float weight, Color bodyColor) {
Random rnd = new Random();
Speed = speed <= 0 ? rnd.nextInt(50, 150) : speed;
Weight = weight <= 0 ? rnd.nextInt(40, 70) : weight;
BodyColor = bodyColor;
}
}

19
src/EntityCatamaran.java Normal file
View File

@ -0,0 +1,19 @@
package src;
import java.awt.*;
public class EntityCatamaran extends EntityBoat {
// Дополнительный цвет
public Color DopColor;
// Признак наличия поплавков
public boolean Bobbers;
// Признак наличия паруса
public boolean Sail;
public EntityCatamaran(int speed, float weight, Color bodyColor, Color dopColor, boolean bobbers, boolean sail) {
super(speed, weight, bodyColor);
DopColor = dopColor;
Bobbers = bobbers;
Sail = sail;
}
}

16
src/EnumDirection.java Normal file
View File

@ -0,0 +1,16 @@
package src;
// Перечисление для направлений движения лодки
public enum EnumDirection {
None(0),
Up(1),
Down(2),
Left(3),
Right(3);
public final int enumNumber;
EnumDirection(int i) {
this.enumNumber = i;
}
}

14
src/EnumPaddlesCount.java Normal file
View File

@ -0,0 +1,14 @@
package src;
// Дополнительное перечисление количества весел
public enum EnumPaddlesCount {
One(1),
Two(2),
Three(3);
public final int enumNumber;
EnumPaddlesCount(int i) {
this.enumNumber = i;
}
}

134
src/FormBoat.form Normal file
View File

@ -0,0 +1,134 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="src.FormBoat">
<grid id="27dc6" binding="PanelWrapper" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="500" height="400"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="5661e" binding="PictureBox" layout-manager="GridLayoutManager" row-count="4" column-count="5" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<opaque value="true"/>
</properties>
<border type="none"/>
<children>
<hspacer id="476ba">
<constraints>
<grid row="2" column="1" row-span="2" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
</hspacer>
<vspacer id="c6a0e">
<constraints>
<grid row="0" column="0" row-span="2" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<component id="9b1c5" class="javax.swing.JButton" binding="ButtonCreate">
<constraints>
<grid row="2" column="0" row-span="2" col-span="1" vsize-policy="0" hsize-policy="3" anchor="2" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="80" height="30"/>
</grid>
</constraints>
<properties>
<margin top="0" left="0" bottom="0" right="0"/>
<text value="Создать"/>
</properties>
</component>
<component id="bf14c" class="javax.swing.JButton" binding="ButtonDown">
<constraints>
<grid row="3" column="3" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<preferred-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="Resources/30px_arrow_down.png"/>
<label value=""/>
<text value=""/>
</properties>
</component>
<component id="cbcd1" class="javax.swing.JButton" binding="ButtonUp">
<constraints>
<grid row="2" column="3" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<preferred-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="Resources/30px_arrow_up.png"/>
<label value=""/>
<text value=""/>
</properties>
</component>
<component id="ce3f1" class="javax.swing.JButton" binding="ButtonLeft">
<constraints>
<grid row="3" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<preferred-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="Resources/30px_arrow_left.png"/>
<label value=""/>
<text value=""/>
</properties>
</component>
<component id="3b5cd" class="javax.swing.JButton" binding="ButtonRight">
<constraints>
<grid row="3" column="4" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<preferred-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<icon value="Resources/30px_arrow_right.png"/>
<label value=""/>
<text value=""/>
</properties>
</component>
</children>
</grid>
<toolbar id="6a652" binding="StatusStrip">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="-1" height="20"/>
</grid>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="81fb1" class="javax.swing.JLabel" binding="StatusStripLabelSpeed">
<constraints/>
<properties>
<foreground color="-16777216"/>
<text value="Скорость:"/>
</properties>
</component>
<component id="b564e" class="javax.swing.JLabel" binding="StatusStripLabelWeight">
<constraints/>
<properties>
<foreground color="-16777216"/>
<text value="Вес:"/>
</properties>
</component>
<component id="8492d" class="javax.swing.JLabel" binding="StatusStripLabelColor">
<constraints/>
<properties>
<foreground color="-16777216"/>
<text value="Цвет:"/>
</properties>
</component>
</children>
</toolbar>
</children>
</grid>
</form>

168
src/FormBoat.java Normal file
View File

@ -0,0 +1,168 @@
package src;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FormBoat {
protected DrawingBoat _drawingBoat;
JPanel PanelWrapper;
private JPanel PictureBox;
private JToolBar StatusStrip;
private JLabel StatusStripLabelSpeed;
private JLabel StatusStripLabelWeight;
private JLabel StatusStripLabelColor;
private JButton ButtonCreate;
private JButton ButtonDown;
private JButton ButtonUp;
private JButton ButtonLeft;
private JButton ButtonRight;
private List<JComponent> __controls;
// Конструктор формы
public FormBoat() {
// Инициализируем список элементов управления для их перерисовки
InitializeControlsRepaintList();
ButtonUp.setName("ButtonUp");
ButtonDown.setName("ButtonDown");
ButtonLeft.setName("ButtonLeft");
ButtonRight.setName("ButtonRight");
// Обработчик нажатия кнопки "Создать"
ButtonCreate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Создаем новый объект отрисовки лодки
Random random = new Random();
// Инициализируем обхект отрисовки
_drawingBoat = new DrawingBoat(
random.nextInt(100, 300),
random.nextInt(1000, 2000),
new Color(
random.nextInt(256),
random.nextInt(256),
random.nextInt(256)
)
);
// Устанавливаем позицию и размеры объекта отрисовки
_drawingBoat.SetPosition(random.nextInt(10, 100), random.nextInt(10, 100),
PictureBox.getWidth(), PictureBox.getHeight());
// Обновляем информацию в статусбаре
StatusStripLabelSpeed.setText("Скорость: " + _drawingBoat.entityBoat.Speed + " ");
StatusStripLabelWeight.setText("Вес: " + _drawingBoat.entityBoat.Weight + " ");
Color color = _drawingBoat.entityBoat.BodyColor;
StatusStripLabelColor.setText("Цвет: (" + color.getRed() + ", " + color.getGreen() + ", " + color.getBlue() + ")");
// Перерисовываем содержимое
Draw();
}
});
// Обработчик изменения размеров формы
PanelWrapper.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
super.componentResized(e);
// Если объект null - выходим
if (_drawingBoat == null) {
return;
}
// Изменяем граници области отрисовки для объекта отрисовки
_drawingBoat.ChangeBorders(PictureBox.getWidth(), PictureBox.getHeight());
// Перерисовываем содержимое
Draw();
}
});
ActionListener buttonMoveClickedListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Если объект null - выходим
if (_drawingBoat == null) {
return;
}
// Получаем имя кнопки перемещения
String buttonName = ((JButton) e.getSource()).getName();
// В зависимости от нажатой кнопки перемещаяем объект
switch (buttonName) {
case ("ButtonUp"): {
_drawingBoat.MoveTransport(EnumDirection.Up);
}
break;
case ("ButtonDown"): {
_drawingBoat.MoveTransport(EnumDirection.Down);
}
break;
case ("ButtonLeft"): {
_drawingBoat.MoveTransport(EnumDirection.Left);
}
break;
case ("ButtonRight"): {
_drawingBoat.MoveTransport(EnumDirection.Right);
}
break;
}
// Перерисовываем содержимое
Draw();
}
};
ButtonUp.addActionListener(buttonMoveClickedListener);
ButtonDown.addActionListener(buttonMoveClickedListener);
ButtonLeft.addActionListener(buttonMoveClickedListener);
ButtonRight.addActionListener(buttonMoveClickedListener);
}
// Метод отрисовки
public void Draw() {
// Если объект null - выходим
if (_drawingBoat == null) {
return;
}
// Закрашиваем PictureBox цветом окна (очищаем его)
Graphics g = PictureBox.getGraphics();
g.setColor(PictureBox.getBackground());
g.fillRect(0, 0, PictureBox.getWidth(), PictureBox.getHeight());
// Рисуем объект
_drawingBoat.DrawTransport(g);
// Перерисовываем элементы управления (PictureBox закрашивает их)
RepaintControls();
}
// Метод перерисовки элементов управления
private void RepaintControls() {
for (JComponent control : __controls) {
control.repaint();
}
}
// Метод инициализации списка элементов управления для их перерисовки
private void InitializeControlsRepaintList() {
__controls = new LinkedList<>();
__controls.add(ButtonCreate);
__controls.add(ButtonUp);
__controls.add(ButtonDown);
__controls.add(ButtonLeft);
__controls.add(ButtonRight);
}
}

16
src/IDrawingObject.java Normal file
View File

@ -0,0 +1,16 @@
package src;
import java.awt.*;
public interface IDrawingObject {
float Step();
void SetObject(int x, int y, int width, int height);
void MoveObject(EnumDirection enumDirection);
void DrawingObject(Graphics g);
Position GetCurrentPosition();
}

16
src/Position.java Normal file
View File

@ -0,0 +1,16 @@
package src;
// Класс для определения координат объекта
public class Position {
public float Left;
public float Top;
public float Right;
public float Bottom;
public Position(float left, float top, float right, float bottom) {
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
}

16
src/Program.java Normal file
View File

@ -0,0 +1,16 @@
package src;
import javax.swing.*;
public class Program {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(false);
JFrame frame = new JFrame("Катамаран");
frame.setContentPane(new FormBoat().PanelWrapper);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(500, 200);
frame.pack();
frame.setSize(1000, 500);
frame.setVisible(true);
}
}