Compare commits

..

No commits in common. "LabWork06" and "main" have entirely different histories.

37 changed files with 0 additions and 2535 deletions

29
Tank/.gitignore vendored
View File

@ -1,29 +0,0 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

View File

@ -1,8 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

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

View File

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

View File

@ -1,124 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

View File

@ -1,11 +0,0 @@
<?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$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -1,93 +0,0 @@
public abstract class AbstractStrategy {
// Перемещаемый объект
private IMoveableObject _moveableObject;
// Статус перемещения
private Status _state = Status.NotInit;
// Ширина поля
protected int FieldWidth;
// Высота поля
protected int FieldHeight;
// Статус перемещения
public Status GetStatus() {
return _state;
}
// Установка данных
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;
}
// Шаг перемещения
public void MakeStep() {
if (_state != Status.InProgress) {
return;
}
if (IsTargetDestination()) {
_state = Status.Finish;
return;
}
MoveToTarget();
}
// Перемещение влево
protected boolean MoveLeft() {
return MoveTo(Direction.Left);
}
// Перемещение вправо
protected boolean MoveRight() {
return MoveTo(Direction.Right);
}
// Перемещение вверх
protected boolean MoveUp() {
return MoveTo(Direction.Up);
}
// Перемещение вниз
protected boolean MoveDown() {
return MoveTo(Direction.Down);
}
// Параметры объекта
protected ObjectParameters GetObjectParameters() {
return _moveableObject.GetObjectPosition();
}
// Шаг объекта
protected int GetStep() {
if (_state != Status.InProgress) {
return 0;
}
return _moveableObject.GetStep();
}
// Перемещение к цели
protected abstract void MoveToTarget();
// Достигнута ли цель
protected abstract boolean IsTargetDestination();
// Попытка перемещения в требуемом направлении
private boolean MoveTo(Direction Direction) {
if (_state != Status.InProgress) {
return false;
}
if (_moveableObject.CheckCanMove(Direction)) {
_moveableObject.MoveObject(Direction);
return true;
}
return false;
}
}

View File

@ -1,13 +0,0 @@
public enum CountWheels {
Two(2),
Three(3),
Four(4),
Five(5);
private final int Value;
CountWheels(int Count){
Value = Count;
}
public int getCountWheels(){
return Value;
}
}

View File

@ -1,6 +0,0 @@
public enum Direction {
Up,
Left,
Down,
Right
}

View File

@ -1,42 +0,0 @@
import java.util.ArrayList;
import java.util.Random;
public class DoubleParametrized<T extends EntityArmoVehicle, U extends IOrnamentForm> {
ArrayList<T> Tanks;
ArrayList<U> Wheels;
public DoubleParametrized() {
Tanks = new ArrayList<>();
Wheels = new ArrayList<>();
}
public void Add(T tanks) {
Tanks.add(tanks);
}
public void Add(U wheels) {
Wheels.add(wheels);
}
public DrawingArmoVehicle GenerateTank(int pictureWidth, int pictureHeight) {
Random rand = new Random();
if(Tanks.isEmpty()) {
return null;
}
T tanks = Tanks.get(rand.nextInt(Tanks.size()));
U wheel = null;
if(!Wheels.isEmpty()){
wheel = Wheels.get(rand.nextInt(Wheels.size()));
}
DrawingArmoVehicle drawingArmoVehicle;
if (tanks instanceof EntityTank) {
drawingArmoVehicle = new DrawingTank((EntityTank) tanks, wheel, pictureWidth, pictureHeight);
} else {
drawingArmoVehicle = new DrawingArmoVehicle(tanks, wheel, pictureWidth, pictureHeight);
}
return drawingArmoVehicle;
}
}

View File

@ -1,132 +0,0 @@
import java.awt.*;
import java.util.Random;
public class DrawingArmoVehicle {
protected IOrnamentForm OrnamentsForm;
public EntityArmoVehicle ArmoVehicle;
protected int _pictureWidth;
protected int _pictureHeight;
protected int _startPosX;
protected int _startPosY;
protected int _TankWidth = 160;
protected int _TankHeight = 55;
public IMoveableObject GetMoveableObject() {
return new DrawingObjectTank(this);
}
public DrawingArmoVehicle(int speed, double weight, Color bodyColor, int _numWheel, int width, int height) {
_pictureWidth = width;
_pictureHeight = height;
if (_pictureHeight < _TankHeight || _pictureWidth < _TankWidth)
return;
ArmoVehicle = new EntityArmoVehicle(speed, weight, bodyColor, _numWheel);
Random random = new Random();
switch(random.nextInt(0, 3)) {
case 0:
OrnamentsForm = new DrawingWheelsCombination();
break;
case 1:
OrnamentsForm = new DrawingStarOrnament();
break;
case 2:
OrnamentsForm = new DrawingSuspensionOrnament();
break;
default:
OrnamentsForm = new DrawingWheelsCombination();
break;
}
OrnamentsForm.setDigit(_numWheel);
}
protected DrawingArmoVehicle(EntityArmoVehicle vehicle, IOrnamentForm ornamentsForm, int width, int height) {
if (height < _pictureHeight || width < _pictureWidth)
return;
_pictureWidth = width;
_pictureHeight = height;
ArmoVehicle = vehicle;
OrnamentsForm = ornamentsForm;
OrnamentsForm.setDigit(ArmoVehicle.numWheel);
}
public void SetPosition(int x, int y) {
_startPosX = Math.min(x, _pictureWidth - _TankWidth);
_startPosY = Math.min(y, _pictureHeight - _TankHeight);
}
public int GetPosX () {
return _startPosX;
}
public int GetPosY () {
return _startPosY;
}
public int GetWidth () {
return _TankWidth;
}
public int GetHeight () {
return _TankHeight;
}
public boolean CanMove(Direction direction) {
if (ArmoVehicle == null) {
return false;
}
switch (direction) {
case Left:
return _startPosX - ArmoVehicle.Step > 0;
case Right:
return _startPosX + _TankWidth + ArmoVehicle.Step < _pictureWidth;
case Up:
return _startPosY - ArmoVehicle.Step > 0;
case Down:
return _startPosY + _TankHeight + ArmoVehicle.Step < _pictureHeight;
default:
return false;
}
}
public void MoveTransport(Direction direction) {
if (!CanMove(direction) || ArmoVehicle == null) {
return;
}
switch (direction) {
//влево
case Left:
_startPosX -= (int)ArmoVehicle.Step;
break;
//вверх
case Up:
_startPosY -= (int)ArmoVehicle.Step;
break;
// вправо
case Right:
_startPosX += (int)ArmoVehicle.Step;
break;
//вниз
case Down:
_startPosY += (int)ArmoVehicle.Step;
break;
}
}
// Прорисовка объекта
public void DrawTransport(Graphics2D g) {
if (ArmoVehicle == null) {
return;
}
// body
g.setColor(ArmoVehicle.BodyColor);
int[] xPoints = {_startPosX + 5, _startPosX + 140, _startPosX + 130, _startPosX + 12};
int[] yPoints = {_startPosY + 30, _startPosY + 30, _startPosY + 42, _startPosY + 42};
int nPoints = xPoints.length;
g.drawPolygon(xPoints, yPoints, nPoints);
g.fillPolygon(xPoints, yPoints, nPoints);
//wheels
OrnamentsForm.Draw(g, _startPosX, _startPosY);
}
}

View File

@ -1,17 +0,0 @@
public class DrawingObjectTank implements IMoveableObject {
private DrawingArmoVehicle _drawingArmoVehicle = null;
public DrawingObjectTank(DrawingArmoVehicle drawingTank)
{
_drawingArmoVehicle = drawingTank;
}
public ObjectParameters GetObjectPosition() {
if (_drawingArmoVehicle == null || _drawingArmoVehicle.ArmoVehicle == null) {
return null;
}
return new ObjectParameters(_drawingArmoVehicle.GetPosX(),_drawingArmoVehicle.GetPosY(),
_drawingArmoVehicle.GetWidth(), _drawingArmoVehicle.GetHeight());
}
public int GetStep(){ return (int)_drawingArmoVehicle.ArmoVehicle.Step; }
public boolean CheckCanMove(Direction direction) { return _drawingArmoVehicle.CanMove(direction);}
public void MoveObject(Direction direction) { _drawingArmoVehicle.MoveTransport(direction); }
}

View File

@ -1,91 +0,0 @@
import java.awt.*;
public class DrawingStarOrnament implements IOrnamentForm {
private CountWheels wheels;
private Color StarColor;
public CountWheels getNumWheel() {
return wheels;
}
public void setDigit(int number) {
switch(number){
case 2:
wheels = CountWheels.Two;
break;
case 3:
wheels = CountWheels.Three;
break;
case 4:
wheels = CountWheels.Four;
break;
case 5:
wheels = CountWheels.Five;
break;
default:
wheels = CountWheels.Two;
break;
}
}
public void CaterpillarStar(Graphics g, int _startPosX, int _startPosY) {
StarColor = Color.RED;
g.setColor(StarColor);
int xPontsStar[] = {_startPosX + 15, _startPosX + 18, _startPosX + 21, _startPosX + 18, _startPosX + 19, _startPosX + 16, _startPosX + 12, _startPosX + 12, _startPosX + 11, _startPosX + 15, _startPosX + 16};
int yPontsStar[] = {_startPosY + 35, _startPosY + 38, _startPosY + 38, _startPosY + 42, _startPosY + 45, _startPosY + 42, _startPosY + 45, _startPosY + 41, _startPosY + 38, _startPosY + 38, _startPosY + 35};
g.drawPolygon(xPontsStar, yPontsStar, xPontsStar.length);
g.fillPolygon(xPontsStar, yPontsStar, xPontsStar.length);
}
public void DrawWheels(Graphics g, int _startPosX, int _startPosY){
g.setColor(Color.BLACK);
g.fillOval(10 + _startPosX, 42 + _startPosY, 20, 20);
}
public void Draw(Graphics g, int _startPosX, int _startPosY) {
DrawWheels(g,_startPosX, _startPosY);
CaterpillarStar(g,_startPosX + 5, _startPosY + 12);
if (wheels == CountWheels.Two){
DrawWheels(g,_startPosX, _startPosY);
DrawWheels(g,_startPosX + 100, _startPosY);
CaterpillarStar(g,_startPosX + 5, _startPosY + 12);
CaterpillarStar(g,_startPosX + 105, _startPosY + 12);
}
if (wheels == CountWheels.Three) {
DrawWheels(g,_startPosX, _startPosY);
DrawWheels(g,_startPosX + 50, _startPosY);
DrawWheels(g,_startPosX + 100, _startPosY);
CaterpillarStar(g,_startPosX + 5, _startPosY + 12);
CaterpillarStar(g,_startPosX + 55, _startPosY + 12);
CaterpillarStar(g,_startPosX + 105, _startPosY + 12);
}
if (wheels == CountWheels.Four) {
DrawWheels(g,_startPosX, _startPosY);
DrawWheels(g,_startPosX + 25, _startPosY);
DrawWheels(g,_startPosX + 50, _startPosY);
DrawWheels(g,_startPosX + 100, _startPosY);
CaterpillarStar(g,_startPosX + 5, _startPosY + 12);
CaterpillarStar(g,_startPosX + 30, _startPosY + 12);
CaterpillarStar(g,_startPosX + 55, _startPosY + 12);
CaterpillarStar(g,_startPosX + 105, _startPosY + 12);
}
if(wheels == CountWheels.Five) {
DrawWheels(g,_startPosX, _startPosY);
DrawWheels(g,_startPosX + 25, _startPosY);
DrawWheels(g,_startPosX + 50, _startPosY);
DrawWheels(g,_startPosX + 75, _startPosY);
DrawWheels(g,_startPosX + 100, _startPosY);
CaterpillarStar(g,_startPosX + 5, _startPosY + 12);
CaterpillarStar(g,_startPosX + 30, _startPosY + 12);
CaterpillarStar(g,_startPosX + 55, _startPosY + 12);
CaterpillarStar(g,_startPosX + 80, _startPosY + 12);
CaterpillarStar(g,_startPosX + 105, _startPosY + 12);
}
}
}

View File

@ -1,76 +0,0 @@
import java.awt.*;
public class DrawingSuspensionOrnament implements IOrnamentForm {
private CountWheels wheels;
private Color SuspensionColor;
public CountWheels getNumWheel() {
return wheels;
}
public void setDigit(int number) {
switch(number){
case 2:
wheels = CountWheels.Two;
break;
case 3:
wheels = CountWheels.Three;
break;
case 4:
wheels = CountWheels.Four;
break;
case 5:
wheels = CountWheels.Five;
break;
default:
wheels = CountWheels.Two;
break;
}
}
public void DrawWheels(Graphics g, int _startPosX, int _startPosY) {
g.setColor(Color.BLACK);
g.fillOval(10 + _startPosX, 42 + _startPosY, 20, 20);
}
public void DrawSuspension(Graphics g, int _startPosX, int _startPosY) {
SuspensionColor = Color.BLUE;
g.setColor(SuspensionColor);
g.fillRect(_startPosX + 27, _startPosY + 50, 10, 3);
}
public void Draw(Graphics g, int _startPosX, int _startPosY) {
DrawWheels(g,_startPosX, _startPosY);
DrawSuspension(g, _startPosX, _startPosY);
if (wheels == CountWheels.Two) {
DrawWheels(g,_startPosX, _startPosY);
DrawWheels(g,_startPosX + 100, _startPosY);
DrawSuspension(g, _startPosX, _startPosY);
DrawSuspension(g,_startPosX + 73, _startPosY);
}
if (wheels == CountWheels.Three) {
DrawWheels(g,_startPosX, _startPosY);
DrawWheels(g,_startPosX + 50, _startPosY);
DrawWheels(g,_startPosX + 100, _startPosY);
DrawSuspension(g, _startPosX, _startPosY);
DrawSuspension(g,_startPosX + 24, _startPosY);
DrawSuspension(g,_startPosX + 73, _startPosY);
}
if (wheels == CountWheels.Four || wheels == CountWheels.Five) {
DrawWheels(g,_startPosX, _startPosY);
DrawWheels(g,_startPosX + 25, _startPosY);
DrawWheels(g,_startPosX + 50, _startPosY);
DrawWheels(g,_startPosX + 75, _startPosY);
DrawWheels(g,_startPosX + 100, _startPosY);
DrawSuspension(g, _startPosX, _startPosY);
DrawSuspension(g,_startPosX + 24, _startPosY);
DrawSuspension(g,_startPosX + 53, _startPosY);
DrawSuspension(g,_startPosX + 73, _startPosY);
}
}
}

View File

@ -1,76 +0,0 @@
import java.awt.*;
public class DrawingTank extends DrawingArmoVehicle {
protected IOrnamentForm OrnamentsForm;
private boolean OrnamentAdd;
// Конструктор (Инициализация характеристик)
public DrawingTank(int speed, double weight, Color bodyColor, int _numWheel, Color additionalColor, boolean bodyKit, boolean caterpillar, boolean tower, int width, int height, boolean ornamentAdd) {
super(speed, weight, bodyColor, _numWheel, width, height);
ArmoVehicle = new EntityTank(speed, weight, bodyColor, _numWheel, additionalColor, bodyKit, caterpillar, tower);
_TankWidth = ((EntityTank)ArmoVehicle).BodyKit ? 169 : 83;
this.OrnamentAdd = ornamentAdd;
}
// Ещё один конструктор
public DrawingTank(int speed, float weight, Color bodyColor, int _numWheel, Color additionalColor, boolean bodyKit, boolean caterpillar, boolean tower, int width, int height) {
super(speed, weight, bodyColor, _numWheel, width, height);
ArmoVehicle=new EntityTank(speed,weight,bodyColor,_numWheel, additionalColor,bodyKit,caterpillar, tower);
}
public DrawingTank(EntityTank armoVehicle, IOrnamentForm _wheelDrawing, int width, int height) {
super(armoVehicle, _wheelDrawing, width, height);
if (height < _pictureHeight || width < _pictureWidth)
return;
ArmoVehicle = armoVehicle;
}
// Установка позиции
public void SetPosition(int x, int y) {
_startPosX = Math.min(x, _pictureWidth-_TankWidth);
_startPosY = Math.min(y, _pictureHeight-_TankHeight);
}
private boolean setOrnamentAdd() {
return OrnamentAdd;
}
// Прорисовка объекта
public void DrawTransport(Graphics2D g) {
if (ArmoVehicle == null) {
return;
}
super.DrawTransport(g);
g.setColor(((EntityTank) ArmoVehicle).AdditionalColor);
if (((EntityTank) ArmoVehicle).BodyKit) {
int[] xPointsBody = {_startPosX + 52, _startPosX + 52, _startPosX + 40, _startPosX + 15, _startPosX + 15, _startPosX + 60, _startPosX + 90, _startPosX + 120, _startPosX + 100, _startPosX + 95, _startPosX + 90};
int[] yPointsBody = {_startPosY + 30, _startPosY + 27, _startPosY + 23, _startPosY + 18, _startPosY + 15, _startPosY + 11, _startPosY + 11, _startPosY + 20, _startPosY + 25, _startPosY + 27, _startPosY + 30};
int nPointsBody = 11;
g.drawPolygon(xPointsBody, yPointsBody, nPointsBody);
g.fillPolygon(xPointsBody, yPointsBody, nPointsBody);
}
if (((EntityTank) ArmoVehicle).Caterpillar) {
// Гусеница
g.drawOval(_startPosX + 10, _startPosY + 30, 120, 30);
}
if (((EntityTank) ArmoVehicle).Tower) {
// Орудие
g.drawRect(_startPosX + 112, _startPosY + 17, 60, 4);
g.fillRect(_startPosX + 112, _startPosY + 17, 60, 4);
// Зенитное орудие
int[] xPointsGun = {_startPosX + 45, _startPosX + 45, _startPosX + 41, _startPosX + 41, _startPosX + 42, _startPosX + 41, _startPosX + 44, _startPosX + 50, _startPosX + 52, _startPosX + 53, _startPosX + 58};
int[] yPointsGun = {_startPosY + 12, _startPosY + 10, _startPosY + 8, _startPosY + 7, _startPosY + 5, _startPosY + 4, _startPosY + 3, _startPosY + 3, _startPosY + 5, _startPosY + 7, _startPosY + 10};
int nPointsGun = 11;
g.fillRect(_startPosX + 50, _startPosY + 5, 20, 2);
g.drawPolygon(xPointsGun, yPointsGun, nPointsGun);
g.fillPolygon(xPointsGun, yPointsGun, nPointsGun);
}
}
}

View File

@ -1,116 +0,0 @@
import java.awt.*;
public class DrawingWheelsCombination implements IOrnamentForm {
private CountWheels wheels;
private Color CombinationColor;
public CountWheels getNumWheel() {
return wheels;
}
public void setDigit(int number) {
switch(number) {
case 2:
wheels = CountWheels.Two;
break;
case 3:
wheels = CountWheels.Three;
break;
case 4:
wheels = CountWheels.Four;
break;
case 5:
wheels = CountWheels.Five;
break;
default:
wheels = CountWheels.Two;
break;
}
}
public void CaterpillarStar(Graphics g, int _startPosX, int _startPosY) {
CombinationColor = Color.RED;
g.setColor(CombinationColor);
int xPontsStar[] = {_startPosX + 15, _startPosX + 18, _startPosX + 21, _startPosX + 18, _startPosX + 19, _startPosX + 16, _startPosX + 12, _startPosX + 13, _startPosX + 12, _startPosX + 15, _startPosX + 16};
int yPontsStar[] = {_startPosY + 35, _startPosY + 38, _startPosY + 38, _startPosY + 42, _startPosY + 45, _startPosY + 42, _startPosY + 45, _startPosY + 41, _startPosY + 38, _startPosY + 38, _startPosY + 35};
g.drawPolygon(xPontsStar, yPontsStar, xPontsStar.length);
g.fillPolygon(xPontsStar, yPontsStar, xPontsStar.length);
}
public void DrawSuspension(Graphics g, int _startPosX, int _startPosY) {
CombinationColor = Color.BLUE;
g.setColor(CombinationColor);
g.fillRect(_startPosX + 27, _startPosY + 50, 10, 3);
}
public void DrawWheels(Graphics g, int _startPosX, int _startPosY){
g.setColor(Color.BLACK);
g.fillOval(10 + _startPosX, 42 + _startPosY, 20, 20);
}
public void Draw(Graphics g, int _startPosX, int _startPosY) {
DrawWheels(g,_startPosX, _startPosY);
DrawSuspension(g, _startPosX, _startPosY);
CaterpillarStar(g,_startPosX + 5, _startPosY + 12);
if (wheels == CountWheels.Two){
DrawWheels(g,_startPosX, _startPosY);
DrawWheels(g,_startPosX + 100, _startPosY);
DrawSuspension(g, _startPosX, _startPosY);
DrawSuspension(g,_startPosX + 73, _startPosY);
CaterpillarStar(g,_startPosX + 5, _startPosY + 12);
CaterpillarStar(g,_startPosX + 105, _startPosY + 12);
}
if (wheels == CountWheels.Three) {
DrawWheels(g,_startPosX, _startPosY);
DrawWheels(g,_startPosX + 50, _startPosY);
DrawWheels(g,_startPosX + 100, _startPosY);
DrawSuspension(g, _startPosX, _startPosY);
DrawSuspension(g,_startPosX + 24, _startPosY);
DrawSuspension(g,_startPosX + 73, _startPosY);
CaterpillarStar(g,_startPosX + 5, _startPosY + 12);
CaterpillarStar(g,_startPosX + 55, _startPosY + 12);
CaterpillarStar(g,_startPosX + 105, _startPosY + 12);
}
if (wheels == CountWheels.Four) {
DrawWheels(g,_startPosX, _startPosY);
DrawWheels(g,_startPosX + 25, _startPosY);
DrawWheels(g,_startPosX + 50, _startPosY);
DrawWheels(g,_startPosX + 100, _startPosY);
DrawSuspension(g, _startPosX, _startPosY);
DrawSuspension(g,_startPosX + 24, _startPosY);
DrawSuspension(g,_startPosX + 53, _startPosY);
DrawSuspension(g,_startPosX + 73, _startPosY);
CaterpillarStar(g,_startPosX + 5, _startPosY + 12);
CaterpillarStar(g,_startPosX + 30, _startPosY + 12);
CaterpillarStar(g,_startPosX + 55, _startPosY + 12);
CaterpillarStar(g,_startPosX + 105, _startPosY + 12);
}
if(wheels == CountWheels.Five) {
DrawWheels(g,_startPosX, _startPosY);
DrawWheels(g,_startPosX + 25, _startPosY);
DrawWheels(g,_startPosX + 50, _startPosY);
DrawWheels(g,_startPosX + 75, _startPosY);
DrawWheels(g,_startPosX + 100, _startPosY);
DrawSuspension(g, _startPosX, _startPosY);
DrawSuspension(g,_startPosX + 24, _startPosY);
DrawSuspension(g,_startPosX + 53, _startPosY);
DrawSuspension(g,_startPosX + 73, _startPosY);
CaterpillarStar(g,_startPosX + 5, _startPosY + 12);
CaterpillarStar(g,_startPosX + 30, _startPosY + 12);
CaterpillarStar(g,_startPosX + 55, _startPosY + 12);
CaterpillarStar(g,_startPosX + 80, _startPosY + 12);
CaterpillarStar(g,_startPosX + 105, _startPosY + 12);
}
}
}

View File

@ -1,21 +0,0 @@
import java.awt.*;
public class EntityArmoVehicle {
public int Speed;
public double Weight;
public double getWeight() {
return Weight;
}
public Color BodyColor;
public void setBodyColor(Color color) { BodyColor = color; }
public double Step;
public int numWheel;
public EntityArmoVehicle(int speed, double weight, Color bodyColor, int _numWheel) {
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
numWheel = _numWheel;
Step = (double) Speed * 200 / Weight;
}
}

View File

@ -1,17 +0,0 @@
import java.awt.*;
public class EntityTank extends EntityArmoVehicle {
public Color AdditionalColor;
public void setAdditionalColor(Color color) { AdditionalColor = color; }
public boolean BodyKit;
public boolean Caterpillar;
public boolean Tower;
public EntityTank(int speed, double weight, Color bodyColor, int _numWheel, Color additionalColor, boolean bodyKit, boolean caterpillar, boolean tower) {
super(speed, weight, bodyColor, _numWheel);
AdditionalColor = additionalColor;
BodyKit = bodyKit;
Caterpillar = caterpillar;
Tower = tower;
}
}

View File

@ -1,77 +0,0 @@
import java.awt.Color;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Vector;
public class ExtentionDrawingTank {
// Создание объекта из строки
public static DrawingArmoVehicle CreateDrawingTank(String info, String separatorForObject, int width, int height) {
String[] strs = info.split(separatorForObject);
if (strs.length == 5)
{
String[] colorValues = strs[2].split(",");
DrawingArmoVehicle drawingVehicle = new DrawingArmoVehicle(Integer.parseInt(strs[0]), (double)Integer.parseInt(strs[1]),
new Color(Integer.parseInt(colorValues[0].replaceAll("\\D", "")),
Integer.parseInt(colorValues[1].replaceAll("\\D", "")),
Integer.parseInt(colorValues[2].replaceAll("\\D", ""))),
Integer.parseInt(strs[3]),
width, height
);
try{
drawingVehicle.OrnamentsForm = (IOrnamentForm) Class.forName(strs[4]).getDeclaredConstructor().newInstance();
drawingVehicle.OrnamentsForm.setDigit(drawingVehicle.ArmoVehicle.numWheel);
} catch (Exception e) {
return null;
}
return drawingVehicle;
}
if(strs.length == 9) {
String[] colorValues = strs[2].split(",");
String[] colorValues2 = strs[5].split(",");
DrawingTank drawingTank = new DrawingTank(
Integer.parseInt(strs[0]),
(float)Integer.parseInt(strs[1]),
new Color(
Integer.parseInt(colorValues[0].replaceAll("\\D", "")),
Integer.parseInt(colorValues[1].replaceAll("\\D", "")),
Integer.parseInt(colorValues[2].replaceAll("\\D", ""))
),
Integer.parseInt(strs[3]),
new Color(
Integer.parseInt(colorValues2[0].replaceAll("\\D", "")),
Integer.parseInt(colorValues2[1].replaceAll("\\D", "")),
Integer.parseInt(colorValues2[2].replaceAll("\\D", ""))
),
strs[6].equals("true"),
strs[7].equals("true"),
strs[8].equals("true"),
width, height
);
try {
drawingTank.OrnamentsForm = (IOrnamentForm)Class.forName(strs[4]).getDeclaredConstructor().newInstance();
drawingTank.OrnamentsForm.setDigit(drawingTank.ArmoVehicle.numWheel);
} catch (Exception e) {
return null;
}
return drawingTank;
}
return null;
}
// Получение данных для сохранения в файл
public static String GetDataForSave(DrawingArmoVehicle drawingArmoVehicle, String separatorForObject) {
EntityArmoVehicle vehicle = drawingArmoVehicle.ArmoVehicle;
if (vehicle == null) {
return null;
}
String str = "" + vehicle.Speed + separatorForObject + (int)vehicle.Weight + separatorForObject + vehicle.BodyColor + separatorForObject + vehicle.numWheel + separatorForObject + drawingArmoVehicle.OrnamentsForm.getClass().getName();
if (!(vehicle instanceof EntityTank)) {
return str;
}
return str+separatorForObject+((EntityTank)vehicle).AdditionalColor.toString()+separatorForObject+((EntityTank)vehicle).BodyKit+separatorForObject+((EntityTank)vehicle).Caterpillar+separatorForObject+((EntityTank)vehicle).Tower;
}
}

View File

@ -1,221 +0,0 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class FormTank {
private class Canvas extends JComponent {
public Canvas() {
}
public void paintComponent(Graphics g) {
if (_drawingVehicle == null) {
return;
}
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
_drawingVehicle.DrawTransport(g2d);
super.repaint();
}
}
public DrawingArmoVehicle SelectedVehicle;
public boolean DialogResult = false;
public DrawingArmoVehicle _drawingVehicle;
private AbstractStrategy abstractStrategy;
Canvas canv;
static int pictureBoxWidth = 980;
static int pictureBoxHeight = 560;
public JButton buttonSelectTank;
public JFrame Frame;
public void Draw() {
canv.repaint();
}
public FormTank() {
SelectedVehicle = null;
Frame = new JFrame("Tank");
JButton buttonCreateArmoVehicle = new JButton("Добавить бронетехнику");
JButton buttonCreateTank = new JButton("Добавить танк");
JButton buttonStrategysStep = new JButton("Шаг");
buttonSelectTank = new JButton("Добавить");
JComboBox<String> ComboBoxStrategy = new JComboBox<String>(
new String[]{
"к центру",
"к краю",
});
JButton up = new JButton();
up.setName("up");
ImageIcon iconUp = new ImageIcon("Resources//KeyUp.png");
up.setIcon(iconUp);
JButton down = new JButton();
down.setName("down");
ImageIcon iconDown = new ImageIcon("Resources//KeyDown.png");
down.setIcon(iconDown);
JButton left = new JButton();
left.setName("left");
ImageIcon iconLeft = new ImageIcon("Resources//KeyLeft.png");
left.setIcon(iconLeft);
JButton right = new JButton();
right.setName("right");
ImageIcon iconRight = new ImageIcon("Resources//KeyRight.png");
right.setIcon(iconRight);
buttonStrategysStep.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (_drawingVehicle == 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 DrawingObjectTank(_drawingVehicle), pictureBoxWidth, pictureBoxHeight);
ComboBoxStrategy.setEnabled(false);
}
if (abstractStrategy == null) {
return;
}
abstractStrategy.MakeStep();
Draw();
if (abstractStrategy.GetStatus() == Status.Finish) {
ComboBoxStrategy.setEnabled(true);
abstractStrategy = null;
}
}
}
);
buttonCreateTank.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
Random random = new Random();
Color color = new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256));
// Вызываем диалоговое окно выбора цвета
Color selectedColor = JColorChooser.showDialog(Frame, "Выберите цвет", Color.WHITE);
if (selectedColor != null) {
color = selectedColor;
}
Color coloradditional = new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256));
// Вызываем диалоговое окно выбора цвета
selectedColor = JColorChooser.showDialog(Frame, "Выберите цвет", Color.WHITE);
if (selectedColor != null) {
coloradditional = selectedColor;
}
_drawingVehicle = new DrawingTank(
random.nextInt(100, 300),
random.nextInt(1000, 3000),
color,
random.nextInt(2, 5),
coloradditional,
true,
true,
true,
pictureBoxWidth,
pictureBoxHeight,
true
);
_drawingVehicle.SetPosition(random.nextInt(10, 100), random.nextInt(10, 100));
Draw();
}
}
);
buttonCreateArmoVehicle.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
Random random = new Random();
Color color = new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256));
// Вызываем диалоговое окно выбора цвета
Color selectedColor = JColorChooser.showDialog(Frame, "Выберите цвет", Color.WHITE);
if (selectedColor != null) {
color = selectedColor;
}
_drawingVehicle = new DrawingArmoVehicle(
random.nextInt(100, 300),
random.nextInt(1000, 3000),
color,
random.nextInt(2, 5),
pictureBoxWidth,
pictureBoxHeight
);
_drawingVehicle.SetPosition(random.nextInt(10, 100), random.nextInt(10, 100));
Draw();
}
}
);
ActionListener actioListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (_drawingVehicle == null) {
return;
}
switch (((JButton) (e.getSource())).getName()) {
case "up":
_drawingVehicle.MoveTransport(Direction.Up);
break;
case "down":
_drawingVehicle.MoveTransport(Direction.Down);
break;
case "left":
_drawingVehicle.MoveTransport(Direction.Left);
break;
case "right":
_drawingVehicle.MoveTransport(Direction.Right);
break;
}
Draw();
}
};
up.addActionListener(actioListener);
down.addActionListener(actioListener);
left.addActionListener(actioListener);
right.addActionListener(actioListener);
Frame.setSize(1000, 620);
Frame.setLayout(null);
canv = new Canvas();
canv.setBounds(0, 0, pictureBoxWidth, pictureBoxHeight);
buttonCreateArmoVehicle.setBounds(2, 520, 180, 40);
buttonCreateTank.setBounds(185, 520, 150, 40);
up.setBounds(900, 480, 40, 40);
down.setBounds(900, 520, 40, 40);
left.setBounds(860, 520, 40, 40);
right.setBounds(940, 520, 40, 40);
ComboBoxStrategy.setBounds(pictureBoxWidth - 150, 20, 150, 20);
buttonStrategysStep.setBounds(pictureBoxWidth - 150, 45, 150, 20);
buttonSelectTank.setBounds(pictureBoxWidth / 2, 530, 150, 30);
Frame.add(buttonSelectTank);
Frame.add(canv);
Frame.add(buttonCreateArmoVehicle);
Frame.add(buttonCreateTank);
Frame.add(up);
Frame.add(down);
Frame.add(left);
Frame.add(right);
Frame.add(ComboBoxStrategy);
Frame.add(buttonStrategysStep);
Frame.setVisible(true);
}
}

View File

@ -1,365 +0,0 @@
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.util.LinkedList;
import java.util.Queue;
public class FormTankCollection {
private class Canvas extends JComponent {
public Canvas() {
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (jListStorage.getSelectedIndex() == -1) {
return;
}
var obj = _storage.get(jListStorage.getSelectedValue());
if (obj == null) {
return;
}
if (obj.ShowTanks() != null) {
g.drawImage(obj.ShowTanks(), 0, 0, this);
}
super.repaint();
}
}
Canvas canv;
static int pictureBoxWidth = 700;
static int pictureBoxHeight = 480;
private TanksGenericStorage _storage;
public void Draw() {
canv.repaint();
}
private Queue<DrawingArmoVehicle> Queue;
private JList<String> jListStorage;
private DefaultListModel<String> listModel;
private void ReloadObjects() {
int index = jListStorage.getSelectedIndex();
listModel.clear();
for (String key : _storage.Keys()) {
listModel.addElement(key);
}
if (listModel.size() > 0 && (index == -1 || index >= listModel.size())) {
jListStorage.setSelectedIndex(0);
} else if (listModel.size() > 0 && index > -1 && index < listModel.size()) {
jListStorage.setSelectedIndex(index);
}
}
FormTankCollection() {
listModel = new DefaultListModel<String>();
jListStorage = new JList<String>(listModel);
canv = new Canvas();
JFrame Frame = new JFrame("TankCollecltion");
_storage = new TanksGenericStorage(pictureBoxWidth, pictureBoxHeight);
JButton ButtonAddVehicle = new JButton("Добавить технику");
ButtonAddVehicle.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jListStorage.getSelectedIndex() == -1) {
return;
}
var obj = _storage.get(jListStorage.getSelectedValue());
if (obj == null) {
return;
}
FormTankConfig form = new FormTankConfig();
form.buttonAdd.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (obj != null && obj.Add(form._vehicle) != -1) {
JOptionPane.showMessageDialog(null, "Объект добавлен", "Информация", JOptionPane.INFORMATION_MESSAGE);
Draw();
} else {
JOptionPane.showMessageDialog(null, "Не удалось добавить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
}
form.Frame.dispose();
}
}
);
}
}
);
Queue = new LinkedList<DrawingArmoVehicle>();
JTextField TextBoxNumber = new JTextField();
JButton ButtonRemoveTank = new JButton("Удалить технику");
ButtonRemoveTank.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jListStorage.getSelectedIndex() == -1) {
return;
}
var obj = _storage.get(jListStorage.getSelectedValue());
if (obj == null) {
return;
}
if (JOptionPane.showConfirmDialog(null, "Удалить объект?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
return;
}
for (char it : TextBoxNumber.getText().toCharArray())
if (it < '0' || it > '9') {
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (TextBoxNumber.getText().length() == 0) {
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
int pos = Integer.parseInt(TextBoxNumber.getText());
var removed = obj.remove(pos);
if (removed != null) {
Queue.add(removed);
JOptionPane.showMessageDialog(null, "Объект удален", "Информация", JOptionPane.INFORMATION_MESSAGE);
Draw();
} else {
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
}
}
}
);
JButton buttonGetRemoved = new JButton("Извлечь");
buttonGetRemoved.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Queue.size() == 0) {
JOptionPane.showMessageDialog(null, "Нет удалённых", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
FormTank form = new FormTank();
form._drawingVehicle = Queue.peek();
Queue.remove();
form.Draw();
}
}
);
JButton ButtonRefreshCollection = new JButton("Обновить коллекцию");
ButtonRefreshCollection.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
Draw();
}
}
);
JButton toFormTankGenerate = new JButton("Генерировать технику");
toFormTankGenerate.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
FormTankGenerate formTankGenerate = new FormTankGenerate();
}
}
);
JTextField textBoxSetName = new JTextField();
JButton buttonAddSet = new JButton("Добавить набор");
buttonAddSet.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (textBoxSetName.getText().length() == 0) {
JOptionPane.showMessageDialog(null, "Не все данные заполнены", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
_storage.AddSet(textBoxSetName.getText());
ReloadObjects();
}
}
);
jListStorage.addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
Draw();
}
}
);
JButton buttonRemoveSet = new JButton("Удалить набор");
buttonRemoveSet.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (jListStorage.getSelectedIndex() == -1) {
return;
}
if (JOptionPane.showConfirmDialog(null, "Удалить объект " + jListStorage.getSelectedValue() + "?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
return;
}
_storage.DelSet(jListStorage.getSelectedValue());
ReloadObjects();
}
}
);
// Создаём панель меню
JMenuBar menuBar = new JMenuBar();
// Создаём пункты меню
JMenu fileMenu = new JMenu("File");
// Создаём пункты меню
JMenuItem openItem = new JMenuItem("Открыть");
openItem.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Выберите файл для загрузки данных");
// Установка фильтра для файлов с определённым расширеним (например, txt)
fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt"));
fileChooser.setDialogTitle("Выберите файл для загрузки данных");
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (_storage.LoadData(selectedFile.getAbsolutePath())) {
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Не загрузилось", "Результат", JOptionPane.ERROR_MESSAGE);
}
}
ReloadObjects();
}
});
JMenuItem saveItem = new JMenuItem("Сохранить");
saveItem.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Выберите файл для сохранения данных");
// Установка фильтра для файлов с определённым расширением (например, txt)
fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt"));
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if(_storage.SaveData(selectedFile.getAbsolutePath()))
JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат", JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(null, "Не сохранилось", "Результат", JOptionPane.ERROR_MESSAGE);
}
}
}
);
JMenuItem openItemSingle = new JMenuItem("Открыть одиночный");
openItemSingle.addActionListener(
new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Выберите файл для загрузки данных");
//Установка фильтра для файлов с определённым расширением (например, txt)
fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt"));
fileChooser.setDialogTitle("Выберите файл для загрузки данных");
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (_storage.LoadDataSingle(selectedFile.getAbsolutePath())) {
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно", "Результат", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "Не загрузилось", "Результат", JOptionPane.ERROR_MESSAGE);
}
}
ReloadObjects();
}
});
JMenuItem saveItemSingle = new JMenuItem("Сохранение одиночного");
saveItemSingle.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
if (jListStorage.getSelectedValue() == null){
JOptionPane.showMessageDialog(null, "Не выбран гараж", "Ошибка", JOptionPane.ERROR_MESSAGE);
return;
}
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Выберите файл для сохранения данных");
// Установка фильтра для файлов с определенным расширением (например, .txt)
fileChooser.setFileFilter(new FileNameExtensionFilter("Текстовые файлы (*.txt)", "txt"));
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
if (_storage.SaveDataSingle(selectedFile.getAbsolutePath(), jListStorage.getSelectedValue()))
JOptionPane.showMessageDialog(null, "Сохранение прошло успешно", "Результат", JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(null, "Не сохранилось", "Результат", JOptionPane.ERROR_MESSAGE);
}
}
}
);
// Добавляем пункты в меню
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.add(openItemSingle);
fileMenu.add(saveItemSingle);
// Добавляем меню в панель меню
menuBar.add(fileMenu);
Frame.setSize(880, 520);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.setLayout(null);
canv.setBounds(0, 0, pictureBoxWidth, pictureBoxHeight);
ButtonAddVehicle.setBounds(pictureBoxWidth - 10, 10, 170, 30);
TextBoxNumber.setBounds(pictureBoxWidth - 10, 50, 170, 30);
ButtonRemoveTank.setBounds(pictureBoxWidth - 10, 90, 170, 30);
ButtonRefreshCollection.setBounds(pictureBoxWidth - 10, 130, 170, 30);
toFormTankGenerate.setBounds(pictureBoxWidth - 10, 170, 170, 30);
buttonAddSet.setBounds(pictureBoxWidth - 10, 210, 170, 20);
textBoxSetName.setBounds(pictureBoxWidth - 10, 240, 170, 20);
jListStorage.setBounds(pictureBoxWidth - 10, 270, 170, 80);
buttonRemoveSet.setBounds(pictureBoxWidth - 10, 360, 170, 20);
buttonGetRemoved.setBounds(pictureBoxWidth - 10, 390, 170, 20);
menuBar.setBounds(pictureBoxWidth - 10, 420, 170, 20);
Frame.add(canv);
Frame.add(ButtonAddVehicle);
Frame.add(ButtonRemoveTank);
Frame.add(ButtonRefreshCollection);
Frame.add(TextBoxNumber);
Frame.add(toFormTankGenerate);
Frame.add(buttonAddSet);
Frame.add(textBoxSetName);
Frame.add(jListStorage);
Frame.add(buttonRemoveSet);
Frame.add(buttonGetRemoved);
Frame.add(menuBar);
Frame.setVisible(true);
}
}

View File

@ -1,389 +0,0 @@
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.event.*;
import java.io.IOException;
public class FormTankConfig {
private class Canvas extends JComponent {
public Canvas() { }
public void paintComponent (Graphics g) {
if(_vehicle == null) {
return;
}
super.paintComponents(g);
Graphics2D g2d = (Graphics2D)g;
_vehicle.DrawTransport(g2d);
super.repaint();
}
}
//Класс для перетаскивания объекта на формочку
private class LabelTransferHandler extends TransferHandler {
@Override
public int getSourceActions(JComponent c) { return TransferHandler.COPY; }
@Override
protected Transferable createTransferable (JComponent c) { return new StringSelection(((JLabel)c).getText()); }
}
// Класс для возможности передвижения цвета
private class ColorTransferable implements Transferable {
private Color color;
private static final DataFlavor colorDataFlavor = new DataFlavor(Color.class, "Color");
public ColorTransferable(Color color) { this.color = color; }
@Override
public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[]{ colorDataFlavor }; }
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) { return colorDataFlavor.equals(flavor); }
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if(isDataFlavorSupported(flavor)) {
return color;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
// Для перетаскивания цвета к объекту
private class PanelTransferHandler extends TransferHandler {
@Override
public int getSourceActions(JComponent c) { return TransferHandler.COPY; }
@Override
protected Transferable createTransferable(JComponent c) {
return new ColorTransferable(((JPanel)c).getBackground());
}
}
// Для обработки нажатий
private class LabelMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
((JLabel)e.getComponent()).getTransferHandler().exportAsDrag(((JLabel)e.getComponent()), e, TransferHandler.COPY);
}
}
private class PanelMouseAdapter extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
((JPanel)e.getComponent()).getTransferHandler().exportAsDrag(((JPanel)e.getComponent()), e, TransferHandler.COPY);
}
}
// Для передвижения wheels по формочке
private class WheelTransferable implements Transferable {
private IOrnamentForm wheelDrawing;
private static final DataFlavor wheelDrawingDataFlavor = new DataFlavor(IOrnamentForm.class, "Wheel Drawing");
public WheelTransferable(IOrnamentForm wheelDrawing) { this.wheelDrawing = wheelDrawing; }
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) { return flavor.equals(wheelDrawingDataFlavor); }
@Override
public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { wheelDrawingDataFlavor }; }
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if(isDataFlavorSupported(flavor)) {
return wheelDrawing;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
// Для отрисовки wheels, которые можно брать и перетаскивать на объект
private class ComponentWheel extends JComponent {
public IOrnamentForm wheelDrawing;
// Конструктор
public ComponentWheel(IOrnamentForm _wheelDrawing) {
wheelDrawing = _wheelDrawing;
this.addMouseListener(
new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((ComponentWheel) e.getComponent()).getTransferHandler().exportAsDrag(((ComponentWheel) e.getComponent()), e, TransferHandler.COPY);
}
});
this.setTransferHandler(
new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new WheelTransferable(((ComponentWheel)c).wheelDrawing);
}
}
);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
wheelDrawing.Draw(g2d,-10, -42);
super.repaint();
}
}
final int WindowHeight = 700;
final int WindowWidth = 1000;
final int CanvasHeight = 600;
final int CanvasWidth = 800;
public DrawingArmoVehicle _vehicle = null;
public JButton buttonAdd;
public JFrame Frame;
public Canvas canvas;
public FormTankConfig() {
Border border = BorderFactory.createLineBorder(Color.GRAY);
JLabel labelSpeed = new JLabel("Speed");
JLabel labelWeight = new JLabel("Weight");
JLabel labelWheelNum = new JLabel("Wheel");
SpinnerModel spinnerModel = new SpinnerNumberModel(100, 100, 1000, 1);
JSpinner numericSpeed = new JSpinner(spinnerModel);
SpinnerModel spinnerModel2 = new SpinnerNumberModel(100, 100, 1000, 1);
JSpinner numericWeight = new JSpinner(spinnerModel2);
SpinnerModel spinnerModel3 = new SpinnerNumberModel(2, 2, 5, 1);
JSpinner numericWheelNum = new JSpinner(spinnerModel3);
JCheckBox checkBoxBodyKit = new JCheckBox("BodyKit");
JCheckBox checkBoxCaterpillar = new JCheckBox("Caterpillar");
JCheckBox checkBoxTower = new JCheckBox("Tower");
JPanel[] colorPanels = {
new JPanel(),new JPanel(),new JPanel(),new JPanel(),
new JPanel(),new JPanel(),new JPanel(),new JPanel(),
};
colorPanels[0].setBackground(Color.BLACK);
colorPanels[1].setBackground(Color.BLUE);
colorPanels[2].setBackground(Color.GRAY);
colorPanels[3].setBackground(Color.YELLOW);
colorPanels[4].setBackground(Color.RED);
colorPanels[5].setBackground(Color.GREEN);
colorPanels[6].setBackground(Color.ORANGE);
colorPanels[7].setBackground(Color.WHITE);
for (var it : colorPanels){
it.setTransferHandler(new PanelTransferHandler());
it.addMouseListener(new PanelMouseAdapter());
}
JLabel labelArmoVehicle = new JLabel("ArmoVehicle");
labelArmoVehicle.setTransferHandler(new LabelTransferHandler());
labelArmoVehicle.addMouseListener(new LabelMouseAdapter());
labelArmoVehicle.setBorder(border);
labelArmoVehicle.setHorizontalAlignment(SwingConstants.CENTER);
labelArmoVehicle.setVerticalAlignment(SwingConstants.CENTER);
JLabel labelTank = new JLabel("Tank");
labelTank.setTransferHandler(new LabelTransferHandler());
labelTank.addMouseListener(new LabelMouseAdapter());
labelTank.setBorder(border);
labelTank.setHorizontalAlignment(SwingConstants.CENTER);
labelTank.setVerticalAlignment(SwingConstants.CENTER);
JLabel labelColor = new JLabel("Color");
labelColor.setBorder(border);
labelColor.setHorizontalAlignment(SwingConstants.CENTER);
labelColor.setVerticalAlignment(SwingConstants.CENTER);
labelColor.setTransferHandler(
new TransferHandler(){
@Override
public boolean canImport(TransferSupport support) {
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferSupport support) {
if (canImport(support)) {
try {
Color color = (Color) support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
if (_vehicle == null)
return false;
_vehicle.ArmoVehicle.setBodyColor(color);
canvas.repaint();
return true;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
return false;
}
}
);
JLabel labelAdditionalColor = new JLabel("Additional color");
labelAdditionalColor.setBorder(border);
labelAdditionalColor.setHorizontalAlignment(SwingConstants.CENTER);
labelAdditionalColor.setVerticalAlignment(SwingConstants.CENTER);
labelAdditionalColor.setTransferHandler(
new TransferHandler(){
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (canImport(support)) {
try {
Color color = (Color) support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
if (_vehicle == null)
return false;
if (!(_vehicle instanceof DrawingTank))
return false;
((EntityTank)_vehicle.ArmoVehicle).setAdditionalColor(color);
return true;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
return false;
}
}
);
JLabel labelWheel = new JLabel("Wheel");
labelWheel.setBorder(border);
labelWheel.setHorizontalAlignment(SwingConstants.CENTER);
labelWheel.setVerticalAlignment(SwingConstants.CENTER);
labelWheel.setTransferHandler(
new TransferHandler(){
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(WheelTransferable.wheelDrawingDataFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (canImport(support)) {
try {
IOrnamentForm wheelDrawing = (IOrnamentForm) support.getTransferable().getTransferData(WheelTransferable.wheelDrawingDataFlavor);
if (_vehicle == null)
return false;
wheelDrawing.setDigit(_vehicle.ArmoVehicle.numWheel);
_vehicle.OrnamentsForm = wheelDrawing;
canvas.repaint();
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
return false;
}
}
);
canvas = new Canvas();
canvas.setTransferHandler(
new TransferHandler(){
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(DataFlavor.stringFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (canImport(support)) {
try {
String data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
switch (data) {
case "ArmoVehicle":
_vehicle = new DrawingArmoVehicle((int)numericSpeed.getValue(), (int)numericWeight.getValue(), Color.WHITE, (int)numericWheelNum.getValue(), CanvasWidth,CanvasHeight);
break;
case "Tank":
_vehicle = new DrawingTank((int)numericSpeed.getValue(), (int)numericWeight.getValue(), Color.WHITE, (int)numericWheelNum.getValue(), Color.BLACK, checkBoxBodyKit.isSelected(), checkBoxCaterpillar.isSelected(), checkBoxTower.isSelected(), CanvasWidth, CanvasHeight);
break;
}
canvas.repaint();
return true;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
}
return false;
}
}
);
buttonAdd = new JButton("Add");
JButton buttonCancel = new JButton("Cancel");
ComponentWheel componentSuspensionOrnament = new ComponentWheel(new DrawingSuspensionOrnament());
ComponentWheel componentAsteriskOrnament = new ComponentWheel(new DrawingStarOrnament());
ComponentWheel componentWheelCombination = new ComponentWheel(new DrawingWheelsCombination());
labelSpeed.setBounds(10,10,40,20);
labelWeight.setBounds(10,40,40,20);
labelWheelNum.setBounds(10,70,40,20);
numericSpeed.setBounds(55,10,80,20);
numericWeight.setBounds(55,40,80,20);
numericWheelNum.setBounds(55,70,80,20);
checkBoxBodyKit.setBounds(10,100,120,20);
checkBoxCaterpillar.setBounds(10,130,120,20);
checkBoxTower.setBounds(10,160,120,20);
for (int i = 0; i < colorPanels.length; i+=2) {
colorPanels[i].setBounds(10,200+i/2*60,50,50);
colorPanels[i+1].setBounds(70,200+i/2*60,50,50);
}
componentSuspensionOrnament.setBounds(10,470,25,20);
componentAsteriskOrnament.setBounds(50,470,20,20);
componentWheelCombination.setBounds(90,470,25,20);
labelArmoVehicle.setBounds(10,600 ,80,30);
labelTank.setBounds(100,600 ,80,30);
labelColor.setBounds(WindowWidth-CanvasWidth, 10, CanvasWidth/3, 30);
labelAdditionalColor.setBounds(WindowWidth-CanvasWidth + CanvasWidth/3, 10, CanvasWidth/3, 30);
labelWheel.setBounds(WindowWidth-CanvasWidth + CanvasWidth*2/3, 10, CanvasWidth/3, 30);
canvas.setBounds(WindowWidth-CanvasWidth, 50, CanvasWidth, CanvasHeight);
buttonAdd.setBounds(WindowWidth-CanvasWidth, CanvasHeight+60, CanvasWidth/3, 30);
buttonCancel.setBounds(WindowWidth-CanvasWidth + CanvasWidth*2/3, CanvasHeight+60, CanvasWidth/3, 30);
Frame = new JFrame();
Frame.setSize (WindowWidth+20, WindowHeight+40);
Frame.setLayout(null);
Frame.add(labelSpeed);
Frame.add(labelWeight);
Frame.add(labelWheelNum);
Frame.add(numericSpeed);
Frame.add(numericWeight);
Frame.add(numericWheelNum);
Frame.add(checkBoxBodyKit);
Frame.add(checkBoxCaterpillar);
Frame.add(checkBoxTower);
for (var it : colorPanels)
Frame.add(it);
Frame.add(labelArmoVehicle);
Frame.add(labelTank);
Frame.add(labelColor);
Frame.add(labelAdditionalColor);
Frame.add(labelWheel);
Frame.add(canvas);
Frame.add(buttonAdd);
Frame.add(buttonCancel);
Frame.add(componentSuspensionOrnament);
Frame.add(componentAsteriskOrnament);
Frame.add(componentWheelCombination);
Frame.setVisible(true);
buttonCancel.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
Frame.dispose();
}
}
);
}
}

View File

@ -1,55 +0,0 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FormTankGenerate extends JFrame {
static int pictureBoxWidth = 560;
static int pictureBoxHeight = 560;
public DrawingArmoVehicle _drawingTank;
private class Canvas extends JComponent{
public Canvas() {
}
public void paintComponent (Graphics g){
if (_drawingTank == null){
return;
}
super.paintComponents (g) ;
Graphics2D g2d = (Graphics2D)g;
_drawingTank.SetPosition(250, 250);
_drawingTank.DrawTransport(g2d);
super.repaint();
}
}
DoubleParametrized<EntityArmoVehicle, IOrnamentForm> genericTankGenerate;
public FormTankGenerate(){
_drawingTank = null;
Canvas canv = new Canvas();
setSize (640, 640);
setLayout(null);
canv.setBounds(0,0,pictureBoxWidth, pictureBoxHeight);
genericTankGenerate = new DoubleParametrized<>();
genericTankGenerate.Add(new EntityArmoVehicle(100, 100, Color.BLUE, 2));
genericTankGenerate.Add(new EntityArmoVehicle(100, 100, Color.RED, 3));
genericTankGenerate.Add(new EntityArmoVehicle(100, 100, Color.GRAY, 4));
genericTankGenerate.Add(new EntityTank(100, 100, Color.BLUE, 2, Color.ORANGE, true, true, true));
genericTankGenerate.Add(new DrawingStarOrnament());
genericTankGenerate.Add(new DrawingWheelsCombination());
JButton creatButton = new JButton("Сгенерировать");
creatButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
_drawingTank = genericTankGenerate.GenerateTank(pictureBoxWidth,pictureBoxHeight);
canv.repaint();
}
}
);
creatButton.setBounds(pictureBoxWidth/2 - 40, pictureBoxHeight-20, 180, 20);
add(canv);
add(creatButton);
setVisible(true);
}
}

View File

@ -1,13 +0,0 @@
public interface IMoveableObject {
// Получение координаты X объекта
ObjectParameters GetObjectPosition();
// Шаг объекта
int GetStep();
// Проверка, можно ли переместиться по нужному направлению
boolean CheckCanMove(Direction direction);
/// Изменение направления пермещения объекта
void MoveObject(Direction direction);
}

View File

@ -1,7 +0,0 @@
import java.awt.*;
public interface IOrnamentForm {
public CountWheels getNumWheel();
void setDigit(int number);
void Draw(Graphics g, int _startPosX, int _startPosY);
}

View File

@ -1,5 +0,0 @@
public class Main {
public static void main(String[] args) {
new FormTankCollection();
}
}

View File

@ -1,36 +0,0 @@
public class MoveToBorder extends AbstractStrategy{
protected boolean IsTargetDestination() {
var objParams = GetObjectParameters();
if (objParams == null) {
return false;
}
return objParams.RightBorder() <= FieldWidth &&
objParams.RightBorder() + GetStep() >= FieldWidth &&
objParams.DownBorder() <= FieldHeight &&
objParams.DownBorder() + GetStep() >= FieldHeight;
}
protected void MoveToTarget() {
var objParams = GetObjectParameters();
if (objParams == null) {
return;
}
var diffX = objParams.RightBorder() - FieldWidth;
if (Math.abs(diffX) > GetStep()) {
if (diffX > 0) {
MoveLeft();
}
else {
MoveRight();
}
}
var diffY = objParams.DownBorder() - FieldHeight;
if (Math.abs(diffY) > GetStep()) {
if (diffY > 0) {
MoveUp();
}
else {
MoveDown();
}
}
}
}

View File

@ -1,35 +0,0 @@
public class MoveToCenter extends AbstractStrategy {
protected boolean IsTargetDestination() {
var objParams = GetObjectParameters();
if (objParams == null) {
return false;
}
return
Math.abs(objParams.ObjectMiddleHorizontal() - FieldWidth / 2) <= GetStep()
&&
Math.abs(objParams.ObjectMiddleVertical() - FieldHeight / 2) <= GetStep();
}
protected void MoveToTarget() {
var objParams = GetObjectParameters();
if (objParams == null) {
return;
}
var diffX = objParams.ObjectMiddleHorizontal() - FieldWidth / 2;
if (Math.abs(diffX) > GetStep()) {
if (diffX > 0) {
MoveLeft();
} else {
MoveRight();
}
}
var diffY = objParams.ObjectMiddleVertical() - FieldHeight / 2;
if (Math.abs(diffY) > GetStep()) {
if (diffY > 0) {
MoveUp();
} else {
MoveDown();
}
}
}
}

View File

@ -1,44 +0,0 @@
public class ObjectParameters {
private int _x;
private int _y;
private int _width;
private int _height;
// Левая граница
public int LeftBorder() {
return _x;
}
// Верхняя граница
public int TopBorder() {
return _y;
}
// Правая граница
public int RightBorder() {
return _x + _width;
}
// Нижняя граница
public int DownBorder() {
return _y + _height;
}
// Середина объекта
public int ObjectMiddleHorizontal() {
return _x + _width / 2;
}
// Середина объекта
public int ObjectMiddleVertical() {
return _y + _height / 2;
}
// Конструктор
public ObjectParameters(int x, int y, int width, int height) {
_x = x;
_y = y;
_width = width;
_height = height;
}
}

View File

@ -1,90 +0,0 @@
import java.util.*;
public class SetGeneric <T extends Object> {
// Массив объектов, которые храним
private final ArrayList<T> _places;
// Количество объектов в массиве
public int Count() { return _places.size(); }
// Максимальное количество объектов в списке
private final int _maxCount;
// Конструктор
public SetGeneric(int count) {
_maxCount = count;
_places = new ArrayList<T>(count);
}
// Добавление объектов в набор
public int Insert(T tank) {
if(_places.size() >= _maxCount)
return -1;
_places.add(0,tank);
return 0;
}
public boolean Insert(T tank, int position) {
// Проверка позиции
if (position < 0 || position > _places.size())
return false;
if (_places.size() >= _maxCount)
return false;
if (position == _places.size())
_places.add(tank);
else
_places.add(position, tank);
return true;
}
// Удаление объекта из набора с конкретной позиции
public boolean Remove(int position) {
// Проверка позиции
if (position < 0 || position >= _places.size())
return false;
_places.remove(position);
return true;
}
// Получение объекта из набора по позиции
public T Get(int position) {
// Проверка позиции
if (position < 0 || position >= _places.size())
return null;
return _places.get(position);
}
// Проход по списку
public Iterable<T> GetTanks(final Integer maxTanks) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
private int count = 0;
@Override
public boolean hasNext() {
return currentIndex < _places.size() && (maxTanks == null || count < maxTanks);
}
@Override
public T next() {
if (hasNext()) {
count++;
return _places.get(currentIndex++);
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
public void clear() { _places.clear(); }
}

View File

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

View File

@ -1,91 +0,0 @@
import java.awt.*;
import java.awt.image.BufferedImage;
public class TanksGenericCollections<T extends DrawingArmoVehicle, U extends IMoveableObject> {
// Высота и Ширина окна прорисовки
private int _pictureWidth;
private int _pictureHeight;
// Размеры занимаемого объектом места (ширина и высота)
private int _placeSizeWidth = 180;
private int _placeSizeHeight = 90;
// Набор объектов
private SetGeneric<T> _collection;
// Получение объектов коллекции
public Iterable<T> getTanks(final Integer maxTanks) { return _collection.GetTanks(maxTanks); }
public void clear() { _collection.clear(); }
// Конструктор
public TanksGenericCollections(int pictureWidth, int pictureHeight) {
int width = pictureWidth / _placeSizeWidth;
int height = pictureHeight / _placeSizeHeight;
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
_collection = new SetGeneric<T>(width * height);
}
// Перегрузка оператора сложения
public int Add(T obj) {
if (obj == null) {
return -1;
}
return _collection.Insert(obj);
}
// Перегрузка оператора вычитания
public T remove(int pos) {
T obj = _collection.Get(pos);
if (obj != null) {
_collection.Remove(pos);
}
return obj;
}
// Получение объекта IMoveableObject
public U GetU(int pos) {
return (U) _collection.Get(pos).GetMoveableObject();
}
// Вывод всего набора объектов
public BufferedImage ShowTanks() {
BufferedImage bitmap = new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bitmap.createGraphics();
DrawBackground(g);
DrawObjects(g);
g.dispose();
return bitmap;
}
// Метод отрисовки фона
private void DrawBackground(Graphics g) {
g.setColor(Color.BLACK);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) {
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j) {
// Линия разметки места
g.drawLine(i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
}
g.drawLine(i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
// Метод прорисовки объектов
private void DrawObjects(Graphics g) {
int i = 0;
for (T tank : _collection.GetTanks(100)) {
if (tank != null) {
tank._pictureHeight = _pictureHeight;
tank._pictureWidth = _pictureWidth;
tank.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
if (tank instanceof DrawingTank)
((DrawingTank) tank).DrawTransport((Graphics2D) g);
else
tank.DrawTransport((Graphics2D) g);
}
i++;
}
}
}

View File

@ -1,216 +0,0 @@
import java.util.*;
import java.util.stream.Collectors;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
public class TanksGenericStorage {
// Разделитель для записи ключа и значения элемента словаря
private static String _separatorForKeyValueWR = "|";
private static String _separatorForKeyValue = "\\|";
// Разделитель для записей коллекции данных в файл
private String _separatorRecordsWR = ";";
private String _separatorRecords = "\\;";
// Разделитель для записи информации по объекту в файл
private static String _separatorForObjectWR = ":";
private static String _separatorForObject = "\\:";
public boolean SaveDataSingle(String filename, String key) {
if(new File(filename).exists()) {
new File(filename).delete();
}
StringBuilder data = new StringBuilder();
data.append(key).append("\n");
for (DrawingArmoVehicle elem: _tankStorages.get(key).getTanks(100)) {
if(_tankStorages.get(key) == null)
return false;
if(_tankStorages.get(key) != null)
data.append(elem != null ? ExtentionDrawingTank.GetDataForSave(elem, _separatorForObjectWR) + "\n" : "");
}
if(data.length() == 0)
return false;
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
writer.write("TankStorageSingle" + System.lineSeparator() + data.toString());
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
public boolean LoadDataSingle(String filename) {
if(!new File(filename).exists()) {
return false;
}
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String s = reader.readLine();
if(s == null || s.length() == 0)
return false;
if(!s.startsWith("TankStorageSingle"))
return false;
String key = reader.readLine();
if(key == null || key.length() == 0)
return false;
TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank> collections = new TanksGenericCollections<>(_pictureWidth, _pictureHeight);
if (_tankStorages.containsKey(key)){
collections = _tankStorages.get(key);
collections.clear();
}
else
collections = new TanksGenericCollections<>(_pictureWidth, _pictureHeight);
List<String> tanksStrings = new ArrayList<String>();
s = reader.readLine();
while (s != null && s.length() != 0) {
tanksStrings.add(s);
s = reader.readLine();
}
Collections.reverse(tanksStrings);
for (String elem : tanksStrings) {
DrawingArmoVehicle vehicle = ExtentionDrawingTank.CreateDrawingTank(elem, _separatorForObject, _pictureWidth, _pictureHeight);
if(vehicle == null || collections.Add(vehicle) == -1)
return false;
}
if(_tankStorages.containsKey(key))
_tankStorages.remove(key);
_tankStorages.put(key, collections);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
// Сохранение информации по технике в хранилище в файл
public boolean SaveData(String filename) {
if(new File(filename).exists()) {
new File(filename).delete();
}
StringBuilder data = new StringBuilder();
for (Map.Entry<String, TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank>> record : _tankStorages.entrySet()) {
StringBuilder records = new StringBuilder();
for (DrawingArmoVehicle elem : record.getValue().getTanks(100)) {
records.append(elem != null ? ExtentionDrawingTank.GetDataForSave(elem, _separatorForObjectWR) + _separatorRecordsWR : "");
}
data.append(record.getKey()).append(_separatorForKeyValueWR).append(records).append("\n");
}
if (data.length() == 0)
return false;
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
writer.write("TankStorage" + System.lineSeparator() + data.toString());
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
// Загрузка информации по технике в хранилище из файла
public boolean LoadData(String filename) {
if (!new File(filename).exists()) {
return false;
}
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String s = reader.readLine();
if (s == null || s.length() == 0)
return false;
if (!s.startsWith("TankStorage"))
return false;
_tankStorages.clear();
s = reader.readLine();
while (s != null && s.length() != 0) {
String[] record = s.split(_separatorForKeyValue);
s = reader.readLine();
if (record.length != 2) {
continue;
}
TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank> collection = new TanksGenericCollections<>(_pictureWidth, _pictureHeight);
String[] set = record[1].split(_separatorRecords);
List<String> reversedSet = Arrays.asList(set);
Collections.reverse(reversedSet);
for (String elem : reversedSet) {
DrawingArmoVehicle vehicle = ExtentionDrawingTank.CreateDrawingTank(elem, _separatorForObject, _pictureWidth, _pictureHeight);
if (vehicle == null || collection.Add(vehicle) == -1)
return false;
}
_tankStorages.put(record[0], collection);
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
// Словарь (как хранилище)
HashMap<String, TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank>> _tankStorages;
// Возвращение списка названий наборов
public List<String> Keys() {
return _tankStorages.keySet().stream().collect(Collectors.toList());
}
// Ширина и высота отрисовки
private int _pictureWidth;
private int _pictureHeight;
// Конструктор
public TanksGenericStorage(int pictureWidth, int pictureHeight) {
_tankStorages = new HashMap<String, TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
// Добавление набора
public void AddSet(String name) {
if (_tankStorages.containsKey(name))
return;
_tankStorages.put(name, new TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank>(_pictureWidth, _pictureHeight));
}
// Удаление набора
public void DelSet(String name) {
if (!_tankStorages.containsKey(name))
return;
_tankStorages.remove(name);
}
// Доступ к набору
public TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank> get(String ind) {
if (_tankStorages.containsKey(ind))
return _tankStorages.get(ind);
return null;
}
public DrawingObjectTank get(String ind1, int ind2){
if (!_tankStorages.containsKey(ind1))
return null;
return _tankStorages.get(ind1).GetU(ind2);
}
}