Compare commits

...

10 Commits

Author SHA1 Message Date
1f5fa9eb6f лаб6 2024-05-12 15:30:17 +04:00
ef26efb807 Merge branch 'LabWork05' into LabWork04 2024-05-12 13:08:57 +04:00
8fd3691dd4 лаб5 2024-04-28 15:44:48 +04:00
4ea097cdb5 лаб4 2024-04-28 13:45:08 +04:00
5f3ecf6c51 лаб3.2 2024-04-27 17:38:24 +04:00
029dcb4e42 лаб3 2024-04-27 17:00:36 +04:00
78392f4692 лаб2 2024-03-31 22:44:49 +04:00
51864f5752 Правки 2024-03-07 17:53:06 +04:00
f13d7a60f8 Правки 2024-03-07 17:47:15 +04:00
4937e3672f Сделано, но не до конца проверено 2024-03-03 21:47:04 +04:00
39 changed files with 2683 additions and 1 deletions

View File

@ -0,0 +1,124 @@
<?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.

After

Width:  |  Height:  |  Size: 857 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 800 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 786 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 453 B

View File

@ -0,0 +1,29 @@
import javax.swing.*;
import CollectionGenericObjects.AbstractCompany;
import Drawnings.DrawingBaseStormtrooper;
import java.awt.*;
public class CanvasFormStormtrooperCollection<T> extends JComponent {
public AbstractCompany company = null;
public void SetCollectionToCanvas(AbstractCompany company) {
this.company = company;
}
public CanvasFormStormtrooperCollection() {};
public void paintComponent(Graphics g) {
super.paintComponents(g);
if (company == null || company._collection == null) {
return;
}
company.DrawBackgound(g);
for (int i = 0; i < company._collection.getCount(); i++) {
Graphics2D g2d = (Graphics2D) g;
T obj = (T) company._collection.Get(i);
if (obj instanceof DrawingBaseStormtrooper) {
((DrawingBaseStormtrooper) obj).DrawTransport(g2d);
}
}
super.repaint();
}
}

View File

@ -0,0 +1,18 @@
import Drawnings.DrawingBaseStormtrooper;
import javax.swing.*;
import java.awt.*;
public class CanvasStormtrooper extends JComponent {
public DrawingBaseStormtrooper _drawingBaseStormtrooper;
public CanvasStormtrooper(){}
public void paintComponent(Graphics g) {
if (_drawingBaseStormtrooper == null) {
return;
}
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
_drawingBaseStormtrooper.DrawTransport(g2d);
super.repaint();
}
}

View File

@ -0,0 +1,34 @@
package CollectionGenericObjects;
import Drawnings.DrawingBaseStormtrooper;
import java.awt.*;
public abstract class AbstractCompany {
protected int _placeSizeWidth = 220;
protected int _placeSizeHeight = 155;
protected int _pictureWidth;
protected int _pictureHeight;
public ICollectionGenericObjects<DrawingBaseStormtrooper> _collection = null;
private int GetMaxCount() {
return _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight);
}
public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects<DrawingBaseStormtrooper> collection)
{
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount(GetMaxCount());
}
//Перегрузок нет
public DrawingBaseStormtrooper GetRandomObject()
{
return _collection.Get((int)(Math.random()*GetMaxCount() + 0));
}
public void SetPosition()
{
SetObjectsPosition();
}
public abstract void DrawBackgound(Graphics graphics);
protected abstract void SetObjectsPosition();
}

View File

@ -0,0 +1,60 @@
package CollectionGenericObjects;
import Drawnings.DrawingBaseStormtrooper;
import Drawnings.DrawingStormtrooper;
import Drawnings.Engines.IDrawingEngines;
import Entities.EntityBaseStormtrooper;
import Entities.EntityStormtrooper;
import java.lang.reflect.Array;
import java.util.Random;
public class AdditionalCollection <T extends EntityBaseStormtrooper, U extends IDrawingEngines>{
public T[] _collectionEntity;
public U[] _collectionEngines;
public AdditionalCollection(int size, Class<T> type1, Class<T> type2) {
_collectionEntity = (T[]) Array.newInstance(type1, size);
_collectionEngines = (U[]) Array.newInstance(type2, size);
CountEntities = size;
CountEngines = size;
}
public int CountEntities;
public int CountEngines;
public int Insert(T entity) {
int index = 0;
while (index < CountEntities) {
if (_collectionEntity[index] == null)
{
_collectionEntity[index] = entity;
return index;
}
++index;
}
return -1;
}
public int Insert(U decks) {
int index = 0;
while (index < CountEngines) {
if (_collectionEngines[index] == null)
{
_collectionEngines[index] = decks;
return index;
}
++index;
}
return -1;
}
public DrawingBaseStormtrooper CreateAdditionalCollectionStormtrooper() {
Random random = new Random();
if (_collectionEntity == null || _collectionEngines == null) return null;
T entity = _collectionEntity[random.nextInt(CountEntities)];
U engines = _collectionEngines[random.nextInt(CountEngines)];
DrawingBaseStormtrooper drawingBaseStormtrooper = null;
if (entity instanceof EntityStormtrooper) {
drawingBaseStormtrooper = new DrawingStormtrooper((EntityStormtrooper) entity, engines);
}
else {
drawingBaseStormtrooper = new DrawingBaseStormtrooper(entity, engines);
}
return drawingBaseStormtrooper;
}
}

View File

@ -0,0 +1,7 @@
package CollectionGenericObjects;
public enum CollectionType {
None,
Massive,
List
}

View File

@ -0,0 +1,14 @@
package CollectionGenericObjects;
public interface ICollectionGenericObjects<T>
{
int getCount();
void SetMaxCount(int count);
int Insert(T obj);
T Remove(int position);
T Get(int position);
CollectionType GetCollectionType();
Iterable<T> GetItems();
void ClearCollection();
}

View File

@ -0,0 +1,76 @@
package CollectionGenericObjects;
import java.util.*;
public class ListGenericObjects<T> implements ICollectionGenericObjects<T> {
private List<T> _collection;
private CollectionType collectionType = CollectionType.List;
private int _maxCount;
public int getCount() {
return _collection.size();
}
@Override
public void SetMaxCount(int size) {
if (size > 0) {
_maxCount = size;
}
}
public ListGenericObjects() {
_collection = new ArrayList<T>();
}
@Override
public CollectionType GetCollectionType() {
return collectionType;
}
@Override
public T Get(int position)
{
if (position >= getCount() || position < 0) return null;
return _collection.get(position);
}
@Override
public int Insert(T obj)
{
if (getCount() == _maxCount) return -1;
_collection.add(obj);
return getCount();
}
@Override
public T Remove(int position)
{
if (position >= getCount() || position < 0) return null;
T obj = _collection.get(position);
_collection.remove(position);
return obj;
}
@Override
public Iterable<T> GetItems() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
//нужен ли count
private int count = 0;
@Override
public boolean hasNext() {
return currentIndex < getCount();
}
@Override
public T next() {
if (hasNext()) {
count++;
return _collection.get(currentIndex++);
}
throw new NoSuchElementException();
}
};
}
};
}
@Override
public void ClearCollection() {
for (T stormtrooper : _collection) {
stormtrooper = null;
}
}
}

View File

@ -0,0 +1,87 @@
package CollectionGenericObjects;
import Drawnings.DrawingBaseStormtrooper;
import java.lang.reflect.Array;
import java.util.*;
public class MassiveGenericObjects<T> implements ICollectionGenericObjects<T>{
private T[] _collection = null;
private CollectionType collectionType = CollectionType.Massive;
private int Count;
public void SetMaxCount(int size) {
if (size > 0) {
if (_collection == null) {
_collection = (T[]) Array.newInstance((Class) DrawingBaseStormtrooper.class, size);
Count = size;
}
}
}
@Override
public CollectionType GetCollectionType() {
return collectionType;
}
@Override
public int getCount() {
return Count;
}
@Override
public int Insert(T obj) {
int index = 0;
while (index < getCount())
{
if (_collection[index] == null)
{
_collection[index] = obj;
return index;
}
++index;
}
return -1;
}
@Override
public T Remove(int position) {
if (position >= getCount() || position < 0)
return null;
T obj = (T) _collection[position];
_collection[position] = null;
return obj;
}
@Override
public T Get(int position) {
if (position >= getCount() || position < 0) return null;
return (T) _collection[position];
}
@Override
public Iterable<T> GetItems() {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentIndex = 0;
//нужен ли count
private int count = 0;
@Override
public boolean hasNext() {
return currentIndex < getCount();
}
@Override
public T next() {
if (hasNext()) {
count++;
return _collection[currentIndex++];
}
throw new NoSuchElementException();
}
};
}
};
}
@Override
public void ClearCollection() {
for (T stormtrooper : _collection) {
stormtrooper = null;
}
}
}

View File

@ -0,0 +1,192 @@
package CollectionGenericObjects;
import Drawnings.DrawingBaseStormtrooper;
import Drawnings.ExtentionDrawingBaseStormtrooper;
import java.util.*;
import java.io.*;
public class StorageCollection<T extends DrawingBaseStormtrooper> {
private Map<String, ICollectionGenericObjects<T>> _storages;
public StorageCollection()
{
_storages = new HashMap<String, ICollectionGenericObjects<T>>();
}
public Set<String> Keys() {
Set<String> keys = _storages.keySet();
return keys;
}
public void AddCollection(String name, CollectionType collectionType)
{
if (_storages.containsKey(name)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages.put(name, new MassiveGenericObjects<T>());
else if (collectionType == CollectionType.List)
_storages.put(name, new ListGenericObjects<T>());
}
public void DelCollection(String name)
{
if (_storages.containsKey(name))
_storages.remove(name);
}
public ICollectionGenericObjects<T> getCollectionObject(String name) {
if (_storages.containsKey(name))
return _storages.get(name);
return null;
}
public T remove(String name, int position){
if(_storages.containsKey(name))
return _storages.get(name).Remove(position);
return null;
}
private String _collectionKey = "CollectionsStorage";
private String _collectionName = "StorageCollection";
private String _separatorForKeyValueS = "|";
private String _separatorForKeyValue = "\\|";
private String _separatorItemsS = ";";
private String _separatorItems = "\\;";
public boolean SaveData(String filename) {
if (_storages.isEmpty()) return false;
File file = new File(filename);
if (file.exists()) file.delete();
try {
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(_collectionKey);
writer.write("\n");
for (Map.Entry<String, ICollectionGenericObjects<T>> value : _storages.entrySet()) {
StringBuilder sb = new StringBuilder();
sb.append(value.getKey());
sb.append(_separatorForKeyValueS);
sb.append(value.getValue().GetCollectionType());
sb.append(_separatorForKeyValueS);
sb.append(value.getValue().getCount());
sb.append(_separatorForKeyValueS);
for (T stormtrooper : value.getValue().GetItems()) {
String data = ExtentionDrawingBaseStormtrooper.GetDataForSave((DrawingBaseStormtrooper) stormtrooper);
if (data.isEmpty()) continue;
sb.append(data);
sb.append(_separatorItemsS);
}
sb.append("\n");
writer.write(String.valueOf(sb));
}
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
public boolean SaveOneCollection(String filename, String name) {
if (_storages.isEmpty()) return false;
File file = new File(filename);
if (file.exists()) file.delete();
try {
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(_collectionName);
writer.write("\n");
ICollectionGenericObjects<T> value = _storages.get(name);
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append(_separatorForKeyValueS);
sb.append(value.GetCollectionType());
sb.append(_separatorForKeyValueS);
sb.append(value.getCount());
sb.append(_separatorForKeyValueS);
for (T stormtrooper : value.GetItems()) {
String data = ExtentionDrawingBaseStormtrooper.GetDataForSave((DrawingBaseStormtrooper) stormtrooper);
if (data.isEmpty()) continue;
sb.append(data);
sb.append(_separatorItemsS);
}
writer.append(sb);
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
public boolean LoadData(String filename) {
File file = new File(filename);
if (!file.exists()) return false;
try (BufferedReader fs = new BufferedReader(new FileReader(filename))) {
String s = fs.readLine();
if (s == null || s.isEmpty() || !s.startsWith(_collectionKey))
return false;
_storages.clear();
s = "";
while ((s = fs.readLine()) != null) {
String[] record = s.split(_separatorForKeyValue);
if (record.length != 4) {
continue;
}
ICollectionGenericObjects<T> collection = CreateCollection(record[1]);
if (collection == null)
{
return false;
}
collection.SetMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems);
for (String elem : set) {
DrawingBaseStormtrooper stormtrooper = ExtentionDrawingBaseStormtrooper.CreateDrawingBaseStomrtrooper(elem);
if (collection.Insert((T) stormtrooper) == -1)
{
return false;
}
}
_storages.put(record[0], collection);
}
return true;
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean LoadOneCollection(String filename) {
File file = new File(filename);
if (!file.exists()) return false;
try (BufferedReader fs = new BufferedReader(new FileReader(filename))) {
String s = fs.readLine();
if (s == null || s.isEmpty() || !s.startsWith(_collectionName))
return false;
if (_storages.containsKey(s)) {
_storages.get(s).ClearCollection();
}
s = fs.readLine();
String[] record = s.split(_separatorForKeyValue);
if (record.length != 4) {
return false;
}
ICollectionGenericObjects<T> collection = CreateCollection(record[1]);
if (collection == null)
{
return false;
}
collection.SetMaxCount(Integer.parseInt(record[2]));
String[] set = record[3].split(_separatorItems);
for (String elem : set) {
DrawingBaseStormtrooper stormtrooper = ExtentionDrawingBaseStormtrooper.CreateDrawingBaseStomrtrooper(elem);
if (collection.Insert((T) stormtrooper) == -1)
{
return false;
}
}
_storages.put(record[0], collection);
return true;
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
public ICollectionGenericObjects<T> CreateCollection(String s) {
switch (s) {
case "Massive":
return new MassiveGenericObjects<T>();
case "List":
return new ListGenericObjects<T>();
}
return null;
}
}

View File

@ -0,0 +1,49 @@
package CollectionGenericObjects;
import Drawnings.DrawingBaseStormtrooper;
import java.awt.*;
public class StormtrooperSharingService extends AbstractCompany{
public StormtrooperSharingService (int picWidth, int picHeight, ICollectionGenericObjects<DrawingBaseStormtrooper> collection) {
super(picWidth, picHeight, collection);
}
@Override
public void DrawBackgound(Graphics g) {
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
g.setColor(Color.BLACK);
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height + 1; ++j)
{
g.drawLine(i * _placeSizeWidth+15, j * _placeSizeHeight, i * _placeSizeWidth+15 + _placeSizeWidth-55, j * _placeSizeHeight);
g.drawLine(i * _placeSizeWidth+15, j * _placeSizeHeight, i * _placeSizeWidth+15, j * _placeSizeHeight -_placeSizeHeight);
}
}
}
@Override
protected void SetObjectsPosition() {
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int curWidth = width - 4;
int curHeight = 0;
for (int i = 0; i < (_collection.getCount()); i++) {
if (_collection.Get(i) != null) {
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 16, curHeight * _placeSizeHeight + 3);
}
if (curWidth < width-1)
curWidth++;
else
{
curWidth = 0;
curHeight++;
}
if (curHeight > height)
{
return;
}
}
}
}

View File

@ -0,0 +1,9 @@
package Drawnings;
public enum DirectionType {
Unknow,
Up,
Down,
Left,
Right
}

View File

@ -0,0 +1,155 @@
package Drawnings;
import Drawnings.Engines.DrawingEngines;
import Drawnings.Engines.DrawingOvalEngines;
import Drawnings.Engines.DrawingTriangleEngines;
import Drawnings.Engines.IDrawingEngines;
import Entities.*;
import java.awt.*;
public class DrawingBaseStormtrooper {
public EntityBaseStormtrooper EntityBaseStormtrooper;
public IDrawingEngines drawingEngines =null;
protected Integer _pictureWidth;
protected Integer _pictureHeight;
protected Integer _startPosX;
protected Integer _startPosY;
public Integer getPosX(){return _startPosX;}
public Integer getPosY(){return _startPosY;}
private Integer _drawningStormtrooperWidth = 140;
public Integer getWidth(){return _drawningStormtrooperWidth;}
private Integer _drawningStormtrooperHeight = 135;
public Integer getHeight(){return _drawningStormtrooperHeight;}
protected DrawingBaseStormtrooper(){
_pictureWidth=null;
_pictureHeight=null;
_startPosX=null;
_startPosY=null;
}
public DrawingBaseStormtrooper(int speed, float weight, Color bodyColor) {
super();
EntityBaseStormtrooper = new EntityBaseStormtrooper(speed, weight, bodyColor);
}
public DrawingBaseStormtrooper(EntityBaseStormtrooper entityBaseStormtrooper, IDrawingEngines drawingEngines){
this.EntityBaseStormtrooper = entityBaseStormtrooper;
this.drawingEngines = drawingEngines;
}
public boolean SetPictureSize(int width, int height) {
// TODO проверка, что объект "влезает" в размеры поля
// если влезает, сохраняем границы и корректируем позицию объекта, если она была уже установлена
if (width < _drawningStormtrooperWidth || height < _drawningStormtrooperHeight) return false;
_pictureWidth = width;
_pictureHeight = height;
if (_startPosX != null || _startPosY != null) {
if (_startPosX + _drawningStormtrooperWidth > _pictureWidth) {
_startPosX = -_drawningStormtrooperWidth + _pictureWidth;
} else if (_startPosX < 0) {
_startPosX = 0;
}
if (_startPosY + _drawningStormtrooperHeight > _pictureHeight) {
_startPosY = -_drawningStormtrooperHeight + _pictureHeight;
} else if (_startPosY < 0) {
_startPosY = 0;
}
}
return true;
}
public void SetPosition(int x, int y) {
if (!(_pictureHeight != null && _pictureWidth != null)) return;
// TODO если при установке объекта в эти координаты, он будет "выходить" за границы формы
// то надо изменить координаты, чтобы он оставался в этих границах
if (x + _drawningStormtrooperWidth > _pictureWidth) {
_startPosX = x - (x + _drawningStormtrooperWidth - _pictureWidth);
} else if (x < 0) {
_startPosX = 0;
} else {
_startPosX = x;
}
if (y + _drawningStormtrooperHeight > _pictureHeight) {
_startPosY = y - (y + _drawningStormtrooperHeight - _pictureHeight);
} else if (y < 0) {
_startPosY = 0;
} else {
_startPosY = y;
}
}
public boolean MoveTransport(DirectionType direction) {
if (EntityBaseStormtrooper == null || _startPosX == null || _startPosY == null) {
return false;
}
switch (direction) {
//влево
case DirectionType.Left:
if (_startPosX - EntityBaseStormtrooper.Step > 0) {
_startPosX -= (int) EntityBaseStormtrooper.Step;
}
return true;
//вверх
case DirectionType.Up:
if (_startPosY - EntityBaseStormtrooper.Step > 0) {
_startPosY -= (int) EntityBaseStormtrooper.Step;
}
return true;
// вправо
case DirectionType.Right:
//TODO прописать логику сдвига в право
if (_startPosX + _drawningStormtrooperWidth + EntityBaseStormtrooper.Step < _pictureWidth) {
_startPosX += (int) EntityBaseStormtrooper.Step;
}
return true;
//вниз
case DirectionType.Down:
//TODO прописать логику сдвига в вниз
if (_startPosY + _drawningStormtrooperHeight + EntityBaseStormtrooper.Step < _pictureHeight) {
_startPosY += (int) EntityBaseStormtrooper.Step;
}
return true;
default:
return false;
}
}
public void DrawTransport(Graphics g) {
if (EntityBaseStormtrooper == null || _startPosX == null || _startPosY == null) {
return;
}
g.setColor(Color.black);
//Тело бомбардировщика
g.drawRect(_startPosX + 20, _startPosY + 60, 120, 20);
//Задние крылья бомбардировщика
g.drawLine(_startPosX + 140, _startPosY + 30, _startPosX + 140, _startPosY + 110);
g.drawLine(_startPosX + 120, _startPosY + 90, _startPosX + 120, _startPosY + 80);
g.drawLine(_startPosX + 140, _startPosY + 110, _startPosX + 120, _startPosY + 90);
g.drawLine(_startPosX + 140, _startPosY + 30, _startPosX + 120, _startPosY + 50);
g.drawLine(_startPosX + 120, _startPosY + 50, _startPosX + 120, _startPosY + 60);
//Крылья бомбардировщика
g.drawLine(_startPosX + 50, _startPosY, _startPosX + 50, _startPosY + 60);
g.drawLine(_startPosX + 50, _startPosY + 80, _startPosX + 50, _startPosY + 135);
g.drawLine(_startPosX + 50, _startPosY + 135, _startPosX + 60, _startPosY + 135);
g.drawLine(_startPosX + 60, _startPosY + 135, _startPosX + 65, _startPosY + 80);
g.drawLine(_startPosX + 50, _startPosY, _startPosX + 60, _startPosY);
g.drawLine(_startPosX + 60, _startPosY, _startPosX + 65, _startPosY + 60);
///Нос бомбардировщика
g.setColor(EntityBaseStormtrooper.getBodyColor());
Point[] Nose = new Point[3];
int[] arrX = {_startPosX + 20, _startPosX, _startPosX + 20};
int[] arrY = {_startPosY + 80, _startPosY + 70, _startPosY + 60};
Polygon poly = new Polygon(arrX, arrY, 3);
g.fillPolygon(poly);
}
public String[] GetStringRepresentationDecks() {
if (drawingEngines instanceof DrawingEngines) {
return new String[]{String.valueOf(drawingEngines.getNumberOfEngines()), "DrawingEngines"};
}
else if (drawingEngines instanceof DrawingOvalEngines) {
return new String[]{String.valueOf(drawingEngines.getNumberOfEngines()), "DrawingOvalEngines"};
}
else if (drawingEngines instanceof DrawingTriangleEngines) {
return new String[]{String.valueOf(drawingEngines.getNumberOfEngines()), "DrawingTriangleEngines"};
}
return null;
}
}

View File

@ -0,0 +1,50 @@
package Drawnings;
import Drawnings.Engines.DrawingEngines;
import Drawnings.Engines.DrawingOvalEngines;
import Drawnings.Engines.DrawingTriangleEngines;
import Drawnings.Engines.IDrawingEngines;
import Entities.*;
import java.awt.*;
public class DrawingStormtrooper extends DrawingBaseStormtrooper{
public DrawingStormtrooper(int speed, float weight, Color bodyColor, Color additionalColor,boolean rockets, boolean bombs, boolean engines) {
EntityBaseStormtrooper = new EntityStormtrooper(speed, weight, bodyColor, additionalColor, rockets, bombs, engines);
_startPosX=null;
_startPosY=null;
_pictureWidth = null;
_pictureHeight = null;
}
public DrawingStormtrooper(EntityStormtrooper entityStormtrooper, IDrawingEngines drawingEngines){
this.EntityBaseStormtrooper=entityStormtrooper;
this.drawingEngines = drawingEngines;
}
@Override
public void DrawTransport(Graphics g)
{
if (EntityBaseStormtrooper == null ||!(EntityBaseStormtrooper instanceof EntityStormtrooper entityStormtrooper) || _startPosX==null || _startPosY==null)
{
return;
}
super.DrawTransport(g);
//Ракеты бомбардировщика
if (entityStormtrooper.getRockets())
{
g.setColor(entityStormtrooper.getAdditionalColor());
g.setColor(entityStormtrooper.getAdditionalColor());
g.fillRect( _startPosX + 35, _startPosY + 20, 15, 5);
g.fillRect( _startPosX + 35, _startPosY + 110, 15, 5);
}
//Бомбы бомбардировщика
if (entityStormtrooper.getBombs())
{
g.setColor(entityStormtrooper.getAdditionalColor());
g.fillRect(_startPosX + 40, _startPosY + 40, 10, 10);
g.fillRect(_startPosX + 40, _startPosY + 90, 10, 10);
}
if(entityStormtrooper.getEngines() && drawingEngines!=null){
drawingEngines.SwitchDrawEngines(g, _startPosX, _startPosY, EntityBaseStormtrooper.getBodyColor());
}
}
}

View File

@ -0,0 +1,57 @@
package Drawnings.Engines;
import java.awt.*;
public class DrawingEngines implements IDrawingEngines {
private NumberOfEngines numberOfEngines;
@Override
public NumberOfEngines getNumberOfEngines() {
return numberOfEngines;
}
@Override
public void setAmountOfEngines(int amount){
if(NumberOfEngines.contains(amount)) {
numberOfEngines = NumberOfEngines.getNumber(amount);
}
}
@Override
public int getNumberFromString(String numberString){
NumberOfEngines number = NumberOfEngines.valueOf(numberString);
return number.getNumber();
}
@Override
public void DrawEngines(Graphics g, int x, int y, Color bodyColor) {
g.setColor(bodyColor);
g.fillRect(x, y, 10, 10);
}
@Override
public void drawTwoEngines(Graphics g, int x, int y, Color bodyColor){
DrawEngines(g,x + 65, y + 50, bodyColor);
DrawEngines(g,x + 65, y + 81,bodyColor);
}
@Override
public void drawFourEngines(Graphics g, int x, int y, Color bodyColor){
DrawEngines(g,x + 62, y + 10,bodyColor);
DrawEngines(g,x + 64, y + 101,bodyColor);
DrawEngines(g,x + 64, y + 30,bodyColor);
DrawEngines(g,x + 62, y + 121,bodyColor);
}
@Override
public void drawSixEngines(Graphics g, int x, int y, Color bodyColor){
drawFourEngines(g,x,y,bodyColor);
drawTwoEngines(g,x,y,bodyColor);
}
@Override
public void SwitchDrawEngines(Graphics g, int x, int y, Color bodyColor){
switch(getNumberOfEngines()){
case NumberOfEngines.TWO:
drawTwoEngines(g,x,y,bodyColor);
break;
case NumberOfEngines.FOUR:
drawFourEngines(g,x,y,bodyColor);
break;
case NumberOfEngines.SIX:
drawSixEngines(g,x,y,bodyColor);
break;
}
}
}

View File

@ -0,0 +1,58 @@
package Drawnings.Engines;
import java.awt.*;
public class DrawingOvalEngines implements IDrawingEngines {
private NumberOfEngines numberOfEngines;
@Override
public NumberOfEngines getNumberOfEngines() {
return numberOfEngines;
}
@Override
public void setAmountOfEngines(int amount){
if(NumberOfEngines.contains(amount)) {
numberOfEngines = NumberOfEngines.getNumber(amount);
}
}
@Override
public int getNumberFromString(String numberString){
NumberOfEngines number = NumberOfEngines.valueOf(numberString);
return number.getNumber();
}
@Override
public void DrawEngines(Graphics g, int x, int y, Color bodyColor) {
g.setColor(bodyColor);
g.fillOval(x, y, 10, 10);
}
@Override
public void drawTwoEngines(Graphics g, int x, int y, Color bodyColor){
DrawEngines(g,x + 65, y + 50, bodyColor);
DrawEngines(g,x + 65, y + 81,bodyColor);
}
public @Override
void drawFourEngines(Graphics g, int x, int y, Color bodyColor){
DrawEngines(g,x + 62, y + 10,bodyColor);
DrawEngines(g,x + 64, y + 101,bodyColor);
DrawEngines(g,x + 64, y + 30,bodyColor);
DrawEngines(g,x + 62, y + 121,bodyColor);
}
@Override
public void drawSixEngines(Graphics g, int x, int y, Color bodyColor){
drawFourEngines(g,x,y,bodyColor);
drawTwoEngines(g,x,y,bodyColor);
}
@Override
public void SwitchDrawEngines(Graphics g, int x, int y, Color bodyColor){
switch(getNumberOfEngines()){
case NumberOfEngines.TWO:
drawTwoEngines(g,x,y,bodyColor);
break;
case NumberOfEngines.FOUR:
drawFourEngines(g,x,y,bodyColor);
break;
case NumberOfEngines.SIX:
drawSixEngines(g,x,y,bodyColor);
break;
}
}
}

View File

@ -0,0 +1,63 @@
package Drawnings.Engines;
import java.awt.*;
public class DrawingTriangleEngines implements IDrawingEngines {
private NumberOfEngines numberOfEngines;
@Override
public NumberOfEngines getNumberOfEngines() {
return numberOfEngines;
}
@Override
public void setAmountOfEngines(int amount){
if(NumberOfEngines.contains(amount)) {
numberOfEngines = NumberOfEngines.getNumber(amount);
}
}
@Override
public int getNumberFromString(String numberString){
NumberOfEngines number = NumberOfEngines.valueOf(numberString);
return number.getNumber();
}
@Override
public void DrawEngines(Graphics g, int x, int y, Color bodyColor) {
g.setColor(bodyColor);
Point[] Nose = new Point[3];
int[] arrX = {x,x,x+10};
int[] arrY = {y,y+12,y+6};
Polygon poly = new Polygon(arrX, arrY, 3);
g.fillPolygon(poly);
}
@Override
public void drawTwoEngines(Graphics g, int x, int y, Color bodyColor){
DrawEngines(g,x + 65, y + 50, bodyColor);
DrawEngines(g,x + 65, y + 81,bodyColor);
}
public @Override
void drawFourEngines(Graphics g, int x, int y, Color bodyColor){
DrawEngines(g,x + 62, y + 10,bodyColor);
DrawEngines(g,x + 64, y + 101,bodyColor);
DrawEngines(g,x + 64, y + 30,bodyColor);
DrawEngines(g,x + 62, y + 121,bodyColor);
}
@Override
public void drawSixEngines(Graphics g, int x, int y, Color bodyColor){
drawFourEngines(g,x,y,bodyColor);
drawTwoEngines(g,x,y,bodyColor);
}
public void SwitchDrawEngines(Graphics g, int x, int y, Color bodyColor){
switch(getNumberOfEngines()){
case NumberOfEngines.TWO:
drawTwoEngines(g,x,y,bodyColor);
break;
case NumberOfEngines.FOUR:
drawFourEngines(g,x,y,bodyColor);
break;
case NumberOfEngines.SIX:
drawSixEngines(g,x,y,bodyColor);
break;
}
}
}

View File

@ -0,0 +1,18 @@
package Drawnings.Engines;
import java.awt.*;
public interface IDrawingEngines {
void setAmountOfEngines(int amount);
int getNumberFromString(String numberString);
NumberOfEngines getNumberOfEngines();
void DrawEngines(Graphics g, int x, int y, Color bodyColor);
void drawTwoEngines(Graphics g, int x, int y, Color bodyColor);
void drawFourEngines(Graphics g, int x, int y, Color bodyColor);
void drawSixEngines(Graphics g, int x, int y, Color bodyColor);
void SwitchDrawEngines(Graphics g, int startPosX, int startPosY, Color bodyColor);
}

View File

@ -0,0 +1,35 @@
package Drawnings.Engines;
public enum NumberOfEngines {
TWO(2),
FOUR(4),
SIX(6);
private final int value;
NumberOfEngines(int value){
this.value=value;
}
public static NumberOfEngines getNumber(int amount){
NumberOfEngines [] num = NumberOfEngines.values();
for(int i =0 ; i <num.length;i++){
if(amount==num[i].value){
return num[i];
}
}
return null;
}
public int getNumber(){
return value;
}
public static boolean contains(int amount){
NumberOfEngines [] num = NumberOfEngines.values();
for(int i =0 ; i <num.length;i++){
if(amount==num[i].value){
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,78 @@
package Drawnings;
import Drawnings.Engines.*;
import Entities.EntityBaseStormtrooper;
import Entities.EntityStormtrooper;
import java.util.ArrayList;
import java.util.Collections;
public class ExtentionDrawingBaseStormtrooper {
private static String _separatorForObjectS = ":";
private static String _separatorForObject = "\\:";
public static DrawingBaseStormtrooper CreateDrawingBaseStomrtrooper(String info) {
String[] strs = info.split(_separatorForObject);
EntityBaseStormtrooper stormtrooper;
IDrawingEngines engines = null;
if (strs.length == 10)
{
String s = strs[9];
System.out.println(s);
switch (s) {
case "DrawingEngines":
engines = new DrawingEngines();
break;
case "DrawingOvalEngines":
engines = new DrawingOvalEngines();
break;
case "DrawingTriangleEngines":
engines = new DrawingTriangleEngines();
break;
}
if (engines != null) engines.setAmountOfEngines(engines.getNumberFromString(strs[8]));
}
else if (strs.length == 6) {
String s = strs[5];
switch (s) {
case "DrawingEngines":
engines = new DrawingEngines();
break;
case "DrawingOvalEngines":
engines = new DrawingOvalEngines();
break;
case "DrawingTriangleEngines":
engines = new DrawingTriangleEngines();
break;
}
if (engines != null) engines.setAmountOfEngines(Integer.parseInt(strs[4]));
}
stormtrooper = EntityStormtrooper.CreateEntityStormtrooper(strs);
if (stormtrooper != null)
{
return new DrawingStormtrooper((EntityStormtrooper) stormtrooper, engines);
}
stormtrooper = EntityBaseStormtrooper.CreateEntityBaseStormtrooper(strs);
if (stormtrooper != null)
{
return new DrawingBaseStormtrooper(stormtrooper, engines);
}
return null;
}
public static String GetDataForSave(DrawingBaseStormtrooper drawingBaseStormtrooper)
{
if (drawingBaseStormtrooper == null) return "";
String[] array1 = drawingBaseStormtrooper.EntityBaseStormtrooper.GetStringRepresentation();
String[] array2 = drawingBaseStormtrooper.GetStringRepresentationDecks();
if (array1 == null)
{
return "";
}
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, array1);
if (array2 == null) {
Collections.addAll(list, "0", " ");
}
else Collections.addAll(list, array2);
return String.join(_separatorForObjectS, list);
}
}

View File

@ -0,0 +1,49 @@
package Entities;
import java.awt.*;
import java.util.Objects;
public class EntityBaseStormtrooper
{
private Integer Speed;
public void setSpeed(int speed){
Speed = speed;
}
public Integer getSpeed() {return Speed;}
private Double Weight;
public void setWeight (double weight){
Weight= weight;
}
public Double getWeight() {return Weight;}
private Color BodyColor;
public void setBodyColor (Color bodyColor){
BodyColor = bodyColor;
}
public Color getBodyColor() {return BodyColor;}
public double Step;
public EntityBaseStormtrooper(int speed, double weight, Color bodyColor)
{
Speed = speed;
Weight = weight;
BodyColor = bodyColor;
Step=speed*100/weight;
}
public String[] GetStringRepresentation()
{
return new String[]{"EntityBaseStormtrooper", Speed.toString(), Weight.toString(), colorToHexString(BodyColor)};
}
public static EntityBaseStormtrooper CreateEntityBaseStormtrooper(String[] strs)
{
if (strs.length != 6 || !Objects.equals(strs[0], "EntityBaseStormtrooper"))
{
return null;
}
return new EntityBaseStormtrooper(Integer.parseInt(strs[1]), Double.parseDouble(strs[2]), hexStringToColor(strs[3]));
}
public static String colorToHexString(Color color) {
return String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue());
}
public static Color hexStringToColor(String hexString) {
return Color.decode(hexString);
}
}

View File

@ -0,0 +1,58 @@
package Entities;
import java.awt.*;
import java.util.Objects;
public class EntityStormtrooper extends EntityBaseStormtrooper{
private Color AdditionalColor;
public void setAdditionalColor(Color additionalColor){
AdditionalColor = additionalColor;
}
public Color getAdditionalColor() {
return AdditionalColor;
}
private boolean Rockets;
public void setRockets ( boolean rockets){
Rockets= rockets;
}
public boolean getRockets() {
return Rockets;
}
private boolean Bombs;
public void setBombs (boolean bombs){
Bombs= bombs;
}
public boolean getBombs() {
return Bombs;
}
private boolean Engines;
public void setEngines (boolean engines){
Engines = engines;
}
public boolean getEngines() {return Engines;}
public EntityStormtrooper(int speed, double weight, Color bodyColor, Color additionalColor, boolean rockets, boolean bombs, boolean engines)
{
super(speed,weight,bodyColor);
AdditionalColor = additionalColor;
Rockets = rockets;
Bombs = bombs;
Engines = engines;
}
@Override
public String[] GetStringRepresentation()
{
return new String[]{"EntityStormtrooper", getSpeed().toString(), getWeight().toString(),
colorToHexString(getBodyColor()), colorToHexString(getAdditionalColor()),
String.valueOf(Rockets), String.valueOf(Bombs),String.valueOf(Engines)};
}
public static EntityStormtrooper CreateEntityStormtrooper(String[] strs)
{
if (strs.length != 10 || !Objects.equals(strs[0], "EntityStormtrooper"))
{
return null;
}
return new EntityStormtrooper(Integer.parseInt(strs[1]), Double.parseDouble(strs[2]), hexStringToColor(strs[3]),
hexStringToColor(strs[4]), Boolean.parseBoolean(strs[5]), Boolean.parseBoolean(strs[6]), Boolean.parseBoolean(strs[7]));
}
}

View File

@ -0,0 +1,153 @@
import CollectionGenericObjects.AdditionalCollection;
import CollectionGenericObjects.AbstractCompany;
import Drawnings.DrawingBaseStormtrooper;
import Drawnings.DrawingStormtrooper;
import Drawnings.Engines.DrawingEngines;
import Drawnings.Engines.DrawingOvalEngines;
import Drawnings.Engines.DrawingTriangleEngines;
import Drawnings.Engines.IDrawingEngines;
import Entities.EntityBaseStormtrooper;
import Entities.EntityStormtrooper;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class FormAdditionalCollection extends JFrame {
public DrawingBaseStormtrooper _drawingBaseStormtrooper = null;
private DrawingBaseStormtrooper copyStormtrooper = null;
private AbstractCompany _company = null;
private CanvasStormtrooper _canvasStormtrooper = new CanvasStormtrooper();
private AdditionalCollection<EntityBaseStormtrooper, IDrawingEngines> _additionalCollection = null;
private Random random = new Random();
private JButton buttonGenerate = new JButton("Создать");
private JButton buttonGoToCollection = new JButton("В коллекцию");
private JList<String> listEntity = new JList<String>();
private JList<String> listEngines = new JList<String>();
public FormAdditionalCollection() {
setTitle("Случайные бомбардировщики");
setMinimumSize(new Dimension(970,310));
_additionalCollection = new AdditionalCollection<EntityBaseStormtrooper,IDrawingEngines>(3,(Class)EntityBaseStormtrooper.class,(Class)IDrawingEngines.class);
AddEntities();
AddEngines();
buttonGoToCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(_drawingBaseStormtrooper!=null){
_company._collection.Insert(copyStormtrooper);
FormStormtrooperCollection.canvasShow();
}
}
});
buttonGenerate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
_drawingBaseStormtrooper = _additionalCollection.CreateAdditionalCollectionStormtrooper();
_drawingBaseStormtrooper.SetPictureSize(getWidth(), getHeight());
_drawingBaseStormtrooper.SetPosition(360,30);
_canvasStormtrooper._drawingBaseStormtrooper = _drawingBaseStormtrooper;
_canvasStormtrooper.repaint();
if (_drawingBaseStormtrooper instanceof DrawingStormtrooper)
copyStormtrooper = new DrawingStormtrooper((EntityStormtrooper) _drawingBaseStormtrooper.EntityBaseStormtrooper, _drawingBaseStormtrooper.drawingEngines);
else
copyStormtrooper = new DrawingBaseStormtrooper(_drawingBaseStormtrooper.EntityBaseStormtrooper, _drawingBaseStormtrooper.drawingEngines);
}
});
buttonGoToCollection.setBounds(830,200,120,60);
buttonGenerate.setBounds(830, 130, 120, 60);
listEntity.setBounds(10,200,400,60);
listEngines.setBounds(420,200,400,60);
add(buttonGenerate);
add(buttonGoToCollection);
add(listEntity);
add(listEngines);
add(_canvasStormtrooper);
setVisible(true);
}
private String ToString(EntityBaseStormtrooper entity) {
String str = "";
if (entity instanceof EntityStormtrooper) str += "EntityStormtrooper ";
else str += "EntityBaseStormtrooper ";
str += entity.getBodyColor().toString();
return str;
}
private String ToString(IDrawingEngines engines) {
if (engines == null || engines.getNumberOfEngines() == null)
return "Не имеет двигателей";
String str = ""+engines.getNumberOfEngines();
str+=" двигателя";
return str;
}
public void AddEntities() {
for (int i = 0; i < _additionalCollection.CountEntities; i++) {
random = new Random();
int speed = random.nextInt(100, 300);
float weight = random.nextInt(1000, 3000);
Color bodycolor = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
EntityBaseStormtrooper entityBaseStormtrooper;
if (random.nextBoolean()) {
entityBaseStormtrooper = new EntityBaseStormtrooper(speed, weight, bodycolor);
}
else {
Color additionalcolor = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
boolean rockets = random.nextBoolean();
boolean bombs = random.nextBoolean();
boolean engines = random.nextBoolean();
entityBaseStormtrooper = new EntityStormtrooper(speed, weight, bodycolor, additionalcolor, rockets, bombs,engines);
}
_additionalCollection.Insert(entityBaseStormtrooper);
}
}
public void AddEngines() {
for (int i = 0; i < _additionalCollection.CountEngines; i++) {
random = new Random();
EntityBaseStormtrooper entity = _additionalCollection._collectionEntity[i];
IDrawingEngines drawingEngines = null;
int numberOfEngines = ((int) ((Math.random() * 3) + 1) * 2);
int typeOfEngines = (int) ((Math.random() * 3) + 1);
if (entity instanceof EntityStormtrooper) {
if (((EntityStormtrooper) entity).getEngines()) {
switch (typeOfEngines) {
case 1:
drawingEngines = new DrawingEngines();
drawingEngines.setAmountOfEngines((int) ((Math.random() * 3) + 1) * 2);
break;
case 2:
drawingEngines = new DrawingTriangleEngines();
drawingEngines.setAmountOfEngines((int) ((Math.random() * 3) + 1) * 2);
break;
case 3:
drawingEngines = new DrawingOvalEngines();
drawingEngines.setAmountOfEngines((int) ((Math.random() * 3) + 1) * 2);
break;
}
}
}
if(drawingEngines!=null){
_additionalCollection.Insert(drawingEngines);
}
}
}
void setCompany(AbstractCompany company) {
this._company = company;
String[] data1 = new String[_additionalCollection.CountEntities];
for (int i = 0; i < _additionalCollection.CountEntities; i++) {
EntityBaseStormtrooper entity = _additionalCollection._collectionEntity[i];
data1[i] = ToString(entity);
}
String[] data2 = new String[_additionalCollection.CountEngines];
for (int i = 0; i < _additionalCollection.CountEngines; i++) {
IDrawingEngines engines = _additionalCollection._collectionEngines[i];
data2[i] = ToString(engines);
}
listEntity.setListData(data1);
listEngines.setListData(data2);
}
}

View File

@ -0,0 +1,143 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import Drawnings.DirectionType;
import Drawnings.DrawingBaseStormtrooper;
import Drawnings.DrawingStormtrooper;
import MovementStrategy.*;
public class FormStormtrooper extends JFrame {
private AbstractStrategy _strategy;
private final String title;
private final Dimension dimension;
private int Width;
private int Height;
private final CanvasStormtrooper canvasStormtrooper = new CanvasStormtrooper();
private JComboBox ComboBoxStrategy = new JComboBox(new String []{"К центру", "К краю"});
private JButton ButtonStrategy = new JButton("Шаг");
private final JButton UpButton = new JButton();
private final JButton DownButton = new JButton();
private final JButton LeftButton = new JButton();
private final JButton RightButton = new JButton();
public FormStormtrooper(String title, Dimension dimension) {
this.title = title;
this.dimension = dimension;
}
public void Init(DrawingBaseStormtrooper stormtrooper) {
setTitle(title);
setMinimumSize(dimension);
canvasStormtrooper._drawingBaseStormtrooper = stormtrooper;
canvasStormtrooper._drawingBaseStormtrooper.SetPosition((int) (Math.random() * 300 + 100), (int) (Math.random() * 300 + 100));
Width = getWidth() - 10;
Height = getHeight() - 34;
_strategy = null;
Icon iconUp = new ImageIcon("E:\\ООП\\Java\\Lab3\\ProjectStormtrooper\\Resources\\arrowUp.jpg");
UpButton.setIcon(iconUp);
UpButton.setName("UP");
DownButton.setName("DOWN");
Icon iconDown = new ImageIcon("E:\\ООП\\Java\\Lab3\\ProjectStormtrooper\\Resources\\arrowDown.jpg");
DownButton.setIcon(iconDown);
LeftButton.setName("LEFT");
Icon iconLeft = new ImageIcon("E:\\ООП\\Java\\Lab3\\ProjectStormtrooper\\Resources\\arrowLeft.jpg");
LeftButton.setIcon(iconLeft);
RightButton.setName("RIGHT");
Icon iconRight = new ImageIcon("E:\\ООП\\Java\\Lab3\\ProjectStormtrooper\\Resources\\arrowRight.jpg");
RightButton.setIcon(iconRight);
ButtonStrategy.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (canvasStormtrooper._drawingBaseStormtrooper == null) return;
if (ComboBoxStrategy.isEnabled()) {
int index = ComboBoxStrategy.getSelectedIndex();
switch (index) {
case 1:
_strategy = new MoveToBorder();
break;
case 0:
_strategy = new MoveToCenter();
break;
default:
_strategy = null;
break;
}
;
if (_strategy == null) {
return;
}
_strategy.SetData(new MoveableStormtrooper(canvasStormtrooper._drawingBaseStormtrooper), Width, Height);
}
if (_strategy == null) {
return;
}
ComboBoxStrategy.setEnabled(false);
_strategy.MakeStep();
if (_strategy.GetStatus() == StrategyStatus.Finish) {
ComboBoxStrategy.setEnabled(true);
_strategy = null;
}
}
});
ActionListener actionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (canvasStormtrooper._drawingBaseStormtrooper == null) return;
boolean result = switch ((((JButton) (event.getSource())).getName())) {
case "UP" -> canvasStormtrooper._drawingBaseStormtrooper.MoveTransport(DirectionType.Up);
case "DOWN" -> canvasStormtrooper._drawingBaseStormtrooper.MoveTransport(DirectionType.Down);
case "LEFT" -> canvasStormtrooper._drawingBaseStormtrooper.MoveTransport(DirectionType.Left);
case "RIGHT" -> canvasStormtrooper._drawingBaseStormtrooper.MoveTransport(DirectionType.Right);
default -> false;
};
if (result) {
canvasStormtrooper.repaint();
}
}
};
UpButton.addActionListener(actionListener);
DownButton.addActionListener(actionListener);
LeftButton.addActionListener(actionListener);
RightButton.addActionListener(actionListener);
setSize(dimension.width, dimension.height);
setLayout(null);
canvasStormtrooper.setBounds(0, 0, getWidth() - 180, getHeight());
UpButton.setBounds(getWidth() - 180, getHeight() - 210, 70, 70);
DownButton.setBounds(getWidth() - 180, getHeight() - 140, 70, 70);
RightButton.setBounds(getWidth() - 110, getHeight() - 140, 70, 70);
LeftButton.setBounds(getWidth() - 250, getHeight() - 140, 70, 70);
ComboBoxStrategy.setBounds(getWidth() - 170, 10, 140, 35);
ButtonStrategy.setBounds(getWidth() - 130, 55, 100, 25);
add(ComboBoxStrategy);
add(ButtonStrategy);
add(UpButton);
add(DownButton);
add(RightButton);
add(LeftButton);
add(canvasStormtrooper);
setVisible(true);
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
Width = getWidth() - 10;
Height = getHeight() - 34;
if (canvasStormtrooper._drawingBaseStormtrooper != null)
canvasStormtrooper._drawingBaseStormtrooper.SetPictureSize(Width, Height);
canvasStormtrooper.setBounds(0, 0, getWidth(), getHeight());
UpButton.setBounds(getWidth() - 180, getHeight() - 210, 70, 70);
DownButton.setBounds(getWidth() - 180, getHeight() - 140, 70, 70);
RightButton.setBounds(getWidth() - 110, getHeight() - 140, 70, 70);
LeftButton.setBounds(getWidth() - 250, getHeight() - 140, 70, 70);
ComboBoxStrategy.setBounds(getWidth() - 170, 10, 140, 35);
ButtonStrategy.setBounds(getWidth() - 130, 55, 100, 25);
}
});
}
}

View File

@ -0,0 +1,358 @@
import CollectionGenericObjects.*;
import Drawnings.DrawingBaseStormtrooper;
import Drawnings.DrawingStormtrooper;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import static java.lang.Integer.parseInt;
public class FormStormtrooperCollection extends JFrame {
private String title;
private Dimension dimension;
public static CanvasFormStormtrooperCollection<DrawingBaseStormtrooper> _canvasStormtrooper = new CanvasFormStormtrooperCollection<DrawingBaseStormtrooper>();
private static AbstractCompany _company = null;
private Queue<DrawingBaseStormtrooper> _collectionRemovedObjects = new LinkedList<>();
private StorageCollection<DrawingBaseStormtrooper> _storageCollection = new StorageCollection<DrawingBaseStormtrooper>();
private JTextField textBoxCollection = new JTextField();
private JRadioButton radioButtonMassive = new JRadioButton("Массив");
private JRadioButton radioButtonList = new JRadioButton("Список");
private JButton buttonAddCollection = new JButton("Добавить");
private JList listBoxCollection = new JList();
private JButton buttonRemoveCollection = new JButton("Удалить");
private JButton buttonCreateCompany = new JButton("Создать компанию");
private JButton createButton = new JButton("Создать бомбардировщик");
private JButton removeButton = new JButton("Удалить");
private JButton removeObjectsButton = new JButton("Удаленные объекты");
private JButton GoToCheckButton = new JButton("На проверку");
private JButton RandomButton = new JButton("Случайные");
private JButton RefreshButton = new JButton("Обновить");
private JComboBox ComboBoxCollections = new JComboBox(new String[]{"", "Хранилище"});
private JFormattedTextField TextField;
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("Файл");
private JMenuItem loadItem = new JMenuItem("Загрузить");
private JMenuItem saveItem = new JMenuItem("Сохранить");
private JMenuItem loadCollection = new JMenuItem("Загрузить коллекцию");
private JMenuItem saveCollection = new JMenuItem("Сохранить коллекцию");
public FormStormtrooperCollection(String title, Dimension dimension) {
this.title = title;
this.dimension = dimension;
}
public static void canvasShow() {
_company.SetPosition();
_canvasStormtrooper.SetCollectionToCanvas(_company);
_canvasStormtrooper.repaint();
}
public void Init() {
setTitle(title);
setMinimumSize(dimension);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TextField = new JFormattedTextField();
createButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null) return;
FormStormtrooperConfig form = new FormStormtrooperConfig("", new Dimension(800, 300));
form.setCompany(_company);
form.Init();
}
});
removeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null || TextField.getText() == null) {
return;
}
int pos = parseInt(TextField.getText());
int resultConfirmDialog = JOptionPane.showConfirmDialog(null, "Удалить", "Удаление", JOptionPane.YES_NO_OPTION);
if (resultConfirmDialog == JOptionPane.NO_OPTION) return;
DrawingBaseStormtrooper obj = _storageCollection.remove(
listBoxCollection.getSelectedValue().toString(), pos);
if (obj != null) {
JOptionPane.showMessageDialog(null, "Объект удален");
_collectionRemovedObjects.add(obj);
canvasShow();
} else {
JOptionPane.showMessageDialog(null, "Не удалось удалить объект");
}
}
});
GoToCheckButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null) {
return;
}
DrawingBaseStormtrooper stormtrooper = null;
int counter = 100;
while (stormtrooper == null) {
stormtrooper = _company.GetRandomObject();
counter--;
if (counter <= 0) {
break;
}
}
if (stormtrooper == null) {
return;
}
FormStormtrooper form = new FormStormtrooper("Бомбардировщик", new Dimension(1000, 750));
form.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
canvasShow();
super.windowClosing(e);
}
});
form.Init(stormtrooper);
}
});
RefreshButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null) {
return;
}
canvasShow();
}
});
RandomButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_company == null) {
return;
}
FormAdditionalCollection form = new FormAdditionalCollection();
form.setCompany(_company);
}
});
buttonAddCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (textBoxCollection.getText().isEmpty() || (!radioButtonMassive.isSelected()
&& !radioButtonList.isSelected())) {
JOptionPane.showMessageDialog(null, "Не все данные заполнены");
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.isSelected()) {
collectionType = CollectionType.Massive;
} else if (radioButtonList.isSelected()) {
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollection.getText(), collectionType);
RerfreshListBoxItems();
}
});
buttonRemoveCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (listBoxCollection.getSelectedIndex() < 0 || listBoxCollection.getSelectedValue() == null) {
JOptionPane.showMessageDialog(null, "Коллекция не выбрана");
return;
}
int resultConfirmDialog = JOptionPane.showConfirmDialog(null,
"Удалить", "Удаление",
JOptionPane.YES_NO_OPTION);
if (resultConfirmDialog == JOptionPane.NO_OPTION) return;
_storageCollection.DelCollection(listBoxCollection.getSelectedValue().toString());
RerfreshListBoxItems();
}
});
buttonCreateCompany.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (listBoxCollection.getSelectedIndex() < 0 || listBoxCollection.getSelectedValue() == null) {
JOptionPane.showMessageDialog(null, "Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawingBaseStormtrooper> collection =
_storageCollection.getCollectionObject(listBoxCollection.getSelectedValue().toString());
if (collection == null) {
JOptionPane.showMessageDialog(null, "Коллекция не проинициализирована");
return;
}
switch (ComboBoxCollections.getSelectedItem().toString()) {
case "Хранилище":
_company = new StormtrooperSharingService(getWidth() - 200, getHeight() - 110,
collection);
break;
}
RerfreshListBoxItems();
}
});
removeObjectsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_collectionRemovedObjects.isEmpty()) {
JOptionPane.showMessageDialog(null, "Коллекция пуста");
return;
}
DrawingBaseStormtrooper stormtrooper = null;
stormtrooper = _collectionRemovedObjects.remove();
if (stormtrooper == null) {
return;
}
FormStormtrooper form = new FormStormtrooper("Бомбардировщик", new Dimension(1000, 750));
form.Init(stormtrooper);
}
});
saveItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SaveFile();
}
});
loadItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LoadFile();
}
});
saveCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Save coll");
SaveCollection();
}
});
loadCollection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Load coll");
LoadCollection();
}
});
ButtonGroup radioButtonsGroup = new ButtonGroup();
JLabel labelCollectionName = new JLabel("Название коллекции");
radioButtonsGroup.add(radioButtonMassive);
radioButtonsGroup.add(radioButtonList);
_canvasStormtrooper.setBounds(0, 0, getWidth() - 200, getHeight());
labelCollectionName.setBounds(getWidth() - 190, 10, 150, 20);
textBoxCollection.setBounds(getWidth() - 190, 35, 150, 25);
radioButtonMassive.setBounds(getWidth() - 190, 60, 75, 20);
radioButtonList.setBounds(getWidth() - 105, 60, 75, 20);
buttonAddCollection.setBounds(getWidth() - 190, 85, 150, 20);
listBoxCollection.setBounds(getWidth() - 190, 115, 150, 70);
buttonRemoveCollection.setBounds(getWidth() - 190, 195, 150, 20);
ComboBoxCollections.setBounds(getWidth() - 190, 225, 150, 20);
buttonCreateCompany.setBounds(getWidth() - 190, 255, 150, 20);
createButton.setBounds(getWidth() - 190, 325, 150, 30);
RandomButton.setBounds(getWidth() - 190, 365, 150, 30);
removeObjectsButton.setBounds(getWidth() - 190, 505, 150, 30);
TextField.setBounds(getWidth() - 190, 545, 150, 30);
removeButton.setBounds(getWidth() - 190, 585, 150, 30);
GoToCheckButton.setBounds(getWidth() - 190, 625, 150, 30);
RefreshButton.setBounds(getWidth() - 190, 665, 150, 30);
setSize(dimension.width, dimension.height);
setLayout(null);
add(textBoxCollection);
add(radioButtonMassive);
add(radioButtonList);
add(buttonAddCollection);
add(listBoxCollection);
add(buttonRemoveCollection);
add(buttonCreateCompany);
add(labelCollectionName);
add(removeObjectsButton);
add(_canvasStormtrooper);
add(ComboBoxCollections);
add(createButton);
add(TextField);
add(removeButton);
add(GoToCheckButton);
add(RandomButton);
add(RefreshButton);
fileMenu.add(loadItem);
fileMenu.add(saveItem);
fileMenu.add(loadCollection);
fileMenu.add(saveCollection);
fileMenu.addSeparator();
menuBar.add(fileMenu);
setJMenuBar(menuBar);
setVisible(true);
}
private String SaveWindow() {
FileDialog fileDialog = new FileDialog(this, "Save File", FileDialog.SAVE);
fileDialog.setVisible(true);
String directory = fileDialog.getDirectory();
String file = fileDialog.getFile();
if (directory == null || file == null) return null;
return directory + file;
}
private void SaveFile() {
String filename = SaveWindow();
if (_storageCollection.SaveData(filename)) {
JOptionPane.showMessageDialog(null, "Сохранено");
} else JOptionPane.showMessageDialog(null, "Ошибка сохранения");
}
private void SaveCollection() {
String filename = SaveWindow();
if (filename == null) {
JOptionPane.showMessageDialog(null, "Файл не выбран");
return;
}
if (listBoxCollection.getSelectedIndex() < 0 || listBoxCollection.getSelectedValue() == null) {
JOptionPane.showMessageDialog(null, "Коллекция не выбрана");
}
if (_storageCollection.SaveOneCollection(filename, listBoxCollection.getSelectedValue().toString())) {
JOptionPane.showMessageDialog(null, "Коллекция сохранена");
} else JOptionPane.showMessageDialog(null, "Ошибка сохранения");
}
private String LoadWindow() {
FileDialog fileDialog = new FileDialog(this, "Save File", FileDialog.LOAD);
fileDialog.setVisible(true);
String directory = fileDialog.getDirectory();
String file = fileDialog.getFile();
if (directory == null || file == null) return null;
return directory + file;
}
private void LoadFile() {
String filename = LoadWindow();
if (_storageCollection.LoadData(filename)) {
JOptionPane.showMessageDialog(null, "Загрузка прошла успешно");
RerfreshListBoxItems();
} else JOptionPane.showMessageDialog(null, "Не загрузилось");
}
private void LoadCollection() {
String filename = LoadWindow();
if (_storageCollection.LoadOneCollection(filename)) {
JOptionPane.showMessageDialog(null, "Коллекция загружена");
RerfreshListBoxItems();
} else JOptionPane.showMessageDialog(null, "Не загрузилось");
}
private void RerfreshListBoxItems() {
DefaultListModel<String> list = new DefaultListModel<String>();
for (String name : _storageCollection.Keys()) {
if (name != "") {
list.addElement(name);
}
}
listBoxCollection.setModel(list);
}
}

View File

@ -0,0 +1,467 @@
import CollectionGenericObjects.AbstractCompany;
import Drawnings.*;
import Drawnings.Engines.*;
import Entities.EntityStormtrooper;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
public class FormStormtrooperConfig extends JFrame {
private String title;
private Dimension dimension;
private DrawingBaseStormtrooper _stormtrooper;
private AbstractCompany company = null;
private JLabel labelSpeed = new JLabel("Скорость");
private JLabel labelWeight = new JLabel("Вес");
private JLabel labelNumberOfEngines = new JLabel("Двигатели");
private JLabel labelBaseStormtrooper = new JLabel("Самолет", SwingConstants.CENTER);
private JLabel labelStormtrooper = new JLabel("Бомбардировщик", SwingConstants.CENTER);
private JLabel labelColor = new JLabel("Цвета");
private JLabel labelBodyColor = new JLabel("Основной цвет", SwingConstants.CENTER);
private JLabel labelAdditionalColor = new JLabel("Дополнительный цвет", SwingConstants.CENTER);
private JLabel labelEngines = new JLabel("Тип двигателей",SwingConstants.CENTER);
private JLabel labelDefaultEngines = new JLabel("Классические",SwingConstants.CENTER);
private JLabel labelOvalEngines = new JLabel("Овальные", SwingConstants.CENTER);
private JLabel labelTriangleEngines = new JLabel("Треугольные", SwingConstants.CENTER);
private JSpinner spinnerSpeed = new JSpinner();
private JSpinner spinnerWeight = new JSpinner();
private JSpinner spinnerNumberOfEngines = new JSpinner();
private JCheckBox checkBoxBombs = new JCheckBox("Имеет бомбы");
private JCheckBox checkBoxRockets = new JCheckBox("Имеет ракеты");
private JCheckBox checkBoxEngines = new JCheckBox("Имеет двигатели");
private JComponent panelObject = new JPanel();
private JPanel panelColorRed = new JPanel();
private JPanel panelColorGreen = new JPanel();
private JPanel panelColorBlue = new JPanel();
private JPanel panelColorYellow = new JPanel();
private JPanel panelColorBlack = new JPanel();
private JPanel panelColorWhite = new JPanel();
private JPanel panelColorGray = new JPanel();
private JPanel panelColorCyan = new JPanel();
private JButton buttonAdd = new JButton("Добавить");
private JButton buttonCancel = new JButton("Отмена");
public FormStormtrooperConfig(String title, Dimension dimension) {
this.title = title;
this.dimension = dimension;
}
public void Init() {
SpinnerModel numSpeed = new SpinnerNumberModel(100, 100, 1000, 1);
SpinnerModel numWeight = new SpinnerNumberModel(100, 100, 1000, 1);
spinnerSpeed.setModel(numSpeed);
spinnerWeight.setModel(numWeight);
SpinnerModel numEngines = new SpinnerNumberModel(2, 2, 6, 2);
spinnerNumberOfEngines.setModel(numEngines);
panelObject = new Canvas();
panelObject.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
spinnerSpeed.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (_stormtrooper == null) return;
_stormtrooper.EntityBaseStormtrooper.setSpeed((int)spinnerSpeed.getValue());
}
});
spinnerWeight.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (_stormtrooper == null) return;
_stormtrooper.EntityBaseStormtrooper.setWeight((int)spinnerWeight.getValue());
}
});
spinnerNumberOfEngines.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if(_stormtrooper ==null)return;
if(_stormtrooper.EntityBaseStormtrooper instanceof EntityStormtrooper stormtrooper){
_stormtrooper.drawingEngines.setAmountOfEngines((int) spinnerNumberOfEngines.getValue());
panelObject.repaint();
}
}
});
checkBoxBombs.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_stormtrooper == null) return;
if (_stormtrooper.EntityBaseStormtrooper instanceof EntityStormtrooper stormtrooper) {
stormtrooper.setBombs(checkBoxBombs.isSelected());
panelObject.repaint();
}
}
});
checkBoxRockets.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_stormtrooper == null) return;
if (_stormtrooper.EntityBaseStormtrooper instanceof EntityStormtrooper stormtrooper) {
stormtrooper.setRockets(checkBoxRockets.isSelected());
panelObject.repaint();
}
}
});
checkBoxEngines.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(_stormtrooper == null)return;
if(_stormtrooper.EntityBaseStormtrooper instanceof EntityStormtrooper stormtrooper){
stormtrooper.setEngines(checkBoxEngines.isSelected());
if(_stormtrooper instanceof DrawingStormtrooper stormtrooper1 && stormtrooper1.drawingEngines==null){
stormtrooper1.drawingEngines=new DrawingEngines();
stormtrooper1.drawingEngines.setAmountOfEngines((int) spinnerNumberOfEngines.getValue());
}
panelObject.repaint();
}
}
});
labelBaseStormtrooper.setBackground(Color.WHITE);
labelStormtrooper.setBackground(Color.WHITE);
labelBaseStormtrooper.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelStormtrooper.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelBodyColor.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelAdditionalColor.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelDefaultEngines.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelOvalEngines.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
labelTriangleEngines.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
MouseAdapter labelObjectsMouseDown = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((JLabel) e.getComponent()).getTransferHandler().exportAsDrag(((JLabel) e.getComponent()), e, TransferHandler.COPY);
}
};
TransferHandler labelObjectsTransferHandler = new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new StringSelection(((JLabel) c).getText());
}
};
labelBaseStormtrooper.addMouseListener(labelObjectsMouseDown);
labelBaseStormtrooper.setTransferHandler(labelObjectsTransferHandler);
labelStormtrooper.addMouseListener(labelObjectsMouseDown);
labelStormtrooper.setTransferHandler(labelObjectsTransferHandler);
MouseAdapter labelEnginesMouseDown = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((JLabel) e.getComponent()).getTransferHandler().exportAsDrag(((JLabel) e.getComponent()), e, TransferHandler.COPY);
}
};
labelDefaultEngines.addMouseListener(labelEnginesMouseDown);
labelOvalEngines.addMouseListener(labelEnginesMouseDown);
labelTriangleEngines.addMouseListener(labelEnginesMouseDown);
labelDefaultEngines.setTransferHandler(new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {return TransferHandler.COPY;}
@Override
protected Transferable createTransferable(JComponent c) {
return new EnginesTransferable(new DrawingEngines());
}
});
labelOvalEngines.setTransferHandler(new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {return TransferHandler.COPY;}
@Override
protected Transferable createTransferable(JComponent c) {
return new EnginesTransferable(new DrawingOvalEngines());
}
});
labelTriangleEngines.setTransferHandler(new TransferHandler() {
@Override
public int getSourceActions(JComponent c) {return TransferHandler.COPY;}
@Override
protected Transferable createTransferable(JComponent c) {
return new EnginesTransferable(new DrawingTriangleEngines());
}
});
panelObject.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(DataFlavor.stringFlavor)
|| support.isDataFlavorSupported(EnginesTransferable.enginesDataFlavor);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (canImport(support)) {
try {
String data = (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
switch (data) {
case "Самолет":
_stormtrooper = new DrawingBaseStormtrooper((int) spinnerSpeed.getValue(), (int) spinnerWeight.getValue(),
Color.WHITE);
break;
case "Бомбардировщик":
_stormtrooper = new DrawingStormtrooper((int) spinnerSpeed.getValue(), (int) spinnerWeight.getValue(),
Color.WHITE, Color.BLACK, checkBoxBombs.isSelected(), checkBoxRockets.isSelected(),checkBoxEngines.isSelected());
_stormtrooper.drawingEngines=new DrawingEngines();
_stormtrooper.drawingEngines.setAmountOfEngines((int) spinnerNumberOfEngines.getValue());
break;
}
if (_stormtrooper != null) {
_stormtrooper.SetPictureSize(155,155);
_stormtrooper.SetPosition(5,10);
}
else return false;
}
catch (UnsupportedFlavorException | IOException e) {}
try {
IDrawingEngines engines =
(IDrawingEngines) support.getTransferable().getTransferData(EnginesTransferable.enginesDataFlavor);
_stormtrooper.drawingEngines = engines;
_stormtrooper.drawingEngines.setAmountOfEngines((int) spinnerNumberOfEngines.getValue());
}catch (UnsupportedFlavorException | IOException e) {}
panelObject.repaint();
return true;
}
return false;
}
});
JPanel[] colorPanels = {
panelColorRed,
panelColorGreen,
panelColorBlue,
panelColorYellow,
panelColorWhite,
panelColorBlack,
panelColorGray,
panelColorCyan,
};
panelColorRed.setBackground(Color.RED);
panelColorGreen.setBackground(Color.GREEN);
panelColorBlue.setBackground(Color.BLUE);
panelColorYellow.setBackground(Color.YELLOW);
panelColorWhite.setBackground(Color.WHITE);
panelColorBlack.setBackground(Color.BLACK);
panelColorGray.setBackground(Color.GRAY);
panelColorCyan.setBackground(Color.CYAN);
MouseAdapter colorMouseDown = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
((JPanel) e.getComponent()).getTransferHandler().exportAsDrag(((JPanel) e.getComponent()), e, TransferHandler.COPY);
}
};
for (var panelColor : colorPanels) {
panelColor.addMouseListener(colorMouseDown);
panelColor.setTransferHandler(new ColorTransferHandler());
}
labelBodyColor.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferSupport support) {
try {
Color color = (Color) support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
if (_stormtrooper == null) return false;
_stormtrooper.EntityBaseStormtrooper.setBodyColor(color);
return true;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
return false;
}
});
labelAdditionalColor.setTransferHandler(new TransferHandler() {
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
if (!(_stormtrooper instanceof DrawingStormtrooper)) return false;
return support.isDataFlavorSupported(ColorTransferable.colorDataFlavor);
}
@Override
public boolean importData(TransferSupport support) {
try {
Color color = (Color) support.getTransferable().getTransferData(ColorTransferable.colorDataFlavor);
if (_stormtrooper == null) return false;
if (_stormtrooper.EntityBaseStormtrooper instanceof EntityStormtrooper stormtrooper) {
stormtrooper.setAdditionalColor(color);
labelColor.setBackground(color);
return true;
}
return false;
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
return false;
}
});
buttonAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_stormtrooper == null) return;
DrawingBaseStormtrooper copyStormtrooper;
if (_stormtrooper instanceof DrawingStormtrooper)
copyStormtrooper = new DrawingStormtrooper((EntityStormtrooper) _stormtrooper.EntityBaseStormtrooper, _stormtrooper.drawingEngines);
else
copyStormtrooper = new DrawingBaseStormtrooper(_stormtrooper.EntityBaseStormtrooper, _stormtrooper.drawingEngines);
company._collection.Insert(copyStormtrooper);
FormStormtrooperCollection.canvasShow();
dispose();
}
});
buttonCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
labelSpeed.setBounds(8, 17, 75, 15);
labelWeight.setBounds(8,43, 75, 15);
labelNumberOfEngines.setBounds(8, 68, 75, 15);
labelBaseStormtrooper.setBounds(8,150,105,30);
labelStormtrooper.setBounds(8,190,110,30);
checkBoxBombs.setBounds(8,85,150,20);
checkBoxRockets.setBounds(8,105,150,20);
checkBoxEngines.setBounds(8,125,150,20);
spinnerSpeed.setBounds(80,15, 60,20);
spinnerWeight.setBounds(80,40, 60,20);
spinnerNumberOfEngines.setBounds(80, 65,60,20);
panelObject.setBounds(555,50,160,150);
labelBodyColor.setBounds(500,5,100, 40);
labelAdditionalColor.setBounds(605,5,170,40);
labelEngines.setBounds(225,190,150,15);
labelDefaultEngines.setBounds(140, 210, 100, 40);
labelOvalEngines.setBounds(250, 210, 100,40);
labelTriangleEngines.setBounds(360,210,100,40);
labelColor.setBounds(200,10,50,15);
panelColorRed.setBounds(200, 30, 40, 40);
panelColorGreen.setBounds(250, 30, 40,40);
panelColorBlue.setBounds(300,30,40,40);
panelColorYellow.setBounds(350,30,40,40);
panelColorWhite.setBounds(200, 80,40,40);
panelColorBlack.setBounds(250,80,40,40);
panelColorGray.setBounds(300,80,40,40);
panelColorCyan.setBounds(350,80,40,40);
buttonAdd.setBounds(515, 210, 110, 40);
buttonCancel.setBounds(640, 210, 110, 40);
setSize(dimension.width, dimension.height);
setLayout(null);
add(labelSpeed);
add(labelWeight);
add(labelNumberOfEngines);
add(labelBaseStormtrooper);
add(labelStormtrooper);
add(labelColor);
add(labelBodyColor);
add(labelAdditionalColor);
add(labelDefaultEngines);
add(labelDefaultEngines);
add(labelOvalEngines);
add(labelTriangleEngines);
add(spinnerSpeed);
add(spinnerWeight);
add(spinnerNumberOfEngines);
add(checkBoxBombs);
add(checkBoxRockets);
add(checkBoxEngines);
add(panelObject);
add(panelColorRed);
add(panelColorGreen);
add(panelColorBlue);
add(panelColorYellow);
add(panelColorWhite);
add(labelEngines);
add(panelColorBlack);
add(panelColorGray);
add(panelColorCyan);
add(buttonAdd);
add(buttonCancel);
setVisible(true);
}
public void setCompany(AbstractCompany company) {
this.company = company;
}
private class Canvas extends JComponent {
public Canvas() {
}
public void paintComponent(Graphics g) {
if (_stormtrooper == null) {
return;
}
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
_stormtrooper.DrawTransport(g2d);
super.repaint();
}
}
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 {
if (isDataFlavorSupported(flavor)) {
return color;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
private class ColorTransferHandler extends TransferHandler {
@Override
public int getSourceActions(JComponent c) {
return TransferHandler.COPY;
}
@Override
protected Transferable createTransferable(JComponent c) {
return new ColorTransferable(c.getBackground());
}
}
private class EnginesTransferable implements Transferable {
private IDrawingEngines engines;
private static final DataFlavor enginesDataFlavor = new DataFlavor(IDrawingEngines.class, "Engines");
public EnginesTransferable(IDrawingEngines engines) {
this.engines = engines;
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{enginesDataFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(enginesDataFlavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
if (isDataFlavorSupported(flavor)) {
return engines;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
}
}

View File

@ -1,5 +1,10 @@
import Drawnings.Engines.NumberOfEngines;
import java.awt.*;
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
FormStormtrooperCollection form = new FormStormtrooperCollection("Бoмбардировщик", new Dimension(1100,750));
form.Init();
}
}

View File

@ -0,0 +1,60 @@
package MovementStrategy;
public abstract class AbstractStrategy
{
private IMoveableObject _moveableObject;
private StrategyStatus _state = StrategyStatus.NotInit;
public int FieldWidth;
public int FieldHeight;
public StrategyStatus GetStatus (){ return _state; }
public void SetData(IMoveableObject moveableObject, int width, int height)
{
if (moveableObject == null)
{
_state = StrategyStatus.NotInit;
return;
}
_state = StrategyStatus.InProgress;
_moveableObject = moveableObject;
FieldWidth = width;
FieldHeight = height;
}
public void MakeStep()
{
if (_state != StrategyStatus.InProgress)
{
return;
}
if (IsTargetDestinaion())
{
_state = StrategyStatus.Finish;
return;
}
MoveToTarget();
}
protected boolean MoveLeft() {return MoveTo(MovementDirection.Left);}
protected boolean MoveRight() {return MoveTo(MovementDirection.Right);}
protected boolean MoveUp(){return MoveTo(MovementDirection.Up);}
protected boolean MoveDown(){return MoveTo(MovementDirection.Down);}
protected ObjectParameters GetObjectParameters (){return _moveableObject.GetObjectPosition();}
protected int GetStep(){
if (_state != StrategyStatus.InProgress)
{
return -1;
}
return _moveableObject.getStep();
}
protected abstract void MoveToTarget();
protected abstract boolean IsTargetDestinaion();
private boolean MoveTo(MovementDirection movementDirection) {
if (_state != StrategyStatus.InProgress) {
return false;
}
if (_moveableObject.TryMoveObject(movementDirection)) {
return _moveableObject.TryMoveObject(movementDirection);
}
return false;
}
}

View File

@ -0,0 +1,7 @@
package MovementStrategy;
public interface IMoveableObject
{
ObjectParameters GetObjectPosition ();
int getStep();
boolean TryMoveObject(MovementDirection direction);
}

View File

@ -0,0 +1,29 @@
package MovementStrategy;
public class MoveToBorder extends AbstractStrategy
{
@Override
protected boolean IsTargetDestinaion()
{
ObjectParameters objParams = GetObjectParameters();
if (objParams == null)
{
return false;
}
return objParams.LeftBorder - GetStep() <= 0 &&
objParams.RightBorder + GetStep() >= FieldWidth &&
objParams.TopBorder - GetStep() <= 0
&& objParams.ObjectMiddleVertical + GetStep() >= FieldHeight;
}
@Override
protected void MoveToTarget()
{
ObjectParameters objParams = GetObjectParameters();
if (objParams == null) {
return;
}
int x = objParams.RightBorder;
if (x + GetStep() < FieldWidth)MoveRight();
int y = objParams.DownBorder;
if (y + GetStep() < FieldHeight) MoveDown();
}
}

View File

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

View File

@ -0,0 +1,46 @@
package MovementStrategy;
import Drawnings.*;
import Entities.EntityBaseStormtrooper;
public class MoveableStormtrooper implements IMoveableObject
{
private DrawingBaseStormtrooper _stormtrooper ;
public MoveableStormtrooper(DrawingBaseStormtrooper stormtrooper)
{
_stormtrooper = stormtrooper;
}
@Override
public ObjectParameters GetObjectPosition() {
if (_stormtrooper == null || _stormtrooper.EntityBaseStormtrooper == null || _stormtrooper.getPosX()==null || _stormtrooper.getPosY()==null) {
return null;
}
return new ObjectParameters(_stormtrooper.getPosX(), _stormtrooper.getPosY(), _stormtrooper.getWidth(), _stormtrooper.getHeight());
}
@Override
public int getStep(){ return (int)(_stormtrooper.EntityBaseStormtrooper.Step);}
@Override
public boolean TryMoveObject(MovementDirection direction)
{
if (_stormtrooper == null || _stormtrooper.EntityBaseStormtrooper == null)
{
return false;
}
return _stormtrooper.MoveTransport(GetDirectionType(direction));
}
private static DirectionType GetDirectionType(MovementDirection direction) {
switch (direction) {
case Left:
return DirectionType.Left;
case Right:
return DirectionType.Right;
case Up:
return DirectionType.Up;
case Down:
return DirectionType.Down;
default:
return DirectionType.Unknow;
}
}
}

View File

@ -0,0 +1,12 @@
package MovementStrategy;
public enum MovementDirection {
///Вверх
Up,
///Вниз
Down,
///Влево
Left,
///Вправо
Right
}

View File

@ -0,0 +1,24 @@
package MovementStrategy;
public class ObjectParameters
{
private int _x;
private int _y;
public int _width;
private int _height;
public int TopBorder =_y;
public int LeftBorder = _x;
public int RightBorder = _x + _width;
public int DownBorder = _y + _height;
public int ObjectMiddleHorizontal;
public int ObjectMiddleVertical;
public ObjectParameters(int x, int y, int width, int height)
{
_x = x;
_y = y;
_width = width;
_height = height;
ObjectMiddleHorizontal = _x + _width/ 2;
ObjectMiddleVertical = _y + _height/ 2;
}
}

View File

@ -0,0 +1,7 @@
package MovementStrategy;
public enum StrategyStatus
{
NotInit,
InProgress,
Finish
}