Лабораторная 4

This commit is contained in:
Никита Белянин 2023-11-12 23:54:15 +04:00
parent f36e6da08d
commit 1c95abf999
12 changed files with 349 additions and 139 deletions

View File

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

View File

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

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

@ -5,7 +5,7 @@ public enum CountWheels {
Five(5); Five(5);
private final int Value; private final int Value;
CountWheels(int Count){ CountWheels(int Count){
Value = Count; Value=Count;
} }
public int getCountWheels(){ public int getCountWheels(){
return Value; return Value;

View File

@ -10,7 +10,9 @@ public class DrawingArmoVehicle {
protected int _startPosY; protected int _startPosY;
protected int _TankWidth = 160; protected int _TankWidth = 160;
protected int _TankHeight = 55; protected int _TankHeight = 55;
public IMoveableObject GetMoveableObject() { return new DrawingObjectTank(this);} public IMoveableObject GetMoveableObject() {
return new DrawingObjectTank(this);
}
public DrawingArmoVehicle(int speed, double weight, Color bodyColor, int _numWheel, int width, int height) { public DrawingArmoVehicle(int speed, double weight, Color bodyColor, int _numWheel, int width, int height) {
_pictureWidth = width; _pictureWidth = width;
@ -20,7 +22,7 @@ public class DrawingArmoVehicle {
ArmoVehicle = new EntityArmoVehicle(speed, weight, bodyColor, _numWheel); ArmoVehicle = new EntityArmoVehicle(speed, weight, bodyColor, _numWheel);
Random random = new Random(); Random random = new Random();
switch(random.nextInt(0, 3)) { switch (random.nextInt(0, 3)) {
case 0: case 0:
OrnamentsForm = new DrawingWheelsCombination(); OrnamentsForm = new DrawingWheelsCombination();
break; break;
@ -52,10 +54,21 @@ public class DrawingArmoVehicle {
_startPosY = Math.min(y, _pictureHeight - _TankHeight); _startPosY = Math.min(y, _pictureHeight - _TankHeight);
} }
public int GetPosX () { return _startPosX; } public int GetPosX() {
public int GetPosY () { return _startPosY; } return _startPosX;
public int GetWidth () { return _TankWidth; } }
public int GetHeight () { return _TankHeight; }
public int GetPosY() {
return _startPosY;
}
public int GetWidth() {
return _TankWidth;
}
public int GetHeight() {
return _TankHeight;
}
public boolean CanMove(Direction direction) { public boolean CanMove(Direction direction) {
if (ArmoVehicle == null) { if (ArmoVehicle == null) {
@ -82,19 +95,19 @@ public class DrawingArmoVehicle {
switch (direction) { switch (direction) {
//влево //влево
case Left: case Left:
_startPosX -= (int)ArmoVehicle.Step; _startPosX -= (int) ArmoVehicle.Step;
break; break;
//вверх //вверх
case Up: case Up:
_startPosY -= (int)ArmoVehicle.Step; _startPosY -= (int) ArmoVehicle.Step;
break; break;
// вправо // вправо
case Right: case Right:
_startPosX += (int)ArmoVehicle.Step; _startPosX += (int) ArmoVehicle.Step;
break; break;
//вниз //вниз
case Down: case Down:
_startPosY += (int)ArmoVehicle.Step; _startPosY += (int) ArmoVehicle.Step;
break; break;
} }
} }
@ -104,13 +117,12 @@ public class DrawingArmoVehicle {
return; return;
} }
// body
g.setColor(ArmoVehicle.BodyColor); g.setColor(ArmoVehicle.BodyColor);
int[] xPoints = {_startPosX + 5, _startPosX + 140, _startPosX + 130,_startPosX + 12}; int[] xPoints = {_startPosX + 5, _startPosX + 140, _startPosX + 130, _startPosX + 12};
int[] yPoints = {_startPosY + 30, _startPosY + 30, _startPosY + 42, _startPosY + 42}; int[] yPoints = {_startPosY + 30, _startPosY + 30, _startPosY + 42, _startPosY + 42};
int nPoints = xPoints.length; int nPoints = 4;
g.drawPolygon(xPoints,yPoints,nPoints); g.drawPolygon(xPoints, yPoints, nPoints);
g.fillPolygon(xPoints,yPoints,nPoints); g.fillPolygon(xPoints, yPoints, nPoints);
//wheels //wheels
OrnamentsForm.Draw(g, _startPosX, _startPosY); OrnamentsForm.Draw(g, _startPosX, _startPosY);

View File

@ -4,67 +4,64 @@ public class DrawingTank extends DrawingArmoVehicle {
protected IOrnamentForm OrnamentsForm; protected IOrnamentForm OrnamentsForm;
private boolean OrnamentAdd; 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) { 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); super(speed, weight, bodyColor, _numWheel, width, height);
ArmoVehicle = new EntityTank(speed, weight, bodyColor, _numWheel, additionalColor, bodyKit, caterpillar, tower); ArmoVehicle = new EntityTank(speed, weight, bodyColor, _numWheel, additionalColor, bodyKit, caterpillar, tower);
_TankWidth = ((EntityTank)ArmoVehicle).BodyKit ? 169 : 83; _TankWidth = ((EntityTank) ArmoVehicle).BodyKit ? 169 : 83;
this.OrnamentAdd = ornamentAdd; this.OrnamentAdd = ornamentAdd;
} }
// Ещё один конструктор // Ещё один конструктор
public DrawingTank(EntityTank tank, IOrnamentForm _wheelDrawing, int width, int height ){ public DrawingTank(EntityTank tank, IOrnamentForm _wheelDrawing, int width, int height) {
super(tank, _wheelDrawing, width, height); super(tank, _wheelDrawing, width, height);
if (height < _pictureHeight || width < _pictureWidth) if (height < _pictureHeight || width < _pictureWidth)
return; return;
} }
// Установка позиции
public void SetPosition(int x, int y) { public void SetPosition(int x, int y) {
_startPosX = Math.min(x, _pictureWidth-_TankWidth); _startPosX = Math.min(x, _pictureWidth - _TankWidth);
_startPosY = Math.min(y, _pictureHeight-_TankHeight); _startPosY = Math.min(y, _pictureHeight - _TankHeight);
} }
private boolean setOrnamentAdd() { return OrnamentAdd; } private boolean setOrnamentAdd() {
return OrnamentAdd;
}
// Прорисовка объекта
public void DrawTransport(Graphics2D g) { public void DrawTransport(Graphics2D g) {
if (ArmoVehicle == null) { if (ArmoVehicle == null) {
return; return;
} }
super.DrawTransport(g); super.DrawTransport(g);
g.setColor(((EntityTank) ArmoVehicle).AdditionalColor);
if (((EntityTank) ArmoVehicle).BodyKit) { if (((EntityTank) ArmoVehicle).BodyKit) {
g.setColor(((EntityTank) ArmoVehicle).AdditionalColor); 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[] 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[] 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;
int nPointsBody = xPointsBody.length;
g.drawPolygon(xPointsBody,yPointsBody,nPointsBody); g.drawPolygon(xPointsBody, yPointsBody, nPointsBody);
g.fillPolygon(xPointsBody,yPointsBody,nPointsBody); g.fillPolygon(xPointsBody, yPointsBody, nPointsBody);
} }
if (((EntityTank) ArmoVehicle).Caterpillar) { if (((EntityTank) ArmoVehicle).Caterpillar) {
Color Gray = new Color(128, 128, 128); // Гусеница
g.setColor(Gray);
g.drawOval(_startPosX + 10, _startPosY + 30, 120, 30); g.drawOval(_startPosX + 10, _startPosY + 30, 120, 30);
} }
if (((EntityTank) ArmoVehicle).Tower) { if (((EntityTank) ArmoVehicle).Tower) {
g.setColor(Color.DARK_GRAY);
// Орудие // Орудие
g.drawRect(_startPosX + 112, _startPosY + 17, 60, 5); g.drawRect(_startPosX + 112, _startPosY + 17, 60, 4);
g.fillRect(_startPosX + 112, _startPosY + 17, 60, 5); 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[] 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[] 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 = xPointsGun.length; int nPointsGun = 11;
g.fillRect(_startPosX + 50, _startPosY + 5, 20, 2); g.fillRect(_startPosX + 50, _startPosY + 5, 20, 2);
g.drawPolygon(xPointsGun,yPointsGun,nPointsGun); g.drawPolygon(xPointsGun, yPointsGun, nPointsGun);
g.fillPolygon(xPointsGun,yPointsGun,nPointsGun); g.fillPolygon(xPointsGun, yPointsGun, nPointsGun);
} }
} }
} }

View File

@ -3,6 +3,9 @@ import java.awt.*;
public class EntityArmoVehicle { public class EntityArmoVehicle {
public int Speed; public int Speed;
public double Weight; public double Weight;
public double getWeight() {
return Weight;
}
public Color BodyColor; public Color BodyColor;
public double Step; public double Step;
public int numWheel; public int numWheel;
@ -12,6 +15,6 @@ public class EntityArmoVehicle {
Weight = weight; Weight = weight;
BodyColor = bodyColor; BodyColor = bodyColor;
numWheel = _numWheel; numWheel = _numWheel;
Step = (double) Speed * 200 / Weight; Step = (double) Speed * 300 / Weight;
} }
} }

View File

@ -58,12 +58,11 @@ public class FormTank {
down.setIcon(iconDown); down.setIcon(iconDown);
JButton left = new JButton(); JButton left = new JButton();
left.setName("left"); left.setName("left");
ImageIcon iconLeft = new ImageIcon("Resources//KeyLeft.png"); ImageIcon iconLeft = new ImageIcon("Resources//KeyLeft.png");
left.setIcon(iconLeft); left.setIcon(iconLeft);
JButton right = new JButton();
JButton right = new JButton();
right.setName("right"); right.setName("right");
ImageIcon iconRight = new ImageIcon("Resources//KeyRight.png"); ImageIcon iconRight = new ImageIcon("Resources//KeyRight.png");
right.setIcon(iconRight); right.setIcon(iconRight);
@ -105,6 +104,7 @@ public class FormTank {
} }
} }
); );
buttonCreateTank.addActionListener( buttonCreateTank.addActionListener(
new ActionListener() { new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
@ -139,6 +139,7 @@ public class FormTank {
} }
} }
); );
buttonCreateArmoVehicle.addActionListener( buttonCreateArmoVehicle.addActionListener(
new ActionListener() { new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
@ -186,6 +187,7 @@ public class FormTank {
Draw(); Draw();
} }
}; };
up.addActionListener(actioListener); up.addActionListener(actioListener);
down.addActionListener(actioListener); down.addActionListener(actioListener);
left.addActionListener(actioListener); left.addActionListener(actioListener);

View File

@ -1,44 +1,84 @@
import javax.swing.*; import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*; import java.awt.*;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.Queue;
public class FormTankCollection { public class FormTankCollection {
private class Canvas extends JComponent { private class Canvas extends JComponent {
public TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank> _tank;
public Canvas() { public Canvas() {
} }
public void paintComponent (Graphics g) {
public void paintComponent(Graphics g) {
super.paintComponent(g); super.paintComponent(g);
if (_tank.ShowTanks() != null) { if (jListStorage.getSelectedIndex() == -1) {
g.drawImage(_tank.ShowTanks(), 0, 10, this); return;
}
var obj = _storage.get(jListStorage.getSelectedValue());
if (obj == null) {
return;
}
if (obj.ShowTank() != null) {
g.drawImage(obj.ShowTank(), 0, 0, this);
} }
super.repaint(); super.repaint();
} }
} }
Canvas canv; Canvas canv;
static int pictureBoxWidth = 700; static int pictureBoxWidth = 700;
static int pictureBoxHeight = 480; static int pictureBoxHeight = 480;
private TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank> _tank; private TanksGenericStorage _storage;
public void Draw(){
public void Draw() {
canv.repaint(); 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() { FormTankCollection() {
listModel = new DefaultListModel<String>();
jListStorage = new JList<String>(listModel);
canv = new Canvas(); canv = new Canvas();
JFrame Frame = new JFrame ("TanksCollecltion"); JFrame Frame = new JFrame("TankCollecltion");
_tank = new TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank>(pictureBoxWidth, pictureBoxHeight); _storage = new TanksGenericStorage(pictureBoxWidth, pictureBoxHeight);
canv._tank = _tank;
JButton ButtonAddTank = new JButton("Добавить технику"); JButton ButtonAddVehicle = new JButton("Добавить технику");
ButtonAddVehicle.addActionListener(
ButtonAddTank.addActionListener(
new ActionListener() { new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if (jListStorage.getSelectedIndex() == -1) {
return;
}
var obj = _storage.get(jListStorage.getSelectedValue());
if (obj == null) {
return;
}
FormTank form = new FormTank(); FormTank form = new FormTank();
form.buttonSelectTank.addActionListener( form.buttonSelectTank.addActionListener(
new ActionListener() { new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if (_tank.Add(form._drawingVehicle) != -1) { if (obj.Add(form._drawingVehicle) != -1) {
JOptionPane.showMessageDialog(null, "Объект добавлен", "Информация", JOptionPane.INFORMATION_MESSAGE); JOptionPane.showMessageDialog(null, "Объект добавлен", "Информация", JOptionPane.INFORMATION_MESSAGE);
Draw(); Draw();
} else { } else {
@ -52,11 +92,21 @@ public class FormTankCollection {
} }
); );
Queue = new LinkedList<DrawingArmoVehicle>();
JTextField TextBoxNumber = new JTextField(); JTextField TextBoxNumber = new JTextField();
JButton ButtonRemoveTank = new JButton("Удалить технику"); JButton ButtonRemoveTank = new JButton("Удалить технику");
ButtonRemoveTank.addActionListener( ButtonRemoveTank.addActionListener(
new ActionListener() { new ActionListener() {
public void actionPerformed(ActionEvent e) { 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) { if (JOptionPane.showConfirmDialog(null, "Удалить объект?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
return; return;
} }
@ -71,7 +121,9 @@ public class FormTankCollection {
} }
int pos = Integer.parseInt(TextBoxNumber.getText()); int pos = Integer.parseInt(TextBoxNumber.getText());
if (_tank.remove(pos) != null) { var removed = obj.remove(pos);
if (removed != null) {
Queue.add(removed);
JOptionPane.showMessageDialog(null, "Объект удален", "Информация", JOptionPane.INFORMATION_MESSAGE); JOptionPane.showMessageDialog(null, "Объект удален", "Информация", JOptionPane.INFORMATION_MESSAGE);
Draw(); Draw();
} else { } else {
@ -81,39 +133,110 @@ public class FormTankCollection {
} }
); );
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("Обновить коллекцию"); JButton ButtonRefreshCollection = new JButton("Обновить коллекцию");
ButtonRefreshCollection.addActionListener( ButtonRefreshCollection.addActionListener(
new ActionListener() { new ActionListener() {
public void actionPerformed(ActionEvent e){ public void actionPerformed(ActionEvent e) {
Draw(); Draw();
} }
} }
); );
JButton toFormTankGenerate = new JButton("Генерировать технику"); JButton toForm4GenericDopClass = new JButton("Генерация");
toFormTankGenerate.addActionListener( toForm4GenericDopClass.addActionListener(
new ActionListener() { new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
FormTankGenerate formTankGenerate = new FormTankGenerate(); FormTankGenerate formTankGenerate = new FormTankGenerate();
} }
} }
); );
Frame.setSize (880, 520); JTextField textBoxSetName = new JTextField();
Frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 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();
}
}
);
Frame.setSize(880, 520);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.setLayout(null); Frame.setLayout(null);
canv.setBounds(0, 0, pictureBoxWidth, pictureBoxHeight); canv.setBounds(0, 0, pictureBoxWidth, pictureBoxHeight);
ButtonAddTank.setBounds(pictureBoxWidth - 50, 10, 170, 30); ButtonAddVehicle.setBounds(pictureBoxWidth - 10, 10, 170, 30);
TextBoxNumber.setBounds(pictureBoxWidth - 50, 50, 170, 20); TextBoxNumber.setBounds(pictureBoxWidth - 10, 50, 170, 30);
ButtonRemoveTank.setBounds(pictureBoxWidth - 50, 80, 170, 30); ButtonRemoveTank.setBounds(pictureBoxWidth - 10, 90, 170, 30);
ButtonRefreshCollection.setBounds(pictureBoxWidth - 50, 120, 170, 30); ButtonRefreshCollection.setBounds(pictureBoxWidth - 10, 130, 170, 30);
toFormTankGenerate.setBounds(pictureBoxWidth - 50, 160, 170, 30); toForm4GenericDopClass.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);
Frame.add(canv); Frame.add(canv);
Frame.add(ButtonAddTank); Frame.add(ButtonAddVehicle);
Frame.add(ButtonRemoveTank); Frame.add(ButtonRemoveTank);
Frame.add(ButtonRefreshCollection); Frame.add(ButtonRefreshCollection);
Frame.add(TextBoxNumber); Frame.add(TextBoxNumber);
Frame.add(toFormTankGenerate); Frame.add(toForm4GenericDopClass);
Frame.add(buttonAddSet);
Frame.add(textBoxSetName);
Frame.add(jListStorage);
Frame.add(buttonRemoveSet);
Frame.add(buttonGetRemoved);
Frame.setVisible(true); Frame.setVisible(true);
} }
} }

View File

@ -1,61 +1,89 @@
public class SetGeneric<T extends DrawingArmoVehicle> { import java.util.*;
public class SetGeneric <T extends Object> {
// Массив объектов, которые храним // Массив объектов, которые храним
private Object[] _places; private final ArrayList<T> _places;
// Количество объектов в массиве // Количество объектов в массиве
public int Count; public int Count() { return _places.size(); }
// Максимальное количество объектов в списке
private final int _maxCount;
// Конструктор // Конструктор
public SetGeneric(int count) { public SetGeneric(int count) {
_places = new Object[count]; _maxCount = count;
Count = _places.length; _places = new ArrayList<T>(count);
} }
// Добавление объекта в набор // Добавление объектов в набор
public int Insert(T tank) { public int Insert(T tank) {
int i = 0; if(_places.size() >= _maxCount)
for (; i < _places.length; i++) {
if (_places[i] == null)
break;
}
if (i == _places.length)
return -1; return -1;
for (; i > 0; i--) { _places.add(0,tank);
_places[i] = _places[i - 1]; return 0;
}
_places[i] = tank;
return i;
} }
// Добавление объекта в набор на конкретную позицию
public boolean Insert(T tank, int position) { public boolean Insert(T tank, int position) {
if (position < 0 || position >= _places.length) // Проверка позиции
if (position < 0 || position > _places.size())
return false; return false;
for (; position < _places.length; position++) {
if (_places[position] == null) if (_places.size() >= _maxCount)
break;
}
if (position == _places.length)
return false; return false;
for (; position > 0; position--) {
_places[position] = _places[position - 1]; if (position == _places.size())
} _places.add(tank);
_places[position] = tank; else
_places.add(position, tank);
return true; return true;
} }
// Удаление объекта из набора с конкретной позиции // Удаление объекта из набора с конкретной позиции
public boolean Remove(int position) { public boolean Remove(int position) {
if (position < 0 || position >= _places.length) // Проверка позиции
if (position < 0 || position >= _places.size())
return false; return false;
_places[position] = null; _places.remove(position);
return true; return true;
} }
// Получение объекта из набора по позиции // Получение объекта из набора по позиции
public T Get(int position) { public T Get(int position) {
if (position < 0 || position >= _places.length) // Проверка позиции
if (position < 0 || position >= _places.size())
return null; return null;
return (T)_places[position]; 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();
}
};
}
};
} }
} }

View File

@ -1,24 +1,25 @@
import java.awt.*; import java.awt.*;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
public class TanksGenericCollections<T extends DrawingArmoVehicle, U extends IMoveableObject> { public class TanksGenericCollections<T extends DrawingArmoVehicle, U extends IMoveableObject> {
// Высота и Ширина окна прорисовки // Ширина и высота окна прорисовки
private int _pictureWidth; private int _pictureWidth;
private int _pictureHeight; private int _pictureHeight;
// Размер занимаемого объектом места (ширина и высота) // Размеры занимаемого объектом места (ширина и высота)
private int _placeSizeWidth = 180; private int _placeSizeWidth = 180;
private int _placeSizeHeight = 90; private int _placeSizeHeight = 90;
// Набор объектов // Набор объектов
private SetGeneric<T> _collection; private SetGeneric<T> _collection;
// Конструктор // Конструтор
public TanksGenericCollections(int pictureWidth, int pictureHeight) { public TanksGenericCollections(int picWidth, int picHeight) {
int width = pictureWidth / _placeSizeWidth; int width = picWidth / _placeSizeWidth;
int height = pictureHeight / _placeSizeHeight; int height = picHeight / _placeSizeHeight;
_pictureWidth = pictureWidth; _pictureWidth = picWidth;
_pictureHeight = pictureHeight; _pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height); _collection = new SetGeneric<T>(width * height);
} }
@ -40,24 +41,24 @@ public class TanksGenericCollections<T extends DrawingArmoVehicle, U extends IMo
} }
// Получение объекта IMoveableObject // Получение объекта IMoveableObject
public U GetU(int pos) public U GetU(int pos) {
{ return (U) _collection.Get(pos).GetMoveableObject();
return (U)_collection.Get(pos).GetMoveableObject();
} }
// Вывод всего набора объектов // Вывод всего набора объектов
public BufferedImage ShowTanks() { public BufferedImage ShowTank() {
BufferedImage bitmap = new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB); BufferedImage bmp = new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bitmap.createGraphics(); Graphics2D g = bmp.createGraphics();
DrawBackground(g); DrawBackground(g);
DrawObjects(g); DrawObjects(g);
g.dispose(); g.dispose();
return bitmap; return bmp;
} }
// Метод отрисовки фона // Метод отрисовки фона
private void DrawBackground(Graphics g) { private void DrawBackground(Graphics g) {
g.setColor(Color.BLACK); g.setColor(Color.BLACK);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) { for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) {
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j) { for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j) {
// Линия разметки места // Линия разметки места
@ -67,16 +68,18 @@ public class TanksGenericCollections<T extends DrawingArmoVehicle, U extends IMo
} }
} }
// Метод прорисовки объектов
private void DrawObjects(Graphics g) { private void DrawObjects(Graphics g) {
for (int i = 0; i < _collection.Count; i++) { int i = 0;
T t = _collection.Get(i); for (T tank : _collection.GetTanks(100)) {
if (t != null) { if (tank != null) {
t.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight); tank.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
if (t instanceof DrawingTank) if (tank instanceof DrawingTank)
((DrawingTank) t).DrawTransport((Graphics2D)g); ((DrawingTank) tank).DrawTransport((Graphics2D) g);
else else
t.DrawTransport((Graphics2D)g); tank.DrawTransport((Graphics2D) g);
} }
i++;
} }
} }
} }

View File

@ -0,0 +1,49 @@
import java.util.*;
import java.util.stream.Collectors;
public class TanksGenericStorage {
// Словарь (как хранилище)
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);
}
}