Compare commits

...

4 Commits

Author SHA1 Message Date
Danil Kargin
d1812c0550 Лабораторная работа 3. Усложненная часть 2022-11-29 11:07:20 +04:00
Danil Kargin
797641613b Лабораторная работа 3. Базовая часть 2022-11-29 02:21:09 +04:00
Danil Kargin
f1cd73f9c4 Правки 2022-11-15 11:11:48 +04:00
Danil Kargin
65ce3bff95 Вторая лабораторная работа 2022-11-15 01:09:41 +04:00
20 changed files with 1238 additions and 67 deletions

View File

@ -0,0 +1,155 @@
import java.awt.*;
import java.awt.image.BufferedImage;
public abstract class AbstractMap {
private IDrawningObject _drawningObject = null;
protected int[][] _map = null;
protected int _width;
protected int _height;
protected float _size_x;
protected float _size_y;
protected final int _freeRoad = 0;
protected final int _barrier = 1;
public BufferedImage CreateMap(int width, int height, IDrawningObject drawningObject)
{
_width = width;
_height = height;
_drawningObject = drawningObject;
GenerateMap();
while (!SetObjectOnMap())
{
GenerateMap();
}
return DrawMapWithObject();
}
public BufferedImage MoveObject(Direction direction)
{
// Проверка коллизии
float Left = _drawningObject.GetLeftPosition();
float Right = _drawningObject.GetRightPosition();
float Top = _drawningObject.GetTopPosition();
float Bottom = _drawningObject.GetBottomPosition();
switch (direction)
{
case Right:
if (Right + _drawningObject.Step() < _width)
{
Left += _drawningObject.Step();
Right += _drawningObject.Step();
}
break;
case Left:
if (Left - _drawningObject.Step() >= 0)
{
Left -= _drawningObject.Step();
Right -= _drawningObject.Step();
}
break;
case Up:
if (Top - _drawningObject.Step() >= 0)
{
Top -= _drawningObject.Step();
Bottom -= _drawningObject.Step();
}
break;
case Down:
if (Bottom + _drawningObject.Step() < _height)
{
Top += _drawningObject.Step();
Bottom += _drawningObject.Step();
}
break;
}
if (CheckBarrier((int)Right, (int)Left, (int)Top, (int)Bottom) == 1)
{
_drawningObject.MoveObject(direction);
}
return DrawMapWithObject();
}
private int CheckBarrier(int Right, int Left, int Top, int Bottom)
{
if(Left < 0 || Top < 0 || Right > _width || Bottom > _height)
{
return 2;
}
for (int i = (int)(Top / _size_y); i <= (int)(Bottom / _size_y); i++)
{
for (int j = (int)(Left / _size_x); j <= (int)(Right / _size_x); j++)
{
if (_map[i][j] == _barrier)
return 0;
}
}
return 1;
}
private boolean SetObjectOnMap()
{
if (_drawningObject == null || _map == null)
{
return false;
}
int x = (int)(Math.random() * 10);
int y = (int)(Math.random() * 10);
_drawningObject.SetObject(x, y, _width, _height);
// Првоерка, что объект не "накладывается" на закрытые участки
float Left = _drawningObject.GetLeftPosition();
float Right = _drawningObject.GetRightPosition();
float Top = _drawningObject.GetTopPosition();
float Bottom = _drawningObject.GetBottomPosition();
float tempBottom = Bottom;
float tempTop = Top;
while (CheckBarrier((int)Right, (int)Left, (int)Top, (int)Bottom) == 0)
{
int flag = 0;
while (flag == 0)
{
y += (int)_size_y;
Top += (int)_size_y;
Bottom += (int)_size_y;
_drawningObject.SetObject(x, y, _width, _height);
flag = CheckBarrier((int)Right, (int)Left, (int)Top, (int)Bottom);
}
if (flag == 1)
{
return true;
}
x += (int)_size_x;
Left += (int)_size_x;
Right += (int)_size_x;
y = (int)tempTop;
Top = (int)tempTop;
Bottom = (int)tempBottom;
}
return false;
}
private BufferedImage DrawMapWithObject()
{
BufferedImage bufImg = new BufferedImage(_width, _height, BufferedImage.TYPE_INT_RGB);
if (_drawningObject == null || _map == null)
{
return bufImg;
}
Graphics gr = bufImg.createGraphics();
for (int i = 0; i < _map.length; ++i)
{
for (int j = 0; j < _map[0].length; ++j)
{
if (_map[i][j] == _freeRoad)
{
DrawRoadPart(gr, j, i);
}
else if (_map[i][j] == _barrier)
{
DrawBarrierPart(gr, j, i);
}
}
}
_drawningObject.DrawningObject(gr);
return bufImg;
}
protected abstract void GenerateMap();
protected abstract void DrawRoadPart(Graphics g, int i, int j);
protected abstract void DrawBarrierPart(Graphics g, int i, int j);
}

View File

@ -3,30 +3,31 @@ import java.awt.*;
public class DrawningAirFighter { public class DrawningAirFighter {
/// Объект сущности военного самолета /// Объект сущности военного самолета
public EntityAirFighter AirFighter; public EntityAirFighter AirFighter;
private DrawningEngine _engine; private IDrawningEngine _engine;
// Левая координата отрисовки самолета // Левая координата отрисовки самолета
private int _startPosX; protected int _startPosX;
// Верхняя кооридната отрисовки самолета // Верхняя кооридната отрисовки самолета
private int _startPosY; protected int _startPosY;
// Ширина окна отрисовки // Ширина окна отрисовки
private int _pictureWidth = 0; private int _pictureWidth = 0;
// Высота окна отрисовки // Высота окна отрисовки
private int _pictureHeight = 0; private int _pictureHeight = 0;
// Ширина отрисовки самолета // Ширина отрисовки самолета
final int _airFighterWidth = 80; public int _airFighterWidth = 80;
// Высота отрисовки самолета // Высота отрисовки самолета
final int _airFighterHeight = 70; public int _airFighterHeight = 70;
// Инициализация свойств // Инициализация свойств
public void Init(int speed, float weight, Color bodyColor, int numberEngine) public DrawningAirFighter(int speed, float weight, Color bodyColor, int numberEngine, IDrawningEngine engineModel)
{ {
_engine = new DrawningEngine(); _engine = engineModel;
_engine.setCodeEngine(numberEngine); _engine.SetCodeEngine(numberEngine);
AirFighter = new EntityAirFighter(); AirFighter = new EntityAirFighter(speed, weight, bodyColor);
AirFighter.Init(speed, weight, bodyColor); }
protected DrawningAirFighter(int speed, float weight, Color bodyColor, int airFighterWidth, int airFighterHeight, int numberEngines, IDrawningEngine engineModel) {
this(speed, weight, bodyColor, numberEngines, engineModel);
_airFighterWidth = airFighterWidth;
_airFighterHeight = airFighterHeight;
} }
public void SetPosition(int x, int y, int width, int height) { public void SetPosition(int x, int y, int width, int height) {
if(width < _airFighterWidth || height < _airFighterHeight) if(width < _airFighterWidth || height < _airFighterHeight)
{ {
@ -91,7 +92,7 @@ public class DrawningAirFighter {
g.fillPolygon(pointX, pointY, 20); g.fillPolygon(pointX, pointY, 20);
g.setColor(Color.BLACK); g.setColor(Color.BLACK);
g.drawPolyline(pointX, pointY, 21); g.drawPolyline(pointX, pointY, 21);
_engine.DrawEngine(g, _startPosX, _startPosY, AirFighter.getBodyColor()); _engine.Draw(g, _startPosX, _startPosY, AirFighter.getBodyColor());
} }
// Смена границ формы отрисовки // Смена границ формы отрисовки
public void ChangeBorders(int width, int height) public void ChangeBorders(int width, int height)

View File

@ -1,35 +0,0 @@
import java.awt.*;
// Класс отрисовки двигателей
public class DrawningEngine {
private Engine _engine;
public void setCodeEngine(int code){
_engine = Engine.getByCode(code);
}
// Отрисовка двигателей
public void DrawEngine(Graphics g, int startX, int startY, Color _bodyColor){
if(_engine.getEngineCode() >= 2) {
g.setColor(_bodyColor);
g.fillRect(startX+ 30, startY + 15, 13, 5);
g.fillRect(startX+ 30, startY + 50, 13, 5);
g.setColor(Color.BLACK);
g.drawRect(startX+ 30, startY + 15, 13, 5);
g.drawRect(startX+ 30, startY + 50, 13, 5);
}
if(_engine.getEngineCode() >= 4){
g.setColor(_bodyColor);
g.fillRect(startX+ 30, startY + 22, 13, 5);
g.fillRect(startX+ 30, startY + 43, 13, 5);
g.setColor(Color.BLACK);
g.drawRect(startX+ 30, startY + 22, 13, 5);
g.drawRect(startX+ 30, startY + 43, 13, 5);
}
if(_engine.getEngineCode() >= 6){
g.setColor(_bodyColor);
g.fillRect(startX+ 30, startY + 8, 13, 5);
g.fillRect(startX+ 30, startY + 57, 13, 5);
g.setColor(Color.BLACK);
g.drawRect(startX+ 30, startY + 8, 13, 5);
g.drawRect(startX+ 30, startY + 57, 13, 5);
}
}
}

View File

@ -0,0 +1,50 @@
import java.awt.*;
public class DrawningObjectAirFighter implements IDrawningObject{
public DrawningAirFighter _airFighter = null;
public float Step() {
return _airFighter != null ? _airFighter.AirFighter.Step() : 0.0F;
}
public DrawningObjectAirFighter(DrawningAirFighter airFighter) {
_airFighter = airFighter;
}
public void SetObject(int x, int y, int width, int height) {
if (_airFighter != null) {
_airFighter.SetPosition(x, y, width, height);
}
}
public void MoveObject(Direction direction) {
if (_airFighter != null) {
_airFighter.MoveTransport(direction);
}
}
public void DrawningObject(Graphics g) {
if (_airFighter != null) {
_airFighter.DrawTransport(g);
}
}
public float GetLeftPosition() {
return (float)_airFighter._startPosX;
}
public float GetRightPosition() {
return (float)(_airFighter._startPosX + _airFighter._airFighterWidth);
}
public float GetTopPosition() {
return (float)_airFighter._startPosY;
}
public float GetBottomPosition() {
return (float)(_airFighter._startPosY + _airFighter._airFighterHeight);
}
}

View File

@ -0,0 +1,54 @@
import java.awt.Color;
import java.awt.Graphics;
public class DrawningUpgradeAirFighter extends DrawningAirFighter{
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);
AirFighter = new EntityUpgradeAirFighter(speed, weight, bodyColor, dopColor, dopWing, rocket);
}
public void DrawTransport(Graphics g) {
EntityAirFighter var3 = AirFighter;
if (var3 instanceof EntityUpgradeAirFighter upgradeAirFighter) {
_startPosX += 5;
_startPosY += 5;
super.DrawTransport(g);
_startPosX -= 5;
_startPosY -= 5;
int[] _leftRocketPointY;
int[] _rightRocketPointX;
int[] _rightRocketPointY;
int[] _leftRocketPointX;
if (upgradeAirFighter.GetDopWing()) {
_leftRocketPointX = new int[]{_startPosX, _startPosX, _startPosX + 10, _startPosX};
_leftRocketPointY = new int[]{_startPosY + 35, _startPosY + 45, _startPosY + 40, _startPosY + 35};
_rightRocketPointX = new int[]{_startPosX + 50, _startPosX + 55, _startPosX + 65, _startPosX + 50};
_rightRocketPointY = new int[]{_startPosY + 35, _startPosY + 30, _startPosY + 35, _startPosY + 35};
int[] _rightWingPointX = new int[]{_startPosX + 50, _startPosX + 55, _startPosX + 65, _startPosX + 50};
int[] _rightWingPointY = new int[]{_startPosY + 45, _startPosY + 50, _startPosY + 45, _startPosY + 45};
g.setColor(upgradeAirFighter.GetDopColor());
g.fillPolygon(_leftRocketPointX, _leftRocketPointY, 3);
g.fillPolygon(_rightRocketPointX, _rightRocketPointY, 3);
g.fillPolygon(_rightWingPointX, _rightWingPointY, 3);
g.setColor(Color.BLACK);
g.drawPolygon(_leftRocketPointX, _leftRocketPointY, 4);
g.drawPolygon(_rightRocketPointX, _rightRocketPointY, 4);
g.drawPolygon(_rightWingPointX, _rightWingPointY, 4);
}
if (upgradeAirFighter.GetRocket()) {
_leftRocketPointX = new int[]{_startPosX + 35, _startPosX + 45, _startPosX + 50, _startPosX + 45, _startPosX + 35, _startPosX + 35};
_leftRocketPointY = new int[]{_startPosY, _startPosY, _startPosY + 3, _startPosY + 5, _startPosY + 5, _startPosY};
_rightRocketPointX = new int[]{_startPosX + 35, _startPosX + 45, _startPosX + 50, _startPosX + 45, _startPosX + 35, _startPosX + 35};
_rightRocketPointY = new int[]{_startPosY + 75, _startPosY + 75, _startPosY + 77, _startPosY + 80, _startPosY + 80, _startPosY + 75};
g.setColor(upgradeAirFighter.GetDopColor());
g.fillPolygon(_leftRocketPointX, _leftRocketPointY, 5);
g.fillPolygon(_rightRocketPointX, _rightRocketPointY, 5);
g.setColor(Color.BLACK);
g.drawPolygon(_leftRocketPointX, _leftRocketPointY, 6);
g.drawPolygon(_rightRocketPointX, _rightRocketPointY, 6);
}
}
}
}

View File

@ -11,7 +11,7 @@ public class EntityAirFighter {
public float Step() { public float Step() {
return Speed * 150 / Weight; return Speed * 150 / Weight;
} }
public void Init(int _speed, float _weight, Color _bodyColor){ public EntityAirFighter(int _speed, float _weight, Color _bodyColor){
Speed = _speed; Speed = _speed;
Weight = _weight; Weight = _weight;
BodyColor = _bodyColor; BodyColor = _bodyColor;

View File

@ -0,0 +1,26 @@
import java.awt.*;
public class EntityUpgradeAirFighter extends EntityAirFighter{
private Color DopColor;
private boolean DopWing;
private boolean Rocket;
public EntityUpgradeAirFighter(int speed, float weight, Color bodyColor, Color dopColor, boolean dopWing, boolean rocket) {
super(speed, weight, bodyColor);
DopColor = dopColor;
DopWing = dopWing;
Rocket = rocket;
}
public Color GetDopColor() {
return DopColor;
}
public boolean GetDopWing() {
return DopWing;
}
public boolean GetRocket() {
return Rocket;
}
}

View File

@ -13,8 +13,17 @@ public class FormAirFighter extends JFrame implements ComponentListener{
private JButton buttonDown; private JButton buttonDown;
private JButton buttonLeft; private JButton buttonLeft;
private JButton buttonRight; private JButton buttonRight;
private JLabel labelBodyColor;
private JLabel labelSpeed;
private JLabel labelWeight;
private String item = "2"; private String item = "2";
private DrawningAirFighter _airFighter; private IDrawningEngine itemEngine = null;
private DrawningAirFighter _airFighter = null;
// Выбранный объект
private DrawningAirFighter SelectedAirFighter = null;
public DrawningAirFighter GetSelectedAirFighter(){
return SelectedAirFighter;
}
// Слушатель кнопки направления // Слушатель кнопки направления
private ActionListener actionListenerDirection = new ActionListener() { private ActionListener actionListenerDirection = new ActionListener() {
@ -35,6 +44,13 @@ public class FormAirFighter extends JFrame implements ComponentListener{
panelForDrawing.repaint(); panelForDrawing.repaint();
} }
}; };
private void SetData(){
_airFighter.SetPosition((int)(Math.random() * 100 + 10), (int)(Math.random() * 100 + 10), panelForDrawing.getWidth(), panelForDrawing.getHeight());
labelSpeed.setText("Скорость: " + _airFighter.AirFighter.getSpeed());
labelWeight.setText("Вес: " + _airFighter.AirFighter.getWeight());
labelBodyColor.setText("Цвет: " + _airFighter.AirFighter.getBodyColor());
panelForDrawing.repaint();
}
public FormAirFighter(){ public FormAirFighter(){
super("Военный самолет"); super("Военный самолет");
// Panel для отрисовки // Panel для отрисовки
@ -47,18 +63,19 @@ public class FormAirFighter extends JFrame implements ComponentListener{
}catch (Exception e){} }catch (Exception e){}
} }
}; };
panelForDrawing.setLayout(new BorderLayout()); panelForDrawing.setLayout(null);
panelForDrawing.setSize(getWidth(), getHeight()); panelForDrawing.setSize(getWidth(), getHeight());
setContentPane(panelForDrawing); add(panelForDrawing);
// statusLabel // statusLabel
JLabel labelSpeed = new JLabel("Скорость:"); labelSpeed = new JLabel("Скорость:");
JLabel labelWeight = new JLabel("Вес:"); labelWeight = new JLabel("Вес:");
JLabel labelBodyColor = new JLabel("Цвет:"); labelBodyColor = new JLabel("Цвет:");
statusLabel.add(labelSpeed); statusLabel.add(labelSpeed);
statusLabel.add(labelWeight); statusLabel.add(labelWeight);
statusLabel.add(labelBodyColor); statusLabel.add(labelBodyColor);
statusLabel.setLayout(new FlowLayout(FlowLayout.LEFT)); statusLabel.setLayout(new FlowLayout(FlowLayout.LEFT));
statusLabel.setSize(new Dimension(getWidth(), 30)); statusLabel.setSize(new Dimension(800, 30));
// Кнопка создания // Кнопка создания
JButton buttonCreate = new JButton("Создать"); JButton buttonCreate = new JButton("Создать");
buttonCreate.setSize(100, 25); buttonCreate.setSize(100, 25);
@ -66,15 +83,38 @@ public class FormAirFighter extends JFrame implements ComponentListener{
buttonCreate.addActionListener(new ActionListener() { buttonCreate.addActionListener(new ActionListener() {
@Override @Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
_airFighter = new DrawningAirFighter(); _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);
_airFighter.Init((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)); SetData();
_airFighter.SetPosition((int)(Math.random() * 100 + 10), (int)(Math.random() * 100 + 10), panelForDrawing.getWidth(), panelForDrawing.getHeight());
labelSpeed.setText("Скорость: " + _airFighter.AirFighter.getSpeed());
labelWeight.setText("Вес: " + _airFighter.AirFighter.getWeight());
labelBodyColor.setText("Цвет: " + _airFighter.AirFighter.getBodyColor());
panelForDrawing.repaint();
} }
}); });
// Кнопка модификации
JButton buttonModific = new JButton("Модифицировать");
buttonModific.setSize(150, 25);
buttonModific.setLayout(new FlowLayout(FlowLayout.LEFT));
buttonModific.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
_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();
}
});
buttonModific.setBounds(50, 0, 150, 25);
panelForDrawing.add(buttonModific);
// Кнопка выбора объекта
JButton buttonSelected = new JButton("Выбрать");
buttonSelected.setSize(100, 25);
buttonSelected.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SelectedAirFighter = _airFighter;
dispatchEvent(new WindowEvent(FormAirFighter.this, WindowEvent.WINDOW_CLOSING));
dispose();
}
});
buttonSelected.setBounds(200, 0, 100, 25);
panelForDrawing.add(buttonSelected);
// Контейнер кнопок и панели с информацией // Контейнер кнопок и панели с информацией
Container container = new Container(); Container container = new Container();
container.setLayout(new GridBagLayout()); container.setLayout(new GridBagLayout());
@ -109,8 +149,35 @@ public class FormAirFighter extends JFrame implements ComponentListener{
item = (String)box.getSelectedItem(); item = (String)box.getSelectedItem();
} }
}); });
editComboBox.setEditable(true); editComboBox.setBounds(0, 0, 50, 25);
container.add(editComboBox, constraints); 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));
@ -182,7 +249,7 @@ public class FormAirFighter extends JFrame implements ComponentListener{
}catch (IOException e){} }catch (IOException e){}
constraints.anchor = GridBagConstraints.EAST; constraints.anchor = GridBagConstraints.EAST;
constraints.gridx = 1; constraints.gridx = 5;
constraints.gridy = 0; constraints.gridy = 0;
container.add(containerDirection, constraints); container.add(containerDirection, constraints);

View File

@ -0,0 +1,272 @@
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class FormMapWithSetAirFighters extends JFrame {
private JLabel panelForDrawing;
private JButton buttonUp;
private JButton buttonDown;
private JButton buttonLeft;
private JButton buttonRight;
private MapWithSetAirFightersGeneric<DrawningObjectAirFighter, AbstractMap> _mapAirFightersCollectionGeneric;
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(_mapAirFightersCollectionGeneric.MoveObject(dir)));
}
};
private FormMapWithSetAirFighters(){
super("Хранилище объектов");
setLayout(null);
// Панелька для отрисовки
panelForDrawing = new JLabel();
panelForDrawing.setBounds(0, 0, 800, 700);
add(panelForDrawing);
// Панель инструментов
JPanel panelTools = new JPanel();
panelTools.setBounds(800, 0, 200, 700);
panelTools.setLayout(null);
// ComboBox выбора карты
String[] maps = {
"Простая карта",
"Карта шторма"
};
JComboBox mapComboBox = new JComboBox(maps);
mapComboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox box = (JComboBox)e.getSource();
AbstractMap map = null;
switch ((String)box.getSelectedItem()){
case "Простая карта":
map = new SimpleMap();
break;
case "Карта шторма":
map = new StormMap();
break;
default:
map = new SimpleMap();
break;
}
_mapAirFightersCollectionGeneric = new
MapWithSetAirFightersGeneric<DrawningObjectAirFighter, AbstractMap>(
panelForDrawing.getWidth(), panelForDrawing.getHeight(), map);
}
});
mapComboBox.setBounds(0, 10, 160, 30);
mapComboBox.setSelectedIndex(0);
panelTools.add(mapComboBox);
// Кнопка добавления
JButton buttonAdd = new JButton("Добавить объект");
buttonAdd.setBounds(0, 50, 160, 30);
buttonAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_mapAirFightersCollectionGeneric == null)
{
return;
}
FormAirFighter form = new FormAirFighter();
form.setSize(500, 500);
form.setVisible(true);
form.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) { }
@Override
public void windowClosing(WindowEvent e) {
int confirm = JOptionPane.showOptionDialog(form,
"Вы точно хотите выбрать этот элемент?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.YES_OPTION){
if(form.GetSelectedAirFighter() == null) {
JOptionPane.showMessageDialog(panelTools, "Объект не удалось добавить");
return;
}
DrawningObjectAirFighter airFighter = new DrawningObjectAirFighter(form.GetSelectedAirFighter());
if (_mapAirFightersCollectionGeneric.Add(airFighter) == 0)
{
JOptionPane.showMessageDialog(panelTools, "Объект добавлен");
panelForDrawing.setIcon(new ImageIcon(_mapAirFightersCollectionGeneric.ShowSet()));
}
}
}
@Override
public void windowClosed(WindowEvent e) {}
@Override
public void windowIconified(WindowEvent e) {}
@Override
public void windowDeiconified(WindowEvent e) {}
@Override
public void windowActivated(WindowEvent e) {}
@Override
public void windowDeactivated(WindowEvent e) {}
});
}
});
panelTools.add(buttonAdd);
// Текстовое поля для получения индекса
JTextField textFieldIndex = new JTextField();
textFieldIndex.setBounds(0, 90, 160, 30);
panelTools.add(textFieldIndex);
// Кнопка удаления
// Кнопка добавления
JButton buttonRemove = new JButton("Удалить объект");
buttonRemove.setBounds(0, 130, 160, 30);
buttonRemove.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
if (textFieldIndex.getText().isEmpty()) {
return;
}
int confirm = JOptionPane.showOptionDialog(FormMapWithSetAirFighters.this,
"Вы точно хотите удалить объект?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.NO_OPTION) {
return;
}
int pos = Integer.parseInt(textFieldIndex.getText());
if (_mapAirFightersCollectionGeneric.Remove(pos) != null) {
JOptionPane.showMessageDialog(panelTools, "Объект удален");
panelForDrawing.setIcon(new ImageIcon(_mapAirFightersCollectionGeneric.ShowSet()));
} else {
JOptionPane.showMessageDialog(panelTools, "Не удалось удалить объект");
}
}catch (Exception ex){
JOptionPane.showMessageDialog(panelTools, "Неккоректный ввод");
}
}
});
panelTools.add(buttonRemove);
// Кнопка перехода в хранилище
JButton buttonShowStorage = new JButton("Посмотреть хранилище");
buttonShowStorage.setBounds(0, 170, 160, 30);
buttonShowStorage.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_mapAirFightersCollectionGeneric == null)
{
return;
}
panelForDrawing.setIcon(new ImageIcon(_mapAirFightersCollectionGeneric.ShowSet()));
}
});
panelTools.add(buttonShowStorage);
// Кнопка перехода на карту
JButton buttonShowOnMap = new JButton("Посмотреть карту");
buttonShowOnMap.setBounds(0, 210, 160, 30);
buttonShowOnMap.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (_mapAirFightersCollectionGeneric == null)
{
return;
}
panelForDrawing.setIcon(new ImageIcon(_mapAirFightersCollectionGeneric.ShowOnMap()));
}
});
panelTools.add(buttonShowOnMap);
// Контейнер с кнопками движения
Container containerDirection = new Container();
containerDirection.setPreferredSize(new Dimension(120, 70));
containerDirection.setLayout(new GridBagLayout());
GridBagConstraints constraintsDirection = new GridBagConstraints();
constraintsDirection.weightx = 40;
constraintsDirection.weighty = 40;
constraintsDirection.gridwidth = 2;
constraintsDirection.gridheight = 1;
// Кнопка Up
try {
BufferedImage bufferedImage = ImageIO.read(new File("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("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("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("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){}
containerDirection.setBounds(20, 500, 110, 70);
panelTools.add(containerDirection);
add(panelTools);
}
public static void main(String[] args) {
// Создание формы
FormMapWithSetAirFighters _formMap = new FormMapWithSetAirFighters();
_formMap.setSize (1000,700);
_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,7 @@
import java.awt.*;
public interface IDrawningEngine {
void SetCodeEngine(int code);
void DrawEngine(Graphics g, int startX, int startY, Color _bodyColor);
void Draw(Graphics g, int startX, int startY, Color _bodyColor);
}

View File

@ -0,0 +1,19 @@
import java.awt.*;
public interface IDrawningObject {
float Step();
void SetObject(int var1, int var2, int var3, int var4);
void MoveObject(Direction var1);
void DrawningObject(Graphics var1);
float GetLeftPosition();
float GetRightPosition();
float GetTopPosition();
float GetBottomPosition();
}

View File

@ -0,0 +1,143 @@
import java.awt.*;
import java.awt.image.BufferedImage;
public class MapWithSetAirFightersGeneric <T extends IDrawningObject, U extends AbstractMap>{
/// Ширина окна отрисовки
private final int _pictureWidth;
/// Высота окна отрисовки
private final int _pictureHeight;
/// Размер занимаемого объектом места (ширина)
private final int _placeSizeWidth = 210;
/// Размер занимаемого объектом места (высота)
private final int _placeSizeHeight = 90;
/// Набор объектов
private final SetAirFightersGeneric<T> _setAirFighters;
/// Карта
private final U _map;
/// Конструктор
public MapWithSetAirFightersGeneric(int picWidth, int picHeight, U map)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_setAirFighters = new SetAirFightersGeneric<T>(width * height);
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
}
/// Добавление в хранилище
public int Add(T airFighter)
{
return _setAirFighters.Insert(airFighter);
}
/// Удаление из хранилища
public T Remove(int position)
{
return _setAirFighters.Remove(position);
}
/// Вывод всего набора объектов
public BufferedImage ShowSet()
{
BufferedImage bimg = new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_RGB);
Graphics gr = bimg.createGraphics();
DrawBackground(gr);
DrawAirFighters(gr);
return bimg;
}
/// Просмотр объекта на карте
public BufferedImage ShowOnMap()
{
Shaking();
for (int i = 0; i < _setAirFighters.Count(); i++)
{
var airFighter = _setAirFighters.Get(i);
if (airFighter != null)
{
return _map.CreateMap(_pictureWidth, _pictureHeight, airFighter);
}
}
return new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_RGB);
}
/// Перемещение объекта по крате
public BufferedImage MoveObject(Direction direction)
{
if (_map != null)
{
return _map.MoveObject(direction);
}
return new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_RGB);
}
/// "Взбалтываем" набор, чтобы все элементы оказались в начале
private void Shaking()
{
int j = _setAirFighters.Count() - 1;
for (int i = 0; i < _setAirFighters.Count(); i++)
{
if (_setAirFighters.Get(i) == null)
{
for (; j > i; j--)
{
var airFighter = _setAirFighters.Get(j);
if (airFighter != null)
{
_setAirFighters.Insert(airFighter, i);
_setAirFighters.Remove(j);
break;
}
}
if (j <= i)
{
return;
}
}
}
}
/// Метод отрисовки фона
private void DrawBackground(Graphics g)
{
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{//линия рамзетки места
g.setColor(Color.BLACK);
g.drawLine(i * _placeSizeWidth, j * _placeSizeHeight, i *
_placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
int[] pointX = new int[]{i * _placeSizeWidth + _placeSizeWidth / 5,(i + 1) * _placeSizeWidth - _placeSizeWidth / 5,
(i + 1) * _placeSizeWidth - _placeSizeWidth / 5,i * _placeSizeWidth + _placeSizeWidth / 5};
int[] pointY = new int[]{j * _placeSizeHeight + _placeSizeHeight / 10, j * _placeSizeHeight + _placeSizeHeight / 10,
(j + 1) * _placeSizeHeight - _placeSizeHeight / 10, (j + 1) * _placeSizeHeight - _placeSizeHeight / 10};
g.setColor(Color.GRAY);
g.fillPolygon(pointX, pointY, 4);
}
g.setColor(Color.BLACK);
g.drawLine(i * _placeSizeWidth, 0, i * _placeSizeWidth,
(_pictureHeight / _placeSizeHeight) * _placeSizeHeight);
}
}
/// Метод прорисовки объектов
private void DrawAirFighters(Graphics g)
{
int currentWidth = _pictureWidth / _placeSizeWidth - 1;
int currentHeight = _pictureHeight / _placeSizeHeight - 1;
for (int i = 0; i < _setAirFighters.Count(); i++)
{
if(_setAirFighters.Get(i) != null) {
_setAirFighters.Get(i).SetObject(currentWidth * _placeSizeWidth + 50, currentHeight * _placeSizeHeight + 10, _pictureWidth, _pictureHeight);
_setAirFighters.Get(i).DrawningObject(g);
}
if(currentWidth > 0)
{
currentWidth -= 1;
}
else
{
if(currentHeight > 0)
{
currentHeight -= 1;
currentWidth = _pictureWidth / _placeSizeWidth - 1;
}else return;
}
}
}
}

View File

@ -0,0 +1,29 @@
import java.awt.*;
// Класс отрисовки двигателей
public class ModelClassicEngine implements IDrawningEngine{
private Engine _engine;
public void SetCodeEngine(int code){
_engine = Engine.getByCode(code);
}
// Отрисовка двигателей
public void DrawEngine(Graphics g, int startX, int startY, Color _bodyColor){
g.setColor(_bodyColor);
g.fillRect(startX, startY, 13, 5);
g.setColor(Color.BLACK);
g.drawRect(startX, startY, 13, 5);
}
public void Draw(Graphics g, int startX, int startY, Color _bodyColor){
if(_engine.getEngineCode() >= 2) {
DrawEngine(g, startX + 30, startY + 15, _bodyColor);
DrawEngine(g, startX + 30, startY + 50, _bodyColor);
}
if(_engine.getEngineCode() >= 4){
DrawEngine(g, startX + 30, startY + 22, _bodyColor);
DrawEngine(g, startX + 30, startY + 43, _bodyColor);
}
if(_engine.getEngineCode() >= 6){
DrawEngine(g, startX + 30, startY + 8, _bodyColor);
DrawEngine(g, startX + 30, startY + 57, _bodyColor);
}
}
}

View File

@ -0,0 +1,32 @@
import java.awt.*;
public class ModelJetEngine implements IDrawningEngine{
private Engine _engine;
public void SetCodeEngine(int code){
_engine = Engine.getByCode(code);
}
// Отрисовка двигателя
public void DrawEngine(Graphics g, int startX, int startY, Color _bodyColor){
int[] pointX = new int[]{startX, startX + 5, startX + 15, startX + 15, startX + 5, startX, startX};
int[] pointY = new int[]{startY + 1, startY, startY, startY + 5, startY + 5, startY + 4, startY + 1};
g.setColor(_bodyColor);
g.fillPolygon(pointX, pointY, 6);
g.setColor(Color.BLACK);
g.drawPolygon(pointX, pointY, 7);
}
// Отрисовка двигателей
public void Draw(Graphics g, int startX, int startY, Color _bodyColor){
if(_engine.getEngineCode() >= 2) {
DrawEngine(g, startX + 30, startY + 15, _bodyColor);
DrawEngine(g, startX + 30, startY + 50, _bodyColor);
}
if(_engine.getEngineCode() >= 4){
DrawEngine(g, startX + 30, startY + 22, _bodyColor);
DrawEngine(g, startX + 30, startY + 43, _bodyColor);
}
if(_engine.getEngineCode() >= 6){
DrawEngine(g, startX + 30, startY + 8, _bodyColor);
DrawEngine(g, startX + 30, startY + 57, _bodyColor);
}
}
}

View File

@ -0,0 +1,31 @@
import java.awt.*;
public class ModelScrewEngine implements IDrawningEngine{
private Engine _engine;
public void SetCodeEngine(int code){
_engine = Engine.getByCode(code);
}
public void DrawEngine(Graphics g, int startX, int startY, Color _bodyColor){
g.setColor(_bodyColor);
g.fillRect(startX, startY, 13, 5);
g.setColor(Color.BLACK);
g.drawRect(startX, startY, 13, 5);
g.drawLine(startX + 13, startY + 2, startX + 15, startY + 2);
g.drawLine(startX + 15, startY, startX + 15, startY + 5);
}
// Отрисовка двигателей
public void Draw(Graphics g, int startX, int startY, Color _bodyColor){
if(_engine.getEngineCode() >= 2) {
DrawEngine(g, startX + 30, startY + 15, _bodyColor);
DrawEngine(g, startX + 30, startY + 50, _bodyColor);
}
if(_engine.getEngineCode() >= 4){
DrawEngine(g, startX + 30, startY + 22, _bodyColor);
DrawEngine(g, startX + 30, startY + 43, _bodyColor);
}
if(_engine.getEngineCode() >= 6){
DrawEngine(g, startX + 30, startY + 8, _bodyColor);
DrawEngine(g, startX + 30, startY + 57, _bodyColor);
}
}
}

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)));
}
}
}

View File

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

View File

@ -0,0 +1,42 @@
import java.awt.*;
public class SimpleMap extends AbstractMap{
// Цвет открытого участка
private Color roadColor = new Color(153, 217, 234);
// Цвет закрытого участка
private Color barrierColor = Color.GRAY;
@Override
protected void GenerateMap() {
_map = new int[100][100];
_size_x = (float)_width / _map[0].length;
_size_y = (float)_height / _map.length;
int counter = 0;
for (int i = 0; i < _map.length; ++i)
{
for (int j = 0; j < _map[0].length; ++j)
{
_map[i][j] = _freeRoad;
}
}
while (counter < 50)
{
int x = (int)(Math.random() * 100);
int y = (int)(Math.random() * 100);
if (_map[x][y] == _freeRoad)
{
_map[x][y] = _barrier;
counter++;
}
}
}
@Override
protected void DrawRoadPart(Graphics g, int i, int j) {
g.setColor(roadColor);
g.fillRect((int)(i * _size_x), (int)(j * _size_y), (int)((i + 1) * _size_x), (int)((j + 1) * _size_y));
}
@Override
protected void DrawBarrierPart(Graphics g, int i, int j) {
g.setColor(barrierColor);
g.fillRect((int)(i * _size_x), (int)(j * _size_y), (int)((i + 1) * _size_x), (int)((j + 1) * _size_y));
}
}

View File

@ -0,0 +1,49 @@
import java.awt.*;
public class StormMap extends AbstractMap{
// Цвет открытого участка
private Color roadColor = new Color(168, 168, 168);
// Дополнительный цвет открытого участка
private Color dopRoadColor = Color.LIGHT_GRAY;
// Цвет закрытого участка
private Color barrierColor = Color.BLACK;
@Override
protected void GenerateMap() {
_map = new int[100][100];
_size_x = (float)_width / _map[0].length;
_size_y = (float)_height / _map.length;
int counter = 0;
for (int i = 0; i < _map.length; ++i)
{
for (int j = 0; j < _map[0].length; ++j)
{
_map[i][j] = _freeRoad;
}
}
while (counter < 50)
{
int x = (int)(Math.random() * 100);
int y = (int)(Math.random() * 100);
if (_map[x][y] == _freeRoad)
{
_map[x][y] = _barrier;
counter++;
}
}
}
@Override
protected void DrawRoadPart(Graphics g, int i, int j) {
if((int)(Math.random() * 2) == 1){
g.setColor(roadColor);
g.fillRect((int)(i * _size_x), (int)(j * _size_y), (int)((i + 1) * _size_x), (int)((j + 1) * _size_y));
}else {
g.setColor(dopRoadColor);
g.fillRect((int) (i * _size_x), (int) (j * _size_y), (int) ((i + 1) * _size_x), (int) ((j + 1) * _size_y));
}
}
@Override
protected void DrawBarrierPart(Graphics g, int i, int j) {
g.setColor(barrierColor);
g.fillRect((int) (i * _size_x), (int) (j * _size_y), (int) ((i + 1) * _size_x), (int) ((j + 1) * _size_y));
}
}