Лабораторная работа 3. Усложненная часть

This commit is contained in:
Danil Kargin 2022-11-29 11:07:20 +04:00
parent 797641613b
commit d1812c0550
6 changed files with 169 additions and 287 deletions

View File

@ -16,28 +16,14 @@ public class DrawningAirFighter {
public int _airFighterWidth = 80; public int _airFighterWidth = 80;
// Высота отрисовки самолета // Высота отрисовки самолета
public int _airFighterHeight = 70; public int _airFighterHeight = 70;
// Инициализация свойств // Инициализация свойств
public DrawningAirFighter(int speed, float weight, Color bodyColor, int numberEngine, String engineModel) public DrawningAirFighter(int speed, float weight, Color bodyColor, int numberEngine, IDrawningEngine engineModel)
{ {
switch(engineModel){ _engine = engineModel;
case "Классический":
_engine = new ModelClassicEngine();
break;
case "Винтовой":
_engine = new ModelScrewEngine();
break;
case "Рeактивный":
_engine = new ModelJetEngine();
break;
default:
_engine = new ModelClassicEngine();
break;
}
_engine.SetCodeEngine(numberEngine); _engine.SetCodeEngine(numberEngine);
AirFighter = new EntityAirFighter(speed, weight, bodyColor); AirFighter = new EntityAirFighter(speed, weight, bodyColor);
} }
protected DrawningAirFighter(int speed, float weight, Color bodyColor, int airFighterWidth, int airFighterHeight, int numberEngines, String engineModel) { protected DrawningAirFighter(int speed, float weight, Color bodyColor, int airFighterWidth, int airFighterHeight, int numberEngines, IDrawningEngine engineModel) {
this(speed, weight, bodyColor, numberEngines, engineModel); this(speed, weight, bodyColor, numberEngines, engineModel);
_airFighterWidth = airFighterWidth; _airFighterWidth = airFighterWidth;
_airFighterHeight = airFighterHeight; _airFighterHeight = airFighterHeight;

View File

@ -2,7 +2,7 @@ import java.awt.Color;
import java.awt.Graphics; import java.awt.Graphics;
public class DrawningUpgradeAirFighter extends DrawningAirFighter{ public class DrawningUpgradeAirFighter extends DrawningAirFighter{
public DrawningUpgradeAirFighter(int speed, float weight, Color bodyColor, Color dopColor, boolean dopWing, boolean rocket, int numberEngines, String engineModel) { public DrawningUpgradeAirFighter(int speed, float weight, Color bodyColor, Color dopColor, boolean dopWing, boolean rocket, int numberEngines, IDrawningEngine engineModel) {
super(speed, weight, bodyColor, 85, 80, numberEngines, engineModel); super(speed, weight, bodyColor, 85, 80, numberEngines, engineModel);
AirFighter = new EntityUpgradeAirFighter(speed, weight, bodyColor, dopColor, dopWing, rocket); AirFighter = new EntityUpgradeAirFighter(speed, weight, bodyColor, dopColor, dopWing, rocket);
} }

View File

@ -17,7 +17,7 @@ public class FormAirFighter extends JFrame implements ComponentListener{
private JLabel labelSpeed; private JLabel labelSpeed;
private JLabel labelWeight; private JLabel labelWeight;
private String item = "2"; private String item = "2";
private String itemEngine = "Классический"; private IDrawningEngine itemEngine = null;
private DrawningAirFighter _airFighter = null; private DrawningAirFighter _airFighter = null;
// Выбранный объект // Выбранный объект
private DrawningAirFighter SelectedAirFighter = null; private DrawningAirFighter SelectedAirFighter = null;
@ -151,6 +151,33 @@ public class FormAirFighter extends JFrame implements ComponentListener{
}); });
editComboBox.setBounds(0, 0, 50, 25); editComboBox.setBounds(0, 0, 50, 25);
panelForDrawing.add(editComboBox); panelForDrawing.add(editComboBox);
// ComboBox для выбора модели двигателя
String[] engineModel = {
"Классический",
"Винтовой",
"Рeактивный"
};
JComboBox engineComboBox = new JComboBox(engineModel);
engineComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox box = (JComboBox)e.getSource();
switch ((String)box.getSelectedItem()){
case "Классический" :
itemEngine = new ModelClassicEngine();
break;
case "Винтовой":
itemEngine = new ModelScrewEngine();
break;
case "Рeактивный":
itemEngine = new ModelJetEngine();
break;
}
}
});
engineComboBox.setBounds(0, 30, 100, 30);
engineComboBox.setSelectedIndex(0);
panelForDrawing.add(engineComboBox);
// Контейнер с кнопками движения // Контейнер с кнопками движения
Container containerDirection = new Container(); Container containerDirection = new Container();
containerDirection.setPreferredSize(new Dimension(120, 70)); containerDirection.setPreferredSize(new Dimension(120, 70));

View File

@ -1,268 +0,0 @@
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class FormMap extends JFrame{
private AbstractMap _abstractMap;
private JLabel panelForDrawing = new JLabel();
private JPanel statusLabel = new JPanel();
private JButton buttonUp;
private JButton buttonDown;
private JButton buttonLeft;
private JButton buttonRight;
private JLabel labelBodyColor;
private JLabel labelSpeed;
private JLabel labelWeight;
private String item = "2";
private String itemEngine = "Классический";
private String mapItem = "Простая карта";
// Слушатель кнопки направления
private ActionListener actionListenerDirection = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JButton tempButton = (JButton)e.getSource();
Direction dir = null;
if (buttonUp.equals(tempButton)) {
dir = Direction.Up;
} else if (buttonDown.equals(tempButton)) {
dir = Direction.Down;
} else if (buttonLeft.equals(tempButton)) {
dir = Direction.Left;
} else if (buttonRight.equals(tempButton)) {
dir = Direction.Right;
}
panelForDrawing.setIcon(new ImageIcon(_abstractMap.MoveObject(dir)));
panelForDrawing.repaint();
}
};
private void SetData(DrawningAirFighter airFighter){
labelSpeed.setText("Скорость: " + airFighter.AirFighter.getSpeed());
labelWeight.setText("Вес: " + airFighter.AirFighter.getWeight());
labelBodyColor.setText("Цвет: " + airFighter.AirFighter.getBodyColor());
BufferedImage bufImg = _abstractMap.CreateMap(panelForDrawing.getWidth(), panelForDrawing.getHeight(), new DrawningObjectAirFighter(airFighter));
panelForDrawing.setIcon(new ImageIcon(bufImg));
}
private void SetMap(String mapName){
switch (mapName){
case "Простая карта":
_abstractMap = new SimpleMap();
break;
case "Карта шторма":
_abstractMap = new StormMap();
break;
}
}
public FormMap(){
super("Военный самолет");
//Panel для отрисовки
panelForDrawing.setLayout(null);
panelForDrawing.setPreferredSize(new Dimension(getWidth(), getHeight()));
panelForDrawing.setBounds(0, 0, getWidth(), getHeight());
add(panelForDrawing);
// ComboBox для выбора карты
String[] maps = {
"Простая карта",
"Карта шторма"
};
JComboBox mapComboBox = new JComboBox(maps);
mapComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox box = (JComboBox)e.getSource();
mapItem = (String)box.getSelectedItem();
SetMap(mapItem);
}
});
mapComboBox.setBounds(0, 0, 100, 30);
mapComboBox.setSelectedIndex(0);
panelForDrawing.add(mapComboBox);
// ComboBox для выбора модели двигателя
String[] engineModel = {
"Классический",
"Винтовой",
"Рeактивный"
};
JComboBox engineComboBox = new JComboBox(engineModel);
engineComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox box = (JComboBox)e.getSource();
itemEngine = (String)box.getSelectedItem();
}
});
engineComboBox.setBounds(100, 0, 100, 30);
engineComboBox.setSelectedIndex(0);
panelForDrawing.add(engineComboBox);
//ComboBox с количеством двигателей
String[] _engine = {
"2",
"4",
"6"
};
JComboBox editComboBox = new JComboBox(_engine);
editComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox box = (JComboBox)e.getSource();
item = (String)box.getSelectedItem();
}
});
editComboBox.setBounds(200, 0, 50, 30);
panelForDrawing.add(editComboBox);
// statusLabel
labelSpeed = new JLabel("Скорость:");
labelWeight = new JLabel("Вес:");
labelBodyColor = new JLabel("Цвет:");
statusLabel.add(labelSpeed);
statusLabel.add(labelWeight);
statusLabel.add(labelBodyColor);
statusLabel.setLayout(new FlowLayout(FlowLayout.LEFT));
statusLabel.setSize(new Dimension(getWidth(), 30));
// Кнопка создания
JButton buttonCreate = new JButton("Создать");
buttonCreate.setSize(100, 25);
buttonCreate.setLayout(new FlowLayout(FlowLayout.LEFT));
buttonCreate.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
var airFighter = new DrawningAirFighter((int)(Math.random() * 300 + 200),(int)(Math.random() * 3000 + 2000), new Color((int)(Math.random() * 255), (int)(Math.random() * 255), (int)(Math.random() * 255)), Integer.parseInt(item), itemEngine);
SetData(airFighter);
}
});
// Кнопка модификации
JButton buttonModific = new JButton("Модифицировать");
buttonModific.setSize(100, 25);
buttonModific.setLayout(new FlowLayout(FlowLayout.LEFT));
buttonModific.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
var airFighter = new DrawningUpgradeAirFighter((int)(Math.random() * 300 + 200),(int)(Math.random() * 3000 + 2000), new Color((int)(Math.random() * 255), (int)(Math.random() * 255), (int)(Math.random() * 255)),
new Color((int)(Math.random() * 255), (int)(Math.random()) * 255, (int)(Math.random() * 255)), ((int)(Math.random() * 2)) == 1, ((int)(Math.random() * 2)) == 1, Integer.parseInt(item), itemEngine);
SetData(airFighter);
}
});
// Контейнер кнопок и панели с информацией
Container container = new Container();
container.setPreferredSize(new Dimension(200, 100));
container.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.weightx = 10;
constraints.weighty = 10;
constraints.anchor = GridBagConstraints.WEST;
constraints.gridwidth = 1;
constraints.gridx = 0;
constraints.gridy = 0;
container.add(buttonCreate, constraints);
constraints.anchor = GridBagConstraints.CENTER;
constraints.gridx = 0;
constraints.gridy = 0;
container.add(buttonModific, constraints);
constraints.anchor = GridBagConstraints.WEST;
constraints.gridx = 0;
constraints.gridy = 1;
container.add(statusLabel, constraints);
// Контейнер с кнопками движения
Container containerDirection = new Container();
containerDirection.setLayout(new GridBagLayout());
containerDirection.setPreferredSize(new Dimension(120, 70));
GridBagConstraints constraintsDirection = new GridBagConstraints();
constraintsDirection.weightx = 40;
constraintsDirection.weighty = 40;
constraintsDirection.gridwidth = 2;
constraintsDirection.gridheight = 1;
// Кнопка Up
try {
BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\User\\IdeaProjects\\ProjectAirFighterHard\\AirFighter\\Images\\Up.png"));
Image imageUp = bufferedImage.getScaledInstance(30, 30, Image.SCALE_DEFAULT);
ImageIcon iconUp = new ImageIcon(imageUp);
buttonUp = new JButton(iconUp);
buttonUp.setPreferredSize(new Dimension(30, 30));
buttonUp.setContentAreaFilled(false);
buttonUp.setBorderPainted(false);
buttonUp.setActionCommand(Direction.Up.name());
buttonUp.addActionListener(actionListenerDirection);
constraintsDirection.gridx = 1;
constraintsDirection.gridy = 0;
containerDirection.add(buttonUp, constraintsDirection);
}catch (IOException e){}
// Кнопка Down
try {
BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\User\\IdeaProjects\\ProjectAirFighterHard\\AirFighter\\Images\\Down.png"));
Image imageDown = bufferedImage.getScaledInstance(30, 30, Image.SCALE_DEFAULT);
ImageIcon iconDown = new ImageIcon(imageDown);
buttonDown = new JButton(iconDown);
buttonDown.setActionCommand(Direction.Down.name());
buttonDown.addActionListener(actionListenerDirection);
buttonDown.setPreferredSize(new Dimension(30, 30));
buttonDown.setContentAreaFilled(false);
buttonDown.setBorderPainted(false);
constraintsDirection.gridx = 1;
constraintsDirection.gridy = 1;
containerDirection.add(buttonDown, constraintsDirection);
}catch (IOException e){}
// Кнопка Left
try {
BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\User\\IdeaProjects\\ProjectAirFighterHard\\AirFighter\\Images\\Left.png"));
Image imageLeft = bufferedImage.getScaledInstance(30, 30, Image.SCALE_DEFAULT);
ImageIcon iconLeft = new ImageIcon(imageLeft);
buttonLeft = new JButton(iconLeft);
buttonLeft.setActionCommand(Direction.Left.name());
buttonLeft.addActionListener(actionListenerDirection);
buttonLeft.setPreferredSize(new Dimension(30, 30));
buttonLeft.setContentAreaFilled(false);
buttonLeft.setBorderPainted(false);
constraintsDirection.fill = GridBagConstraints.WEST;
constraintsDirection.gridx = 0;
containerDirection.add(buttonLeft, constraintsDirection);
}catch (IOException e){}
// Кнопка Right
try {
BufferedImage bufferedImage = ImageIO.read(new File("C:\\Users\\User\\IdeaProjects\\ProjectAirFighterHard\\AirFighter\\Images\\Right.png"));
Image imageRight = bufferedImage.getScaledInstance(30, 30, Image.SCALE_DEFAULT);
ImageIcon iconRight = new ImageIcon(imageRight);
buttonRight = new JButton(iconRight);
buttonRight.setActionCommand(Direction.Right.name());
buttonRight.addActionListener(actionListenerDirection);
buttonRight.setPreferredSize(new Dimension(30, 30));
buttonRight.setContentAreaFilled(false);
buttonRight.setBorderPainted(false);
constraintsDirection.fill = GridBagConstraints.EAST;
constraintsDirection.gridx = 2;
containerDirection.add(buttonRight, constraintsDirection);
}catch (IOException e){}
constraints.anchor = GridBagConstraints.EAST;
constraints.gridx = 1;
constraints.gridy = 0;
container.add(containerDirection, constraints);
add(container, BorderLayout.SOUTH);
}
public static void main(String[] args) {
// Создание формы
FormMap _formMap = new FormMap();
_formMap.setSize (800,600);
_formMap.getRootPane().setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
_formMap.addWindowListener (new WindowAdapter () {
public void windowClosing (WindowEvent e) {
e.getWindow ().dispose ();
}
});
_formMap.setVisible(true);
}
}

View File

@ -0,0 +1,84 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
public class FormWithRandomObject extends JFrame{
JPanel panelForDrawing;
ArrayList<IDrawningObject> objectList = new ArrayList<>();
RandomObjectGenerationGeneric randObjectGeneration = new RandomObjectGenerationGeneric(10);
public FormWithRandomObject(){
super("Форма объектов");
randObjectGeneration.AddEngine(new ModelClassicEngine());
randObjectGeneration.AddEngine(new ModelScrewEngine());
randObjectGeneration.AddEngine(new ModelJetEngine());
for(int i = 0; i < 5; i++){
if(i % 2 == 0){
randObjectGeneration.AddEntity(new EntityUpgradeAirFighter(((int)(Math.random() * 300 + 200)), (int)(Math.random() * 3000 + 2000), new Color((int)(Math.random() * 255), (int)(Math.random() * 255), (int)(Math.random() * 255)),
new Color((int)(Math.random() * 255), (int)(Math.random()) * 255, (int)(Math.random() * 255)), ((int)(Math.random() * 2)) == 1, ((int)(Math.random() * 2)) == 1));
}else
randObjectGeneration.AddEntity(new EntityAirFighter(((int)(Math.random() * 300 + 200)), (int)(Math.random() * 3000 + 2000), new Color((int)(Math.random() * 255), (int)(Math.random() * 255), (int)(Math.random() * 255))));
}
// Панель для отрисовки
panelForDrawing = new JPanel(){
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Drawing(g);
}
};
panelForDrawing.setBounds(0, 0, getWidth(), getHeight());
panelForDrawing.setSize(getWidth(), getHeight());
panelForDrawing.setLayout(null);
add(panelForDrawing);
// Кнопка добавления
JButton buttonAdd = new JButton("Добавить объект");
buttonAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(objectList.size() >= 40){
return;
}
objectList.add(randObjectGeneration.RandomCreateObject());
panelForDrawing.repaint();
}
});
buttonAdd.setBounds(0, 0, 100, 30);
panelForDrawing.add(buttonAdd);
}
public static void main(String[] args) {
// Создание формы
FormWithRandomObject _formWithRandomObject = new FormWithRandomObject();
_formWithRandomObject.setSize (800,600);
_formWithRandomObject.getRootPane().setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
_formWithRandomObject.addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
e.getWindow ().dispose ();
}
});
_formWithRandomObject.setVisible(true);
}
public void Drawing(Graphics g){
int currentX = 0;
int currentY = 0;
for(int i = 0; i < objectList.size(); i++){
objectList.get(i).SetObject(currentX * 100, currentY * 100 + 30, panelForDrawing.getWidth(), panelForDrawing.getHeight());
objectList.get(i).DrawningObject(g);
currentX++;
if(currentX >= 8){
currentX = 0;
currentY++;
if(currentY >= 5){
return;
}
}
}
}
}

View File

@ -0,0 +1,53 @@
import java.util.ArrayList;
public class RandomObjectGenerationGeneric<T extends EntityAirFighter, U extends IDrawningEngine>{
private ArrayList<T> arrayEntites;
private ArrayList<U> arrayEngines;
private int maxCount;
public RandomObjectGenerationGeneric(int _maxCount){
arrayEntites = new ArrayList<T>();
arrayEngines = new ArrayList<U>();
maxCount = _maxCount;
}
public boolean AddEntity(T entity){
if(entity == null){
return false;
}else {
if(arrayEntites.size() >= maxCount){
return false;
}else {
arrayEntites.add(entity);
return true;
}
}
}
public boolean AddEngine(U engine){
if(engine == null){
return false;
}else {
if(arrayEngines.size() >= maxCount){
return false;
}else {
arrayEngines.add(engine);
return true;
}
}
}
public IDrawningObject RandomCreateObject(){
if(arrayEntites.size() == 0 && arrayEngines.size() == 0) {
return null;
}else{
EntityAirFighter entity = arrayEntites.get((int)(Math.random() * arrayEntites.size()));
IDrawningEngine engine = arrayEngines.get((int)(Math.random() * arrayEngines.size()));
int[] numberEngine = new int[]{2, 4, 6};
if(entity instanceof EntityUpgradeAirFighter upgradeEntity){
return (new DrawningObjectAirFighter(new DrawningUpgradeAirFighter(upgradeEntity.getSpeed(), upgradeEntity.getWeight(), upgradeEntity.getBodyColor(),upgradeEntity.GetDopColor(), upgradeEntity.GetDopWing(), upgradeEntity.GetRocket(), 4, engine)));
}
return (new DrawningObjectAirFighter(new DrawningAirFighter(entity.getSpeed(), entity.getWeight(), entity.getBodyColor(), 4, engine)));
}
}
}