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

This commit is contained in:
Никита Белянин 2023-11-12 15:02:58 +04:00
parent 785a3bbfc0
commit 17c4995d8a
13 changed files with 484 additions and 94 deletions

View File

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

View File

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

View File

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

View File

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

View File

@ -10,6 +10,7 @@ public class DrawingArmoVehicle {
protected int _startPosY; protected int _startPosY;
protected int _TankWidth = 160; protected int _TankWidth = 160;
protected int _TankHeight = 55; protected int _TankHeight = 55;
public IMoveableObject GetMoveableObject() { return new DrawingObjectTank(this);}
public DrawingArmoVehicle(int speed, double weight, Color bodyColor, int _numWheel, int width, int height) { public DrawingArmoVehicle(int speed, double weight, Color bodyColor, int _numWheel, int width, int height) {
_pictureWidth = width; _pictureWidth = width;
@ -36,6 +37,16 @@ public class DrawingArmoVehicle {
OrnamentsForm.setDigit(_numWheel); OrnamentsForm.setDigit(_numWheel);
} }
public DrawingArmoVehicle(EntityArmoVehicle vehicle, IOrnamentForm ornamentsForm, int width, int height) {
if (height < _pictureHeight || width < _pictureWidth)
return;
_pictureWidth = width;
_pictureHeight = height;
ArmoVehicle = vehicle;
OrnamentsForm = ornamentsForm;
OrnamentsForm.setDigit(ArmoVehicle.numWheel);
}
public void SetPosition(int x, int y) { public void SetPosition(int x, int y) {
_startPosX = Math.min(x, _pictureWidth - _TankWidth); _startPosX = Math.min(x, _pictureWidth - _TankWidth);
_startPosY = Math.min(y, _pictureHeight - _TankHeight); _startPosY = Math.min(y, _pictureHeight - _TankHeight);

View File

@ -4,6 +4,7 @@ public class DrawingTank extends DrawingArmoVehicle {
protected IOrnamentForm OrnamentsForm; protected IOrnamentForm OrnamentsForm;
private boolean OrnamentAdd; private boolean OrnamentAdd;
// Конструктор (Инициализация свойств)
public DrawingTank(int speed, double weight, Color bodyColor, int _numWheel, Color additionalColor, boolean bodyKit, boolean caterpillar, boolean tower, int width, int height, boolean ornamentAdd) { public DrawingTank(int speed, double weight, Color bodyColor, int _numWheel, Color additionalColor, boolean bodyKit, boolean caterpillar, boolean tower, int width, int height, boolean ornamentAdd) {
super(speed, weight, bodyColor, _numWheel, width, height); super(speed, weight, bodyColor, _numWheel, width, height);
ArmoVehicle = new EntityTank(speed, weight, bodyColor, _numWheel, additionalColor, bodyKit, caterpillar, tower); ArmoVehicle = new EntityTank(speed, weight, bodyColor, _numWheel, additionalColor, bodyKit, caterpillar, tower);
@ -12,6 +13,13 @@ public class DrawingTank extends DrawingArmoVehicle {
this.OrnamentAdd = ornamentAdd; this.OrnamentAdd = ornamentAdd;
} }
// Ещё один конструктор
public DrawingTank(EntityTank tank, IOrnamentForm _wheelDrawing, int width, int height ){
super(tank, _wheelDrawing, width, height);
if (height < _pictureHeight || width < _pictureWidth)
return;
}
// Установка позиции // Установка позиции
public void SetPosition(int x, int y) { public void SetPosition(int x, int y) {
_startPosX = Math.min(x, _pictureWidth-_TankWidth); _startPosX = Math.min(x, _pictureWidth-_TankWidth);

View File

@ -54,8 +54,8 @@ public class DrawingWheelsCombination implements IOrnamentForm {
CaterpillarStar(g,_startPosX + 5, _startPosY + 12); CaterpillarStar(g,_startPosX + 5, _startPosY + 12);
CaterpillarStar(g,_startPosX + 105, _startPosY + 12); CaterpillarStar(g,_startPosX + 105, _startPosY + 12);
} }
if (wheels == CountWheels.Three) { if (wheels == CountWheels.Three) {
DrawWheels(g,_startPosX, _startPosY); DrawWheels(g,_startPosX, _startPosY);
DrawWheels(g,_startPosX + 50, _startPosY); DrawWheels(g,_startPosX + 50, _startPosY);
@ -85,8 +85,8 @@ public class DrawingWheelsCombination implements IOrnamentForm {
CaterpillarStar(g,_startPosX + 30, _startPosY + 12); CaterpillarStar(g,_startPosX + 30, _startPosY + 12);
CaterpillarStar(g,_startPosX + 55, _startPosY + 12); CaterpillarStar(g,_startPosX + 55, _startPosY + 12);
CaterpillarStar(g,_startPosX + 105, _startPosY + 12); CaterpillarStar(g,_startPosX + 105, _startPosY + 12);
} }
if(wheels == CountWheels.Five) { if(wheels == CountWheels.Five) {
DrawWheels(g,_startPosX, _startPosY); DrawWheels(g,_startPosX, _startPosY);
DrawWheels(g,_startPosX + 25, _startPosY); DrawWheels(g,_startPosX + 25, _startPosY);

View File

@ -5,47 +5,77 @@ import java.awt.event.ActionListener;
import java.util.Random; import java.util.Random;
public class FormTank { public class FormTank {
private DrawingArmoVehicle _drawingArmoVehicle; private class Canvas extends JComponent {
public Canvas() {
}
public void paintComponent(Graphics g) {
if (_drawingTank == null) {
return;
}
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
_drawingTank.DrawTransport(g2d);
super.repaint();
}
}
public DrawingArmoVehicle SelectedVehicle;
public boolean DialogResult = false;
public DrawingArmoVehicle _drawingTank;
private AbstractStrategy abstractStrategy; private AbstractStrategy abstractStrategy;
Canvas canv; Canvas canv;
static int pictureBoxWidth = 980; static int pictureBoxWidth = 980;
static int pictureBoxHeight = 560; static int pictureBoxHeight = 570;
public JButton buttonSelectTank;
public JFrame Frame;
public void Draw() { public void Draw() {
canv.repaint(); canv.repaint();
} }
public FormTank() { public FormTank() {
JFrame Frame = new JFrame("Tank"); SelectedVehicle = null;
JButton buttonCreateArmoVehicle = new JButton("Создать Бронемашину"); Frame = new JFrame("Tank");
JButton buttonCreateTank = new JButton("Создать Танк"); JButton buttonCreate = new JButton("Добавить бронетехнику");
JButton buttonCreateTank = new JButton("Добавить танк");
JButton buttonStrategysStep = new JButton("Шаг"); JButton buttonStrategysStep = new JButton("Шаг");
JComboBox ComboBoxStrategy = new JComboBox(new String[]{"к центру", "к краю формочки"}); buttonSelectTank = new JButton("Добавить");
Icon iconUp = new ImageIcon("Tank//Resources//KeyUp.png"); JComboBox<String> comboBoxStrategy = new JComboBox<String>(
JButton up = new JButton(iconUp); new String[]{
"к центру",
"к краю",
});
JButton up = new JButton();
up.setName("up"); up.setName("up");
ImageIcon iconUp = new ImageIcon("Tank//Resources//KeyUp.png");
up.setIcon(iconUp);
Icon iconDown = new ImageIcon("Tank//Resources//KeyDown.png"); JButton down = new JButton();
JButton down = new JButton(iconDown);
down.setName("down"); down.setName("down");
ImageIcon iconDown = new ImageIcon("Tank//Resources//KeyDown.png");
down.setIcon(iconDown);
Icon iconRight = new ImageIcon("Tank//Resources//KeyRight.png"); JButton left = new JButton();
JButton right = new JButton(iconRight);
right.setName("right");
Icon iconLeft = new ImageIcon("Tank//Resources//KeyLeft.png");
JButton left = new JButton(iconLeft);
left.setName("left"); left.setName("left");
ImageIcon iconLeft = new ImageIcon("Tank//Resources//KeyLeft.png");
left.setIcon(iconLeft);
JButton right = new JButton();
right.setName("right");
ImageIcon iconRight = new ImageIcon("Tank//Resources//KeyRight.png");
right.setIcon(iconRight);
buttonStrategysStep.addActionListener( buttonStrategysStep.addActionListener(
new ActionListener() { new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if (_drawingArmoVehicle == null) { if (_drawingTank == null) {
return; return;
} }
if (ComboBoxStrategy.isEnabled()) { if (comboBoxStrategy.isEnabled()) {
switch (ComboBoxStrategy.getSelectedIndex()) { switch (comboBoxStrategy.getSelectedIndex()) {
case 0: case 0:
abstractStrategy = new MoveToCenter(); abstractStrategy = new MoveToCenter();
break; break;
@ -56,14 +86,14 @@ public class FormTank {
abstractStrategy = null; abstractStrategy = null;
break; break;
} }
;
if (abstractStrategy == null) { if (abstractStrategy == null) {
return; return;
} }
abstractStrategy.SetData(new abstractStrategy.SetData(new
DrawingObjectTank(_drawingArmoVehicle), pictureBoxWidth, pictureBoxHeight); DrawingObjectTank(_drawingTank), pictureBoxWidth,
ComboBoxStrategy.setEnabled(false); pictureBoxHeight);
comboBoxStrategy.setEnabled(false);
} }
if (abstractStrategy == null) { if (abstractStrategy == null) {
return; return;
@ -71,23 +101,35 @@ public class FormTank {
abstractStrategy.MakeStep(); abstractStrategy.MakeStep();
Draw(); Draw();
if (abstractStrategy.GetStatus() == Status.Finish) { if (abstractStrategy.GetStatus() == Status.Finish) {
ComboBoxStrategy.setEnabled(true); comboBoxStrategy.setEnabled(true);
abstractStrategy = null; abstractStrategy = null;
} }
} }
} }
); );
buttonCreateTank.addActionListener( buttonCreateTank.addActionListener(
new ActionListener() { new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
Random random = new Random(); Random random = new Random();
_drawingArmoVehicle = new DrawingTank( Color color = new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256));
// Вызываем диалоговое окно выбора цвета
Color selectedColor = JColorChooser.showDialog(Frame, "Выберите цвет", Color.WHITE);
if (selectedColor != null) {
color = selectedColor;
}
Color color2 = new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256));
// Вызываем диалоговое окно выбора цвета
selectedColor = JColorChooser.showDialog(Frame, "Выберите цвет", Color.WHITE);
if (selectedColor != null) {
color2 = selectedColor;
}
_drawingTank = new DrawingTank(
random.nextInt(100, 300), random.nextInt(100, 300),
random.nextInt(1000, 3000), random.nextInt(1000, 3000),
new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256)), color,
random.nextInt(2, 6), random.nextInt(2, 5),
new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256)), color2,
true, true,
true, true,
true, true,
@ -95,26 +137,32 @@ public class FormTank {
pictureBoxHeight, pictureBoxHeight,
true true
); );
_drawingArmoVehicle.SetPosition(random.nextInt(10, 100), random.nextInt(10, 100)); _drawingTank.SetPosition(random.nextInt(10, 100), random.nextInt(10, 100));
canv._drawingArmoVehicle = _drawingArmoVehicle;
Draw(); Draw();
} }
} }
); );
buttonCreate.addActionListener(
buttonCreateArmoVehicle.addActionListener(
new ActionListener() { new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
Random random = new Random(); Random random = new Random();
_drawingArmoVehicle = new DrawingArmoVehicle( Color color = new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256));
// Вызываем диалоговое окно выбора цвета
Color selectedColor = JColorChooser.showDialog(Frame, "Выберите цвет", Color.WHITE);
if (selectedColor != null) {
color = selectedColor;
}
_drawingTank = new DrawingArmoVehicle(
random.nextInt(100, 300), random.nextInt(100, 300),
random.nextInt(1000, 3000), random.nextInt(1000, 3000),
new Color(random.nextInt(0, 256), random.nextInt(0, 256), random.nextInt(0, 256)), color,
random.nextInt(2, 5), random.nextInt(2, 5),
1000, pictureBoxWidth,
560); pictureBoxHeight
_drawingArmoVehicle.SetPosition(random.nextInt(10, 100), random.nextInt(10, 100)); );
canv._drawingArmoVehicle = _drawingArmoVehicle;
_drawingTank.SetPosition(random.nextInt(10, 100), random.nextInt(10, 100));
Draw(); Draw();
} }
} }
@ -122,77 +170,55 @@ public class FormTank {
ActionListener actioListener = new ActionListener() { ActionListener actioListener = new ActionListener() {
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
if (_drawingArmoVehicle == null) { System.out.println(((JButton) (e.getSource())).getName());
if (_drawingTank == null) {
return; return;
} }
switch (((JButton) (e.getSource())).getName()) { switch (((JButton) (e.getSource())).getName()) {
case "up": case "up":
_drawingArmoVehicle.MoveTransport(Direction.Up); _drawingTank.MoveTransport(Direction.Up);
break; break;
case "down": case "down":
_drawingArmoVehicle.MoveTransport(Direction.Down); _drawingTank.MoveTransport(Direction.Down);
break; break;
case "left": case "left":
_drawingArmoVehicle.MoveTransport(Direction.Left); _drawingTank.MoveTransport(Direction.Left);
break; break;
case "right": case "right":
_drawingArmoVehicle.MoveTransport(Direction.Right); _drawingTank.MoveTransport(Direction.Right);
break; break;
} }
Draw(); Draw();
} }
}; };
up.addActionListener(actioListener); up.addActionListener(actioListener);
down.addActionListener(actioListener); down.addActionListener(actioListener);
left.addActionListener(actioListener); left.addActionListener(actioListener);
right.addActionListener(actioListener); right.addActionListener(actioListener);
Frame.setSize(1000, 600); Frame.setSize(1000, 620);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.setLayout(null); Frame.setLayout(null);
canv = new Canvas(); canv = new Canvas();
canv.setBounds(0, 0, pictureBoxWidth, pictureBoxHeight); canv.setBounds(0, 0, pictureBoxWidth, pictureBoxHeight);
buttonCreate.setBounds(2, 520, 180, 40);
buttonCreateArmoVehicle.setBounds(5, 500, 170, 40); buttonCreateTank.setBounds(185, 520, 150, 40);
buttonCreateTank.setBounds(185, 500, 170, 40);
up.setBounds(900, 480, 40, 40); up.setBounds(900, 480, 40, 40);
down.setBounds(900, 520, 40, 40); down.setBounds(900, 520, 40, 40);
left.setBounds(860, 520, 40, 40); left.setBounds(860, 520, 40, 40);
right.setBounds(940, 520, 40, 40); right.setBounds(940, 520, 40, 40);
comboBoxStrategy.setBounds(pictureBoxWidth - 150, 20, 150, 20);
ComboBoxStrategy.setBounds(pictureBoxWidth - 150, 20, 150, 20);
buttonStrategysStep.setBounds(pictureBoxWidth - 150, 45, 150, 20); buttonStrategysStep.setBounds(pictureBoxWidth - 150, 45, 150, 20);
buttonSelectTank.setBounds(pictureBoxWidth / 2, 530, 150, 30);
Frame.add(buttonSelectTank);
Frame.add(canv); Frame.add(canv);
Frame.add(buttonCreateArmoVehicle); Frame.add(buttonCreate);
Frame.add(buttonCreateTank); Frame.add(buttonCreateTank);
Frame.add(up); Frame.add(up);
Frame.add(down); Frame.add(down);
Frame.add(left); Frame.add(left);
Frame.add(right); Frame.add(right);
Frame.add(comboBoxStrategy);
Frame.add(ComboBoxStrategy);
Frame.add(buttonStrategysStep); Frame.add(buttonStrategysStep);
Frame.setVisible(true); Frame.setVisible(true);
} }
}
class Canvas extends JComponent {
public DrawingArmoVehicle _drawingArmoVehicle;
public Canvas() {
}
public void paintComponent(Graphics g) {
if (_drawingArmoVehicle == null) {
return;
}
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
_drawingArmoVehicle.DrawTransport(g2d);
super.repaint();
}
} }

View File

@ -0,0 +1,122 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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);
}
super.repaint();
}
}
Canvas canv;
static int pictureBoxWidth = 700;
static int pictureBoxHeight = 480;
private TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank> _tank;
public void Draw(){
canv.repaint();
}
FormTankCollection() {
canv = new Canvas();
JFrame Frame = new JFrame ("TanksCollecltion");
_tank = new TanksGenericCollections<DrawingArmoVehicle, DrawingObjectTank>(pictureBoxWidth, pictureBoxHeight);
canv._tank = _tank;
JButton ButtonAddTank = new JButton("Добавить технику");
ButtonAddTank.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
FormTank form = new FormTank();
form.buttonSelectTank.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (_tank.Add(form._drawingTank) != -1) {
JOptionPane.showMessageDialog(null, "Объект добавлен", "Информация", JOptionPane.INFORMATION_MESSAGE);
Draw();
}
else {
JOptionPane.showMessageDialog(null, "Не удалось добавить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
}
form.Frame.dispose();
}
}
);
}
}
);
JTextField TextBoxNumber = new JTextField();
JButton ButtonRemoveTank = new JButton("Удалить технику");
ButtonRemoveTank.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (JOptionPane.showConfirmDialog(null, "Удалить объект?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
return;
}
for (char it : TextBoxNumber.getText().toCharArray())
if (it < '0' || it > '9') {
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
if (TextBoxNumber.getText().length() == 0) {
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
return;
}
int pos = Integer.parseInt(TextBoxNumber.getText());
if (_tank.remove(pos) != null) {
JOptionPane.showMessageDialog(null, "Объект удален", "Информация", JOptionPane.INFORMATION_MESSAGE);
Draw();
}
else {
JOptionPane.showMessageDialog(null, "Не удалось удалить объект", "Информация", JOptionPane.INFORMATION_MESSAGE);
}
}
}
);
JButton ButtonRefreshCollection = new JButton("Обновить коллекцию");
ButtonRefreshCollection.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
Draw();
}
}
);
JButton toFormTankGenerate = new JButton("Генерировать технику");
toFormTankGenerate.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e){
FormTankGenerate formTankGenerate = new FormTankGenerate();
}
}
);
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);
Frame.add(canv);
Frame.add(ButtonAddTank);
Frame.add(ButtonRemoveTank);
Frame.add(ButtonRefreshCollection);
Frame.add(TextBoxNumber);
Frame.add(toFormTankGenerate);
Frame.setVisible(true);
}
}

View File

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

View File

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

61
Tank/src/SetGeneric.java Normal file
View File

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

View File

@ -0,0 +1,82 @@
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;
_collection = new SetGeneric<T>(width * height);
}
// Перегрузка оператора сложения
public int Add(T obj) {
if (obj == null) {
return -1;
}
return _collection.Insert(obj);
}
// Перегрузка оператора вычитания
public T remove(int pos) {
T obj = _collection.Get(pos);
if (obj != null) {
_collection.Remove(pos);
}
return obj;
}
// Получение объекта IMoveableObject
public U GetU(int pos)
{
return (U)_collection.Get(pos).GetMoveableObject();
}
// Вывод всего набора объектов
public BufferedImage ShowTanks() {
BufferedImage bitmap = new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bitmap.createGraphics();
DrawBackground(g);
DrawObjects(g);
g.dispose();
return bitmap;
}
// Метод отрисовки фона
private void DrawBackground(Graphics g) {
g.setColor(Color.BLACK);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++) {
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j) {
// Линия разметки места
g.drawLine(i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
}
g.drawLine(i * _placeSizeWidth, 0, i * _placeSizeWidth, _pictureHeight / _placeSizeHeight * _placeSizeHeight);
}
}
private void DrawObjects(Graphics g) {
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);
else
t.DrawTransport((Graphics2D)g);
}
}
}
}