Лабораторная 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
/shelf/
/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">
<component name="ProjectRootManager" version="2" languageLevel="JDK_20" default="true" project-jdk-name="19" project-jdk-type="JavaSDK">
<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

@ -10,7 +10,9 @@ public class DrawingArmoVehicle {
protected int _startPosY;
protected int _TankWidth = 160;
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) {
_pictureWidth = width;
@ -52,10 +54,21 @@ public class DrawingArmoVehicle {
_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 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) {
@ -104,11 +117,10 @@ public class DrawingArmoVehicle {
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;
int nPoints = 4;
g.drawPolygon(xPoints, yPoints, nPoints);
g.fillPolygon(xPoints, yPoints, nPoints);

View File

@ -4,7 +4,6 @@ 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);
@ -20,47 +19,45 @@ public class DrawingTank extends DrawingArmoVehicle {
return;
}
// Установка позиции
public void SetPosition(int x, int y) {
_startPosX = Math.min(x, _pictureWidth - _TankWidth);
_startPosY = Math.min(y, _pictureHeight - _TankHeight);
}
private boolean setOrnamentAdd() { return OrnamentAdd; }
private boolean setOrnamentAdd() {
return OrnamentAdd;
}
// Прорисовка объекта
public void DrawTransport(Graphics2D g) {
if (ArmoVehicle == null) {
return;
}
super.DrawTransport(g);
if (((EntityTank) ArmoVehicle).BodyKit) {
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 = xPointsBody.length;
int nPointsBody = 11;
g.drawPolygon(xPointsBody, yPointsBody, nPointsBody);
g.fillPolygon(xPointsBody, yPointsBody, nPointsBody);
}
if (((EntityTank) ArmoVehicle).Caterpillar) {
Color Gray = new Color(128, 128, 128);
g.setColor(Gray);
// Гусеница
g.drawOval(_startPosX + 10, _startPosY + 30, 120, 30);
}
if (((EntityTank) ArmoVehicle).Tower) {
g.setColor(Color.DARK_GRAY);
// Орудие
g.drawRect(_startPosX + 112, _startPosY + 17, 60, 5);
g.fillRect(_startPosX + 112, _startPosY + 17, 60, 5);
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 = xPointsGun.length;
int nPointsGun = 11;
g.fillRect(_startPosX + 50, _startPosY + 5, 20, 2);
g.drawPolygon(xPointsGun, yPointsGun, nPointsGun);

View File

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

View File

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

View File

@ -1,44 +1,84 @@
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.util.LinkedList;
import java.util.Queue;
public class FormTankCollection {
private class Canvas extends JComponent {
public TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank> _tank;
public Canvas() {
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (_tank.ShowTanks() != null) {
g.drawImage(_tank.ShowTanks(), 0, 10, this);
if (jListStorage.getSelectedIndex() == -1) {
return;
}
var obj = _storage.get(jListStorage.getSelectedValue());
if (obj == null) {
return;
}
if (obj.ShowTank() != null) {
g.drawImage(obj.ShowTank(), 0, 0, this);
}
super.repaint();
}
}
Canvas canv;
static int pictureBoxWidth = 700;
static int pictureBoxHeight = 480;
private TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank> _tank;
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 ("TanksCollecltion");
_tank = new TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank>(pictureBoxWidth, pictureBoxHeight);
canv._tank = _tank;
JFrame Frame = new JFrame("TankCollecltion");
_storage = new TanksGenericStorage(pictureBoxWidth, pictureBoxHeight);
JButton ButtonAddTank = new JButton("Добавить технику");
ButtonAddTank.addActionListener(
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;
}
FormTank form = new FormTank();
form.buttonSelectTank.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (_tank.Add(form._drawingVehicle) != -1) {
if (obj.Add(form._drawingVehicle) != -1) {
JOptionPane.showMessageDialog(null, "Объект добавлен", "Информация", JOptionPane.INFORMATION_MESSAGE);
Draw();
} else {
@ -52,11 +92,21 @@ public class FormTankCollection {
}
);
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;
}
@ -71,7 +121,9 @@ public class FormTankCollection {
}
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);
Draw();
} else {
@ -81,6 +133,22 @@ 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("Обновить коллекцию");
ButtonRefreshCollection.addActionListener(
new ActionListener() {
@ -90,8 +158,8 @@ public class FormTankCollection {
}
);
JButton toFormTankGenerate = new JButton("Генерировать технику");
toFormTankGenerate.addActionListener(
JButton toForm4GenericDopClass = new JButton("Генерация");
toForm4GenericDopClass.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
FormTankGenerate formTankGenerate = new FormTankGenerate();
@ -99,21 +167,76 @@ public class FormTankCollection {
}
);
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();
}
}
);
Frame.setSize(880, 520);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.setLayout(null);
canv.setBounds(0, 0, pictureBoxWidth, pictureBoxHeight);
ButtonAddTank.setBounds(pictureBoxWidth - 50, 10, 170, 30);
TextBoxNumber.setBounds(pictureBoxWidth - 50, 50, 170, 20);
ButtonRemoveTank.setBounds(pictureBoxWidth - 50, 80, 170, 30);
ButtonRefreshCollection.setBounds(pictureBoxWidth - 50, 120, 170, 30);
toFormTankGenerate.setBounds(pictureBoxWidth - 50, 160, 170, 30);
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);
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(ButtonAddTank);
Frame.add(ButtonAddVehicle);
Frame.add(ButtonRemoveTank);
Frame.add(ButtonRefreshCollection);
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);
}
}

View File

@ -1,61 +1,89 @@
public class SetGeneric<T extends DrawingArmoVehicle> {
// Массив объектов, которые храним
private Object[] _places;
import java.util.*;
public class SetGeneric <T extends Object> {
// Массив объектов, которые храним
private final ArrayList<T> _places;
// Количество объектов в массиве
public int Count;
public int Count() { return _places.size(); }
// Максимальное количество объектов в списке
private final int _maxCount;
// Конструктор
public SetGeneric(int count) {
_places = new Object[count];
Count = _places.length;
_maxCount = count;
_places = new ArrayList<T>(count);
}
// Добавление объекта в набор
// Добавление объектов в набор
public int Insert(T tank) {
int i = 0;
for (; i < _places.length; i++) {
if (_places[i] == null)
break;
}
if (i == _places.length)
if(_places.size() >= _maxCount)
return -1;
for (; i > 0; i--) {
_places[i] = _places[i - 1];
}
_places[i] = tank;
return i;
_places.add(0,tank);
return 0;
}
// Добавление объекта в набор на конкретную позицию
public boolean Insert(T tank, int position) {
if (position < 0 || position >= _places.length)
// Проверка позиции
if (position < 0 || position > _places.size())
return false;
for (; position < _places.length; position++) {
if (_places[position] == null)
break;
}
if (position == _places.length)
if (_places.size() >= _maxCount)
return false;
for (; position > 0; position--) {
_places[position] = _places[position - 1];
}
_places[position] = tank;
if (position == _places.size())
_places.add(tank);
else
_places.add(position, tank);
return true;
}
// Удаление объекта из набора с конкретной позиции
public boolean Remove(int position) {
if (position < 0 || position >= _places.length)
// Проверка позиции
if (position < 0 || position >= _places.size())
return false;
_places[position] = null;
_places.remove(position);
return true;
}
// Получение объекта из набора по позиции
public T Get(int position) {
if (position < 0 || position >= _places.length)
// Проверка позиции
if (position < 0 || position >= _places.size())
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.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 TanksGenericCollections(int pictureWidth, int pictureHeight) {
int width = pictureWidth / _placeSizeWidth;
int height = pictureHeight / _placeSizeHeight;
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
// Конструтор
public TanksGenericCollections(int picWidth, int picHeight) {
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height);
}
@ -40,24 +41,24 @@ public class TanksGenericCollections<T extends DrawingArmoVehicle, U extends IMo
}
// Получение объекта IMoveableObject
public U GetU(int pos)
{
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();
public BufferedImage ShowTank() {
BufferedImage bmp = new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bmp.createGraphics();
DrawBackground(g);
DrawObjects(g);
g.dispose();
return bitmap;
return bmp;
}
// Метод отрисовки фона
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) {
// Линия разметки места
@ -67,16 +68,18 @@ public class TanksGenericCollections<T extends DrawingArmoVehicle, U extends IMo
}
}
// Метод прорисовки объектов
private void DrawObjects(Graphics g) {
for (int i = 0; i < _collection.Count; i++) {
T t = _collection.Get(i);
if (t != null) {
t.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
if (t instanceof DrawingTank)
((DrawingTank) t).DrawTransport((Graphics2D)g);
int i = 0;
for (T tank : _collection.GetTanks(100)) {
if (tank != null) {
tank.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
if (tank instanceof DrawingTank)
((DrawingTank) tank).DrawTransport((Graphics2D) g);
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);
}
}