Compare commits

...

51 Commits

Author SHA1 Message Date
7839cb7aad Fixes 2022-12-05 23:43:06 +04:00
4cadb6385c Fixes 2022-12-05 23:42:43 +04:00
3845906a87 Added logging 2022-12-05 23:37:38 +04:00
09e3dfc336 Added exception handling to FormMapWithSetArtilleries 2022-12-05 23:00:06 +04:00
36a610081e Added exceptions to MapsCollection 2022-12-05 22:34:50 +04:00
60bc67a8f5 Added own exception FileFormatException 2022-12-05 22:34:29 +04:00
8d85818dae Added exceptions to SetArtilleriesGeneric 2022-12-05 22:12:14 +04:00
bbb24c454f Added own exceptions 2022-12-05 22:04:47 +04:00
8abded35c8 Fixes 2022-11-22 15:59:06 +04:00
d553376508 Work is done 06 2022-11-21 01:48:43 +04:00
9b23e2f119 Base part has been completed 2022-11-21 01:04:53 +04:00
96d181608f Minor fixes in ArtillerySerde. Added MapsCollection saving to and loading from file 2022-11-20 23:07:02 +04:00
ebc0f07204 Added MapWithSetArtilleriesGeneric serialization and deserialization 2022-11-20 22:41:03 +04:00
8d4407de4c Added DrawingObjectArtillery serialization and deserialization 2022-11-20 22:27:21 +04:00
ade75a5dc3 Added DrawingArtillery serialization and deserialization 2022-11-20 22:20:41 +04:00
63c379da6f Now you can get rollers' count 2022-11-20 22:03:58 +04:00
dc45239592 Added RollersCount serialization 2022-11-20 22:02:02 +04:00
e1c0918dba Merge branch 'LabWork04' into LabWork05 2022-11-08 16:33:40 +04:00
ccab9cd620 Fixes 2022-11-08 16:32:08 +04:00
5c582f70b3 Fixes 2022-11-08 16:19:52 +04:00
680274195d Some fixes 2022-11-07 15:32:44 +04:00
df909891d8 Some refactoring 2022-11-06 21:56:53 +04:00
dd425e3071 Work is done 5. There might be mistakes 2022-11-06 20:33:15 +04:00
e60990067a LabWork04 completed 2022-11-05 19:18:29 +04:00
392e97f71f Fix 2022-11-05 18:48:58 +04:00
b0e2bf7947 Second stage: Fixes
Third stage: Completed
Beginning advanced task
2022-11-05 18:38:20 +04:00
e2f76ef916 Second stage: Completed 2022-11-05 16:40:00 +04:00
0ae6527361 First stage: Refactoring MapWithSetArtilleriesGeneric 2022-11-05 16:31:00 +04:00
9c4f1d4327 First stage: Fixed SetArtilleriesGeneric 2022-11-05 16:26:26 +04:00
8fc2d24e7e First stage: Array was replaced with ArrayList 2022-11-05 16:20:44 +04:00
385eedd0b9 Work is done 3 2022-10-25 16:53:45 +04:00
cd2b9474d4 Fixes 2022-10-25 01:58:38 +04:00
bea4da357c Changed FormArtillery 2022-10-24 23:03:50 +04:00
a5112dcbdd Added MapWithSetArtilleriesGeneric 2022-10-24 22:36:41 +04:00
b481b124a8 Fix SetArtilleriesGeneric 2022-10-24 22:22:51 +04:00
675c220c79 Added SetArtilleriesGeneric 2022-10-24 22:14:33 +04:00
fb4c5f3416 Work is done 02 2022-10-08 23:03:27 +04:00
1ef0f5465b Added two new types of rollers to draw 2022-10-08 22:22:51 +04:00
fbd46924d1 Added interface IDrawingRollers 2022-10-08 19:19:17 +04:00
0abd2c2ca3 Fixes 2022-10-08 17:51:17 +04:00
7758a3b7cc New form has been created. General work is done 2022-10-08 17:30:41 +04:00
a2e79b08bd Added class ForestMap 2022-10-08 16:16:03 +04:00
0df20f4008 Added class SimpleMap 2022-10-08 16:04:32 +04:00
ed422215f0 Added class AbstractMap 2022-10-08 15:40:01 +04:00
6840f8220e Added class DrawingObjectArtillery 2022-10-08 15:25:07 +04:00
f990882127 Added interface IDrawingObject 2022-10-08 15:16:47 +04:00
4e7db63b49 Added class DrawingAdvancedArtillery 2022-10-08 15:13:24 +04:00
145d4dac45 Added class EntityAdvancedArtillery 2022-10-08 15:03:57 +04:00
e890502041 Added new option to Direction enum 2022-10-08 14:56:34 +04:00
0e85f72177 Changed some private fields to protected in DrawingArtillery. Added method getCurrentPosition 2022-10-08 14:55:39 +04:00
02566d7957 Constructors have been added 2022-10-08 14:43:17 +04:00
35 changed files with 2428 additions and 48 deletions

103
AbstractMap.java Normal file
View File

@ -0,0 +1,103 @@
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
public abstract class AbstractMap {
private IDrawingObject _drawingObject = null;
protected int[][] _map = null;
protected int _width;
protected int _height;
protected float _size_x;
protected float _size_y;
protected final Random _random = new Random();
protected final int _freeRoad = 0;
protected final int _barrier = 1;
public Image createMap(int width, int height, IDrawingObject drawingObject) {
_width = width;
_height = height;
_drawingObject = drawingObject;
do {
generateMap();
} while (!setObjectOnMap());
return drawMapWithObject();
}
public Image moveObject(Direction direction) {
_drawingObject.moveObject(direction);
if (objectIntersects()) {
switch (direction) {
case Left -> _drawingObject.moveObject(Direction.Right);
case Right -> _drawingObject.moveObject(Direction.Left);
case Up -> _drawingObject.moveObject(Direction.Down);
case Down -> _drawingObject.moveObject(Direction.Up);
}
}
return drawMapWithObject();
}
private boolean setObjectOnMap() {
if (_drawingObject == null || _map == null)
{
return false;
}
for (int i = 2; i < _map.length; i++)
{
for (int j = 2; j < _map[i].length; j++)
{
_drawingObject.setObject((int) (i * _size_x), (int) (j * _size_y), _width, _height);
if (!objectIntersects()) return true;
}
}
return true;
}
private boolean objectIntersects() {
float[] location = _drawingObject.getCurrentPosition();
Rectangle self = new Rectangle((int) location[0], (int) location[2], (int) location[1] - (int) location[0], (int) location[3] - (int) location[2]);
for (int i = 0; i < _map.length; i++)
{
for (int j = 0; j < _map[i].length; j++)
{
if (_map[i][j] == _barrier)
{
if (self.intersects(new Rectangle(j * (int) _size_x, i * (int) _size_y, (int) _size_x, (int) _size_y)))
{
return true;
}
}
}
}
return false;
}
private Image drawMapWithObject() {
Image img = new BufferedImage(_width, _height, BufferedImage.TYPE_INT_ARGB);
if (_drawingObject == null || _map == null) {
return img;
}
Graphics2D g = (Graphics2D) img.getGraphics();
for (int i = 0; i < _map.length; ++i)
{
for (int j = 0; j < _map[i].length; ++j)
{
if (_map[i][j] == _freeRoad)
{
drawRoadPart(g, i, j);
} else if (_map[i][j] == _barrier)
{
drawBarrierPart(g, i, j);
}
}
}
_drawingObject.drawingObject(g);
return img;
}
protected abstract void generateMap();
protected abstract void drawRoadPart(Graphics2D g, int i, int j);
protected abstract void drawBarrierPart(Graphics2D g, int i, int j);
}

View File

@ -0,0 +1,21 @@
public class ArtilleryNotFoundException extends RuntimeException {
public ArtilleryNotFoundException() {
}
public ArtilleryNotFoundException(int i) {
super("Не найден объект по позиции " + i);
}
public ArtilleryNotFoundException(String message) {
super(message);
}
public ArtilleryNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public ArtilleryNotFoundException(Throwable cause) {
super(cause);
}
}

69
ArtillerySerde.java Normal file
View File

@ -0,0 +1,69 @@
import java.awt.*;
public class ArtillerySerde { // Artillery Serialization/Deserialization
private static final char _separatorForObject = ':';
public static DrawingArtillery deserialize(String info) {
String[] strings = info.split(Character.toString(_separatorForObject));
int speed = Integer.parseInt(strings[0]);
float weight = Float.parseFloat(strings[1]);
Color bodyColor = new Color(Integer.parseInt(strings[2]));
IDrawingRollers rollers = switch (strings[3]) {
case "DrawingRollers" -> new DrawingRollers(Integer.parseInt(strings[4]), bodyColor);
case "DrawingCrossRollers" -> new DrawingCrossRollers(Integer.parseInt(strings[4]), bodyColor);
case "DrawingSquaredRollers" -> new DrawingSquaredRollers(Integer.parseInt(strings[4]), bodyColor);
default -> null;
};
if (strings.length == 5) {
EntityArtillery entity = new EntityArtillery(speed, weight, bodyColor);
return new DrawingArtillery(entity, rollers);
}
if (strings.length == 8) {
Color dopColor = new Color(Integer.parseInt(strings[5]));
boolean weapon = Boolean.parseBoolean(strings[6]);
boolean salvoBattery = Boolean.parseBoolean(strings[7]);
EntityAdvancedArtillery entity = new EntityAdvancedArtillery(speed, weight, bodyColor, dopColor, weapon, salvoBattery);
return new DrawingAdvancedArtillery(entity, rollers);
}
return null;
}
public static String serialize(DrawingArtillery drawingArtillery) {
EntityArtillery artillery = drawingArtillery.getArtillery();
String result = String.format(
"%d%c%s%c%d%c%s%c%d",
artillery.getSpeed(),
_separatorForObject,
artillery.getWeight(),
_separatorForObject,
artillery.getBodyColor().getRGB(),
_separatorForObject,
drawingArtillery.getRollers().getClass().getSimpleName(),
_separatorForObject,
drawingArtillery.getRollers().getRollersCount()
);
if (!(artillery instanceof EntityAdvancedArtillery advanced)) {
return result;
}
return String.format(
"%s%c%d%c%b%c%b",
result,
_separatorForObject,
advanced.getDopColor().getRGB(),
_separatorForObject,
advanced.getWeapon(),
_separatorForObject,
advanced.getSalvoBattery()
);
}
}

View File

@ -2,5 +2,6 @@ public enum Direction {
Up,
Down,
Left,
Right
Right,
None
}

View File

@ -0,0 +1,43 @@
import java.awt.*;
public class DrawingAdvancedArtillery extends DrawingArtillery {
public DrawingAdvancedArtillery(int speed, float weight, Color bodyColor, int rollersCount, Color dopColor, boolean weapon, boolean salvoBattery) {
super(speed, weight, bodyColor, rollersCount, 80, 50);
artillery = new EntityAdvancedArtillery(speed, weight, bodyColor, dopColor, weapon, salvoBattery);
}
public DrawingAdvancedArtillery(EntityAdvancedArtillery entity, IDrawingRollers rollers) {
super(entity, rollers);
}
@Override
public void drawTransport(Graphics2D g) {
if (!(artillery instanceof EntityAdvancedArtillery advancedArtillery)) {
return;
}
g.setColor(advancedArtillery.getDopColor());
if (advancedArtillery.getWeapon()) {
g.setStroke(new BasicStroke(8));
g.drawLine((int) _startPosX + _artilleryWidth / 2, (int) _startPosY + _artilleryHeight / 10, (int) _startPosX + _artilleryWidth, (int) _startPosY);
}
g.setStroke(new BasicStroke(6));
if (advancedArtillery.getSalvoBattery()) {
g.drawLine((int) _startPosX + _artilleryWidth / 4, (int) _startPosY + _artilleryHeight / 4, (int) _startPosX + _artilleryWidth / 4 + _artilleryHeight / 4, (int) _startPosY - 5);
g.drawLine((int) _startPosX + _artilleryWidth / 4 - _artilleryHeight / 4, (int) _startPosY + _artilleryHeight / 4, (int) _startPosX + _artilleryWidth / 4, (int) _startPosY - 5);
g.drawLine((int) _startPosX + _artilleryWidth / 4 - _artilleryHeight / 2, (int) _startPosY + _artilleryHeight / 4, (int) _startPosX + _artilleryWidth / 4 - _artilleryHeight / 4, (int) _startPosY - 5);
}
super.drawTransport(g);
}
@Override
public void setColor(Color color) {
var art = (EntityAdvancedArtillery) artillery;
artillery = new EntityAdvancedArtillery(art.getSpeed(), art.getWeight(), color, art.getDopColor(), art.getWeapon(), art.getSalvoBattery());
}
public void setDopColor(Color color) {
var art = (EntityAdvancedArtillery) artillery;
artillery = new EntityAdvancedArtillery(art.getSpeed(), art.getWeight(), art.getBodyColor(), color, art.getWeapon(), art.getSalvoBattery());
}
}

View File

@ -1,27 +1,40 @@
import java.awt.*;
public class DrawingArtillery {
private EntityArtillery artillery;
private DrawingRollers drawingRollers;
private float _startPosX;
private float _startPosY;
protected EntityArtillery artillery;
protected IDrawingRollers drawingRollers;
protected float _startPosX;
protected float _startPosY;
private Integer _pictureWidth = null;
private Integer _pictureHeight = null;
private final int _artilleryWidth = 80;
private final int _artilleryHeight = 50;
protected int _artilleryWidth = 80;
protected int _artilleryHeight = 50;
public EntityArtillery getArtillery() {
return artillery;
}
public void Init(int speed, float weight, Color bodyColor, int rollersCount) {
artillery = new EntityArtillery();
artillery.Init(speed, weight, bodyColor);
drawingRollers = new DrawingRollers();
drawingRollers.Init(rollersCount, bodyColor);
public IDrawingRollers getRollers() {
return drawingRollers;
}
public void SetPosition(int x, int y, int width, int height) {
public DrawingArtillery(int speed, float weight, Color bodyColor, int rollersCount) {
artillery = new EntityArtillery(speed, weight, bodyColor);
drawingRollers = RollersType.random(rollersCount, bodyColor);
}
protected DrawingArtillery(int speed, float weight, Color bodyColor, int rollersCount, int artilleryWidth, int artilleryHeight) {
this(speed, weight, bodyColor, rollersCount);
_artilleryWidth = artilleryWidth;
_artilleryHeight = artilleryHeight;
}
public DrawingArtillery(EntityArtillery entity, IDrawingRollers rollers) {
artillery = entity;
drawingRollers = rollers;
}
public void setPosition(int x, int y, int width, int height) {
if (x < 0 || x + _artilleryWidth >= width)
{
return;
@ -82,7 +95,7 @@ public class DrawingArtillery {
return;
}
g.setColor(artillery.getBodyColor() != null ? artillery.getBodyColor() : Color.BLACK);
g.fillRect((int) (_startPosX + _artilleryWidth / 8 * 2), (int) _startPosY, _artilleryWidth / 8 * 4, _artilleryWidth / 5);
g.fillRect((int) (_startPosX + _artilleryWidth / 8 * 2), (int) _startPosY, _artilleryWidth / 8 * 4, _artilleryHeight / 5);
g.fillRect((int) _startPosX, (int) (_startPosY + _artilleryHeight / 5), _artilleryWidth, _artilleryHeight / 3);
@ -110,4 +123,16 @@ public class DrawingArtillery {
_startPosY = _pictureHeight - _artilleryHeight;
}
}
public float[] getCurrentPosition() {
return new float[] { _startPosX, _startPosX + _artilleryWidth - 1, _startPosY, _startPosY + _artilleryHeight -1 };
}
public void setColor(Color color) {
artillery = new EntityArtillery(artillery.getSpeed(), artillery.getWeight(), color);
}
public void setRollers(IDrawingRollers rollers) {
drawingRollers = rollers;
}
}

90
DrawingCrossRollers.java Normal file
View File

@ -0,0 +1,90 @@
import java.awt.*;
public class DrawingCrossRollers implements IDrawingRollers {
private RollersCount rollersCount;
private Color color;
public DrawingCrossRollers(int rollersCount, Color bodyColor) {
setRollersCount(rollersCount);
color = bodyColor;
}
public void setRollersCount(int num) {
if (num <= 4) {
rollersCount = RollersCount.Four;
} else if (num >= 6) {
rollersCount = RollersCount.Six;
} else {
rollersCount = RollersCount.Five;
}
}
public int getRollersCount() {
return rollersCount.getValue();
}
public void draw(Graphics2D g, int x, int y, int artilleryWidth, int artilleryHeight) {
g.setColor(color != null ? color : Color.BLACK);
g.fillOval(x + artilleryWidth / 20, y + artilleryHeight * 7 / 15, artilleryWidth * 4 / 20, artilleryHeight * 10 / 32);
g.fillOval(x + artilleryWidth * 15 / 20, y + artilleryHeight * 7 / 15, artilleryWidth * 4 / 20, artilleryHeight * 10 / 32);
switch (rollersCount) {
case Six: {
g.fillOval(x + artilleryWidth * 8 / 20, y + artilleryHeight * 10 / 16, artilleryWidth * 2 / 20, artilleryHeight * 6 / 32);
}
case Five: {
g.fillOval(x + artilleryWidth * 10 / 20, y + artilleryHeight * 10 / 16, artilleryWidth * 2 / 20, artilleryHeight * 6 / 32);
}
case Four: {
g.fillOval(x + artilleryWidth * 5 / 20, y + artilleryHeight * 9 / 16, artilleryWidth * 3 / 20, artilleryHeight * 8 / 32);
g.fillOval(x + artilleryWidth * 12 / 20, y + artilleryHeight * 9 / 16, artilleryWidth * 3 / 20, artilleryHeight * 8 / 32);
}
}
drawOrnament(g, x, y, artilleryWidth, artilleryHeight);
}
private void drawOrnament(Graphics2D g, int x, int y, int artilleryWidth, int artilleryHeight) {
g.setStroke(new BasicStroke(1));
g.setColor(Color.BLACK);
g.drawLine(x + artilleryWidth / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 5 / 32, x + artilleryWidth * 5 / 20 - 1, y + artilleryHeight * 7 / 15 + artilleryHeight * 5 / 32);
g.drawLine(x + artilleryWidth * 3 / 20, y + artilleryHeight * 7 / 15, x + artilleryWidth * 3 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 10 / 32);
g.drawLine(x + artilleryWidth * 2 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 5 / 64, x + artilleryWidth * 4 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 15 / 64);
g.drawLine(x + artilleryWidth * 4 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 5 / 64, x + artilleryWidth * 2 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 15 / 64);
g.drawLine(x + artilleryWidth * 15 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 5 / 32, x + artilleryWidth * 19 / 20 - 1, y + artilleryHeight * 7 / 15 + artilleryHeight * 5 / 32);
g.drawLine(x + artilleryWidth * 17 / 20, y + artilleryHeight * 7 / 15, x + artilleryWidth * 17 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 10 / 32);
g.drawLine(x + artilleryWidth * 16 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 5 / 64, x + artilleryWidth * 18 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 15 / 64);
g.drawLine(x + artilleryWidth * 18 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 5 / 64, x + artilleryWidth * 16 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 15 / 64);
switch(rollersCount) {
case Six: {
g.drawLine(x + artilleryWidth * 8 / 20, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32, x + artilleryWidth * 10 / 20, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32);
g.drawLine(x + artilleryWidth * 9 / 20, y + artilleryHeight * 10 / 16, x + artilleryWidth * 9 / 20, y + artilleryHeight * 10 / 16 + artilleryHeight * 6 / 32);
g.drawLine(x + artilleryWidth * 8 / 20 + artilleryWidth * 2 / 80, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32 - artilleryHeight * 3 / 64, x + artilleryWidth * 10 / 20 - artilleryWidth * 2 / 80, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32 + artilleryHeight * 3 / 64);
g.drawLine(x + artilleryWidth * 9 / 20 + artilleryWidth * 2 / 80, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32 - artilleryHeight * 3 / 64, x + artilleryWidth * 8 / 20 + artilleryWidth * 2 / 80, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32 + artilleryHeight * 3 / 64);
}
case Five: {
g.drawLine(x + artilleryWidth * 10 / 20, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32, x + artilleryWidth * 12 / 20, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32);
g.drawLine(x + artilleryWidth * 11 / 20, y + artilleryHeight * 10 / 16, x + artilleryWidth * 11 / 20, y + artilleryHeight * 10 / 16 + artilleryHeight * 6 / 32);
g.drawLine(x + artilleryWidth * 12 / 20 + artilleryWidth * 2 / 80, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32 - artilleryHeight * 3 / 64, x + artilleryWidth * 12 / 20 - artilleryWidth * 2 / 80, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32 + artilleryHeight * 3 / 64);
g.drawLine(x + artilleryWidth * 11 / 20 + artilleryWidth * 2 / 80, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32 - artilleryHeight * 3 / 64, x + artilleryWidth * 10 / 20 + artilleryWidth * 2 / 80, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32 + artilleryHeight * 3 / 64);
}
case Four: {
g.drawLine(x + artilleryWidth * 5 / 20, y + artilleryHeight * 9 / 16 + artilleryHeight * 4 / 32, x + artilleryWidth * 5 / 20 + artilleryWidth * 3 / 20, y + artilleryHeight * 9 / 16 + artilleryHeight * 4 / 32);
g.drawLine(x + artilleryWidth * 5 / 20 + artilleryWidth * 3 / 40, y + artilleryHeight * 9 / 16, x + artilleryWidth * 5 / 20 + artilleryWidth * 3 / 40, y + artilleryHeight * 9 / 16 + artilleryHeight * 8 / 32);
g.drawLine(x + artilleryWidth * 5 / 20 + artilleryWidth * 3 / 80, y + artilleryHeight * 9 / 16 + artilleryHeight * 2 / 32, x + artilleryWidth * 5 / 20 + artilleryWidth * 9 / 80, y + artilleryHeight * 9 / 16 + artilleryHeight * 6 / 32);
g.drawLine(x + artilleryWidth * 5 / 20 + artilleryWidth * 9 / 80, y + artilleryHeight * 9 / 16 + artilleryHeight * 2 / 32, x + artilleryWidth * 5 / 20 + artilleryWidth * 3 / 80, y + artilleryHeight * 9 / 16 + artilleryHeight * 6 / 32);
g.drawLine(x + artilleryWidth * 12 / 20, y + artilleryHeight * 9 / 16 + artilleryHeight * 4 / 32, x + artilleryWidth * 12 / 20 + artilleryWidth * 3 / 20, y + artilleryHeight * 9 / 16 + artilleryHeight * 4 / 32);
g.drawLine(x + artilleryWidth * 12 / 20 + artilleryWidth * 3 / 40, y + artilleryHeight * 9 / 16, x + artilleryWidth * 12 / 20 + artilleryWidth * 3 / 40, y + artilleryHeight * 9 / 16 + artilleryHeight * 8 / 32);
g.drawLine(x + artilleryWidth * 12 / 20 + artilleryWidth * 3 / 80, y + artilleryHeight * 9 / 16 + artilleryHeight * 2 / 32, x + artilleryWidth * 12 / 20 + artilleryWidth * 9 / 80, y + artilleryHeight * 9 / 16 + artilleryHeight * 6 / 32);
g.drawLine(x + artilleryWidth * 12 / 20 + artilleryWidth * 9 / 80, y + artilleryHeight * 9 / 16 + artilleryHeight * 2 / 32, x + artilleryWidth * 12 / 20 + artilleryWidth * 3 / 80, y + artilleryHeight * 9 / 16 + artilleryHeight * 6 / 32);
}
}
}
public void setColor(Color color) {
this.color = color;
}
}

View File

@ -0,0 +1,53 @@
import java.awt.*;
public class DrawingObjectArtillery implements IDrawingObject {
private DrawingArtillery _artillery;
public DrawingObjectArtillery(DrawingArtillery artillery) {
_artillery = artillery;
}
public DrawingArtillery getArtillery() {
return _artillery;
}
public float getStep() {
if (_artillery != null && _artillery.artillery != null) {
return _artillery.artillery.getStep();
}
return 0;
}
public float[] getCurrentPosition() {
if (_artillery != null) {
return _artillery.getCurrentPosition();
}
return new float[] { 0, 0, 0, 0 };
}
public void moveObject(Direction direction) {
if (_artillery != null) {
_artillery.moveTransport(direction);
}
}
public void setObject(int x, int y, int width, int height) {
_artillery.setPosition(x, y, width, height);
}
public void drawingObject(Graphics2D g) {
_artillery.drawTransport(g);
}
public String getInfo() {
if (_artillery == null) {
return null;
}
return ArtillerySerde.serialize(_artillery);
}
public static IDrawingObject create(String data) {
return new DrawingObjectArtillery(ArtillerySerde.deserialize(data));
}
}

View File

@ -1,10 +1,10 @@
import java.awt.*;
public class DrawingRollers {
public class DrawingRollers implements IDrawingRollers {
private RollersCount rollersCount;
private Color color;
public void Init(int rollersCount, Color bodyColor) {
public DrawingRollers(int rollersCount, Color bodyColor) {
setRollersCount(rollersCount);
color = bodyColor;
}
@ -19,6 +19,10 @@ public class DrawingRollers {
}
}
public int getRollersCount() {
return rollersCount.getValue();
}
public void draw(Graphics2D g, int x, int y, int artilleryWidth, int artilleryHeight) {
g.setColor(color != null ? color : Color.BLACK);
g.fillOval(x + artilleryWidth / 20, y + artilleryHeight * 7 / 15, artilleryWidth * 4 / 20, artilleryHeight * 10 / 32);
@ -36,4 +40,8 @@ public class DrawingRollers {
}
}
}
public void setColor(Color color) {
this.color = color;
}
}

115
DrawingSquaredRollers.java Normal file
View File

@ -0,0 +1,115 @@
import java.awt.*;
public class DrawingSquaredRollers implements IDrawingRollers {
private RollersCount rollersCount;
private Color color;
public DrawingSquaredRollers(int rollersCount, Color bodyColor) {
setRollersCount(rollersCount);
color = bodyColor;
}
public void setRollersCount(int num) {
if (num <= 4) {
rollersCount = RollersCount.Four;
} else if (num >= 6) {
rollersCount = RollersCount.Six;
} else {
rollersCount = RollersCount.Five;
}
}
public int getRollersCount() {
return rollersCount.getValue();
}
public void draw(Graphics2D g, int x, int y, int artilleryWidth, int artilleryHeight) {
g.setColor(color != null ? color : Color.BLACK);
g.fillOval(x + artilleryWidth / 20, y + artilleryHeight * 7 / 15, artilleryWidth * 4 / 20, artilleryHeight * 10 / 32);
g.fillOval(x + artilleryWidth * 15 / 20, y + artilleryHeight * 7 / 15, artilleryWidth * 4 / 20, artilleryHeight * 10 / 32);
switch (rollersCount) {
case Six: {
g.fillOval(x + artilleryWidth * 8 / 20, y + artilleryHeight * 10 / 16, artilleryWidth * 2 / 20, artilleryHeight * 6 / 32);
}
case Five: {
g.fillOval(x + artilleryWidth * 10 / 20, y + artilleryHeight * 10 / 16, artilleryWidth * 2 / 20, artilleryHeight * 6 / 32);
}
case Four: {
g.fillOval(x + artilleryWidth * 5 / 20, y + artilleryHeight * 9 / 16, artilleryWidth * 3 / 20, artilleryHeight * 8 / 32);
g.fillOval(x + artilleryWidth * 12 / 20, y + artilleryHeight * 9 / 16, artilleryWidth * 3 / 20, artilleryHeight * 8 / 32);
}
}
drawOrnament(g, x, y, artilleryWidth, artilleryHeight);
}
private void drawOrnament(Graphics2D g, int x, int y, int artilleryWidth, int artilleryHeight) {
g.setStroke(new BasicStroke(1));
g.setColor(Color.BLACK);
Polygon bigRollerFirstPattern = new Polygon();
bigRollerFirstPattern.addPoint(x + artilleryWidth / 20 + 1, y + artilleryHeight * 7 / 15 + artilleryHeight * 5 / 32);
bigRollerFirstPattern.addPoint(x + artilleryWidth * 3 / 20, y + artilleryHeight * 7 / 15 + 1);
bigRollerFirstPattern.addPoint(x + artilleryWidth * 5 / 20 - 1, y + artilleryHeight * 7 / 15 + artilleryHeight * 5 / 32);
bigRollerFirstPattern.addPoint(x + artilleryWidth * 3 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 10 / 32 - 1);
g.drawPolygon(bigRollerFirstPattern);
bigRollerFirstPattern.translate(artilleryWidth * 14 / 20, 0);
g.drawPolygon(bigRollerFirstPattern);
Polygon bigRollerSecondPattern = new Polygon();
bigRollerSecondPattern.addPoint(x + artilleryWidth * 2 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 5 / 64);
bigRollerSecondPattern.addPoint(x + artilleryWidth * 4 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 5 / 64);
bigRollerSecondPattern.addPoint(x + artilleryWidth * 4 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 15 / 64);
bigRollerSecondPattern.addPoint(x + artilleryWidth * 2 / 20, y + artilleryHeight * 7 / 15 + artilleryHeight * 15 / 64);
g.drawPolygon(bigRollerSecondPattern);
bigRollerSecondPattern.translate(artilleryWidth * 14 / 20, 0);
g.drawPolygon(bigRollerSecondPattern);
Polygon smallRollerFirstPattern = new Polygon();
smallRollerFirstPattern.addPoint(x + artilleryWidth * 8 / 20, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32);
smallRollerFirstPattern.addPoint(x + artilleryWidth * 9 / 20, y + artilleryHeight * 10 / 16);
smallRollerFirstPattern.addPoint(x + artilleryWidth * 10 / 20, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32);
smallRollerFirstPattern.addPoint(x + artilleryWidth * 9 / 20, y + artilleryHeight * 10 / 16 + artilleryHeight * 6 / 32);
Polygon smallRollerSecondPattern = new Polygon();
smallRollerSecondPattern.addPoint(x + artilleryWidth * 8 / 20 + artilleryWidth * 2 / 80, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32 - artilleryHeight * 3 / 64);
smallRollerSecondPattern.addPoint(x + artilleryWidth * 9 / 20 + artilleryWidth * 2 / 80, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32 - artilleryHeight * 3 / 64);
smallRollerSecondPattern.addPoint(x + artilleryWidth * 10 / 20 - artilleryWidth * 2 / 80, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32 + artilleryHeight * 3 / 64);
smallRollerSecondPattern.addPoint(x + artilleryWidth * 8 / 20 + artilleryWidth * 2 / 80, y + artilleryHeight * 10 / 16 + artilleryHeight * 3 / 32 + artilleryHeight * 3 / 64);
switch(rollersCount) {
case Six: {
g.drawPolygon(smallRollerFirstPattern);
g.drawPolygon(smallRollerSecondPattern);
}
case Five: {
smallRollerFirstPattern.translate(artilleryWidth * 2 / 20, 0);
smallRollerSecondPattern.translate(artilleryWidth * 2 / 20, 0);
g.drawPolygon(smallRollerFirstPattern);
g.drawPolygon(smallRollerSecondPattern);
}
case Four: {
Polygon mediumRollerFirstPattern = new Polygon();
mediumRollerFirstPattern.addPoint(x + artilleryWidth * 5 / 20, y + artilleryHeight * 9 / 16 + artilleryHeight * 4 / 32);
mediumRollerFirstPattern.addPoint(x + artilleryWidth * 5 / 20 + artilleryWidth * 3 / 40, y + artilleryHeight * 9 / 16);
mediumRollerFirstPattern.addPoint(x + artilleryWidth * 5 / 20 + artilleryWidth * 3 / 20, y + artilleryHeight * 9 / 16 + artilleryHeight * 4 / 32);
mediumRollerFirstPattern.addPoint(x + artilleryWidth * 5 / 20 + artilleryWidth * 3 / 40, y + artilleryHeight * 9 / 16 + artilleryHeight * 8 / 32);
g.drawPolygon(mediumRollerFirstPattern);
mediumRollerFirstPattern.translate(artilleryWidth * 7 / 20, 0);
g.drawPolygon(mediumRollerFirstPattern);
Polygon mediumRollerSecondPattern = new Polygon();
mediumRollerSecondPattern.addPoint(x + artilleryWidth * 5 / 20 + artilleryWidth * 3 / 80, y + artilleryHeight * 9 / 16 + artilleryHeight * 2 / 32);
mediumRollerSecondPattern.addPoint(x + artilleryWidth * 5 / 20 + artilleryWidth * 9 / 80, y + artilleryHeight * 9 / 16 + artilleryHeight * 2 / 32);
mediumRollerSecondPattern.addPoint(x + artilleryWidth * 5 / 20 + artilleryWidth * 9 / 80, y + artilleryHeight * 9 / 16 + artilleryHeight * 6 / 32);
mediumRollerSecondPattern.addPoint(x + artilleryWidth * 5 / 20 + artilleryWidth * 3 / 80, y + artilleryHeight * 9 / 16 + artilleryHeight * 6 / 32);
g.drawPolygon(mediumRollerSecondPattern);
mediumRollerSecondPattern.translate(artilleryWidth * 7 / 20, 0);
g.drawPolygon(mediumRollerSecondPattern);
}
}
}
public void setColor(Color color) {
this.color = color;
}
}

View File

@ -0,0 +1,26 @@
import java.awt.*;
public class EntityAdvancedArtillery extends EntityArtillery {
private Color dopColor;
private boolean weapon;
private boolean salvoBattery;
public EntityAdvancedArtillery(int speed, float weight, Color bodyColor, Color dopColor, boolean weapon, boolean salvoBattery) {
super(speed, weight, bodyColor);
this.dopColor = dopColor;
this.weapon = weapon;
this.salvoBattery = salvoBattery;
}
public Color getDopColor() {
return dopColor;
}
public boolean getWeapon() {
return weapon;
}
public boolean getSalvoBattery() {
return salvoBattery;
}
}

View File

@ -6,7 +6,7 @@ public class EntityArtillery {
private float weight;
private Color bodyColor;
public void Init(int speed, float weight, Color bodyColor) {
public EntityArtillery(int speed, float weight, Color bodyColor) {
Random rnd = new Random();
this.speed = speed <= 0 ? rnd.nextInt(50, 150) : speed;
this.weight = weight <= 0 ? rnd.nextInt(40, 70) : weight;

43
EntityWithRollers.java Normal file
View File

@ -0,0 +1,43 @@
import java.util.Random;
public class EntityWithRollers<T extends EntityArtillery, U extends IDrawingRollers> {
static Random rnd = new Random();
private final Object[] entities;
public int entitiesCount = 0;
private final Object[] rollers;
public int rollersCount = 0;
public EntityWithRollers(int count) {
entities = new Object[count];
rollers = new Object[count];
}
public boolean add(EntityArtillery entity) {
if (entitiesCount >= entities.length) {
return false;
}
entities[entitiesCount++] = entity;
return true;
}
public boolean add(IDrawingRollers roller) {
if (rollersCount >= rollers.length) {
return false;
}
rollers[rollersCount++] = roller;
return true;
}
public IDrawingObject constructArtillery() {
if (entitiesCount == 0 || rollersCount == 0) {
return null;
}
EntityArtillery entity = (EntityArtillery) entities[rnd.nextInt(0, entitiesCount)];
IDrawingRollers roller = (IDrawingRollers) rollers[rnd.nextInt(0, rollersCount)];
if (entity instanceof EntityAdvancedArtillery advancedEntity) {
return new DrawingObjectArtillery(new DrawingAdvancedArtillery(advancedEntity, roller));
}
return new DrawingObjectArtillery(new DrawingArtillery(entity, roller));
}
}

16
EventListener.java Normal file
View File

@ -0,0 +1,16 @@
import java.util.ArrayList;
import java.util.function.Consumer;
public class EventListener<T> {
private final ArrayList<Consumer<T>> listeners = new ArrayList<>();
public void addListener(Consumer<T> listener) {
listeners.add(listener);
}
public void emit(T artillery) {
for (var listener : listeners) {
listener.accept(artillery);
}
}
}

19
FileFormatException.java Normal file
View File

@ -0,0 +1,19 @@
import java.io.IOException;
public class FileFormatException extends IOException {
public FileFormatException() {
}
public FileFormatException(String message) {
super(message);
}
public FileFormatException(String message, Throwable cause) {
super(message, cause);
}
public FileFormatException(Throwable cause) {
super(cause);
}
}

49
ForestMap.java Normal file
View File

@ -0,0 +1,49 @@
import java.awt.*;
import java.util.Arrays;
public class ForestMap extends AbstractMap {
private final Color barrierColor = Color.green;
private final Color roadColor = new Color(165, 42, 42, 255);
@Override
protected void drawBarrierPart(Graphics2D g, int i, int j)
{
g.setColor(barrierColor);
g.fillRect(j * (int) _size_x, i * (int) _size_y, (int) _size_x, (int) _size_y);
}
@Override
protected void drawRoadPart(Graphics2D g, int i, int j)
{
g.setColor(roadColor);
g.fillRect(j * (int) _size_x, i * (int) _size_y, (int) _size_x, (int) _size_y);
}
@Override
protected void generateMap() {
_map = new int[50][50];
_size_x = (float)_width / _map[0].length;
_size_y = (float)_height / _map.length;
int counter = 0;
for (int[] row : _map) {
Arrays.fill(row, _freeRoad);
}
while (counter < 20)
{
int x = _random.nextInt(2, 49);
int y = _random.nextInt(3, 50);
var points = new int[] { _map[y][x], _map[y - 1][x], _map[y - 2][x], _map[y - 2][x - 1], _map[y - 2][x + 1], _map[y - 3][x] };
var forComparison = new int[] { _freeRoad, _freeRoad, _freeRoad, _freeRoad, _freeRoad, _freeRoad };
if (Arrays.equals(points, forComparison))
{
_map[y][x] = _barrier;
_map[y - 1][x] = _barrier;
_map[y - 2][x] = _barrier;
_map[y - 2][x - 1] = _barrier;
_map[y - 2][x + 1] = _barrier;
_map[y - 3][x] = _barrier;
counter++;
}
}
}
}

View File

@ -53,7 +53,7 @@
</component>
</children>
</grid>
<grid id="fa947" binding="pictureBox" layout-manager="GridLayoutManager" row-count="3" column-count="6" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<grid id="fa947" binding="pictureBox" layout-manager="GridLayoutManager" row-count="3" column-count="8" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
@ -61,11 +61,6 @@
<properties/>
<border type="none"/>
<children>
<hspacer id="f89d0">
<constraints>
<grid row="1" column="2" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
</hspacer>
<vspacer id="402e3">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
@ -73,12 +68,12 @@
</vspacer>
<vspacer id="bbd8c">
<constraints>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
<grid row="0" column="3" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<component id="271ef" class="javax.swing.JButton" binding="buttonUp">
<constraints>
<grid row="1" column="4" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="1" indent="0" use-parent-layout="false">
<grid row="1" column="6" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<preferred-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
@ -93,7 +88,7 @@
</component>
<component id="4b967" class="javax.swing.JButton" binding="buttonDown">
<constraints>
<grid row="2" column="4" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<grid row="2" column="6" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<preferred-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
@ -107,7 +102,7 @@
</component>
<component id="2e663" class="javax.swing.JButton" binding="buttonLeft">
<constraints>
<grid row="2" column="3" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<grid row="2" column="5" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<preferred-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
@ -122,7 +117,7 @@
</component>
<component id="c2d76" class="javax.swing.JButton" binding="buttonRight">
<constraints>
<grid row="2" column="5" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<grid row="2" column="7" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<preferred-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
@ -137,7 +132,7 @@
</component>
<component id="7bc68" class="javax.swing.JButton" binding="createButton">
<constraints>
<grid row="2" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="2" fill="1" indent="0" use-parent-layout="false"/>
<grid row="2" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<alignmentX value="0.0"/>
@ -145,6 +140,27 @@
<text value="Создать"/>
</properties>
</component>
<component id="27408" class="javax.swing.JButton" binding="createAdvancedButton">
<constraints>
<grid row="2" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Модификация"/>
</properties>
</component>
<component id="d034f" class="javax.swing.JButton" binding="buttonSelect">
<constraints>
<grid row="2" column="4" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Выбрать"/>
</properties>
</component>
<hspacer id="f89d0">
<constraints>
<grid row="1" column="3" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
</hspacer>
</children>
</grid>
</children>

View File

@ -1,10 +1,9 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.*;
import java.util.Random;
public class FormArtillery extends JFrame {
public class FormArtillery extends JDialog {
private JPanel artilleryPane;
private JLabel speedLabel;
private JLabel weightLabel;
@ -15,25 +14,23 @@ public class FormArtillery extends JFrame {
private JButton buttonDown;
private JButton buttonLeft;
private JButton buttonRight;
private JButton createAdvancedButton;
public JButton buttonSelect;
private DrawingArtillery _artillery;
private DrawingArtillery selectedArtillery;
public FormArtillery() {
this.setTitle("Artillery");
this.setContentPane(artilleryPane);
createButton.addActionListener(e -> {
Random rnd = new Random();
_artillery = new DrawingArtillery();
_artillery.Init(
rnd.nextInt(100, 300),
rnd.nextInt(1000, 2000),
new Color(
rnd.nextInt(0, 256),
rnd.nextInt(0, 256),
rnd.nextInt(0, 256)),
rnd.nextInt(4, 7)
);
_artillery.SetPosition(10 + rnd.nextInt(90), 10 + rnd.nextInt(90), pictureBox.getWidth(), pictureBox.getHeight());
Color color = JColorChooser.showDialog(this, "Цвет", new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256)));
if (color == null) {
color = new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256));
}
_artillery = new DrawingArtillery(rnd.nextInt(100, 300), rnd.nextInt(1000, 2000), color, rnd.nextInt(4, 7));
_artillery.setPosition(10 + rnd.nextInt(90), 10 + rnd.nextInt(90), pictureBox.getWidth(), pictureBox.getHeight());
speedLabel.setText(String.format("Скорость: %s", _artillery.getArtillery().getSpeed()));
weightLabel.setText(String.format("Вес: %s", _artillery.getArtillery().getWeight()));
colorLabel.setText(String.format("Цвет: %x", _artillery.getArtillery().getBodyColor().getRGB()));
@ -62,12 +59,51 @@ public class FormArtillery extends JFrame {
if (_artillery != null) _artillery.moveTransport(Direction.Down);
repaint();
});
createAdvancedButton.addActionListener(e -> {
Random rnd = new Random();
Color color = JColorChooser.showDialog(this, "Основной цвет", Color.white);
if (color == null) {
color = new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256));
}
Color dopColor = JColorChooser.showDialog(this, "Дополнительный цвет", Color.white);
if (dopColor == null) {
dopColor = new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256));
}
_artillery = new DrawingAdvancedArtillery(
rnd.nextInt(100, 300),
rnd.nextInt(1000, 2000),
color,
rnd.nextInt(4, 7),
dopColor,
rnd.nextBoolean(),
rnd.nextBoolean()
);
_artillery.setPosition(10 + rnd.nextInt(90), 10 + rnd.nextInt(90), pictureBox.getWidth(), pictureBox.getHeight());
speedLabel.setText(String.format("Скорость: %s", _artillery.getArtillery().getSpeed()));
weightLabel.setText(String.format("Вес: %s", _artillery.getArtillery().getWeight()));
colorLabel.setText(String.format("Цвет: %x", _artillery.getArtillery().getBodyColor().getRGB()));
repaint();
});
buttonSelect.addActionListener(e -> {
selectedArtillery = _artillery;
dispose();
});
}
public FormArtillery(DrawingArtillery artillery) {
this();
_artillery = artillery;
repaint();
}
public DrawingArtillery getSelectedArtillery() {
return selectedArtillery;
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) artilleryPane.getGraphics();
Graphics2D g2d = (Graphics2D) pictureBox.getGraphics();
if (_artillery != null) {
_artillery.drawTransport(g2d);
}

341
FormArtilleryConfig.form Normal file
View File

@ -0,0 +1,341 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="FormArtilleryConfig">
<grid id="27dc6" binding="contentPanel" layout-manager="GridLayoutManager" row-count="3" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="878" height="437"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="fdfc8" binding="toolsPanel" layout-manager="GridLayoutManager" row-count="7" column-count="4" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="3" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none" title="Параметры"/>
<children>
<component id="6962a" class="javax.swing.JLabel" binding="speedLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="27572"/>
<text value="Скорость:"/>
</properties>
</component>
<component id="27572" class="javax.swing.JSpinner" binding="speedSpinner">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
</component>
<component id="871d8" class="javax.swing.JLabel" binding="weightLabel">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="8e1be"/>
<text value="Вес:"/>
</properties>
</component>
<component id="8e1be" class="javax.swing.JSpinner" binding="weightSpinner">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
</component>
<component id="39e94" class="javax.swing.JCheckBox" binding="checkBoxWeapon">
<constraints>
<grid row="2" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Признак наличия орудия"/>
</properties>
</component>
<component id="9d114" class="javax.swing.JCheckBox" binding="checkBoxSalvoBattery">
<constraints>
<grid row="3" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Признак наличия залповой батареи"/>
</properties>
</component>
<grid id="2044c" binding="colorsPanel" layout-manager="GridLayoutManager" row-count="2" column-count="4" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="2" row-span="5" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none" title="Цвета"/>
<children>
<grid id="784a6" binding="redPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-65536"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="abece" binding="greenPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-16711936"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="b2eb9" binding="bluePanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-16776961"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="482a4" binding="yellowPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="3" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-723926"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="1692f" binding="whitePanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-1"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="aaf16" binding="grayPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-10527145"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="d1a3c" binding="blackPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="2" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-16777216"/>
</properties>
<border type="none"/>
<children/>
</grid>
<grid id="e81e" binding="purplePanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="3" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="60" height="60"/>
<maximum-size width="60" height="60"/>
</grid>
</constraints>
<properties>
<background color="-5173091"/>
</properties>
<border type="none"/>
<children/>
</grid>
</children>
</grid>
<grid id="f974a" binding="rollersPanel" layout-manager="GridLayoutManager" row-count="3" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="6" column="0" row-span="1" col-span="4" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none" title="Катки"/>
<children>
<component id="a92b0" class="javax.swing.JLabel" binding="rollersLabel">
<constraints>
<grid row="0" column="0" row-span="3" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="be4e0"/>
<text value="Количество катков:"/>
</properties>
</component>
<component id="be4e0" class="javax.swing.JSpinner" binding="rollersSpinner">
<constraints>
<grid row="0" column="1" row-span="3" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<maximum-size width="120" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="9f9ab" class="javax.swing.JLabel" binding="baseRollersLabel">
<constraints>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="100" height="38"/>
<maximum-size width="100" height="38"/>
</grid>
</constraints>
<properties>
<font size="16"/>
<text value="Простые"/>
</properties>
</component>
<component id="ea1ae" class="javax.swing.JLabel" binding="crossRollersLabel">
<constraints>
<grid row="1" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="120" height="38"/>
<maximum-size width="120" height="38"/>
</grid>
</constraints>
<properties>
<font size="16"/>
<text value="С крестиками"/>
</properties>
</component>
<component id="15683" class="javax.swing.JLabel" binding="squaredRollersLabel">
<constraints>
<grid row="2" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="120" height="38"/>
<maximum-size width="120" height="38"/>
</grid>
</constraints>
<properties>
<font size="16"/>
<text value="С квадратами"/>
</properties>
</component>
</children>
</grid>
<component id="9f748" class="javax.swing.JLabel" binding="baseLabel">
<constraints>
<grid row="5" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="100" height="38"/>
<maximum-size width="100" height="38"/>
</grid>
</constraints>
<properties>
<background color="-4720538"/>
<font size="16"/>
<text value="Простой"/>
</properties>
</component>
<component id="7569d" class="javax.swing.JLabel" binding="advancedLabel">
<constraints>
<grid row="5" column="3" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="100" height="38"/>
<maximum-size width="120" height="38"/>
</grid>
</constraints>
<properties>
<font size="16"/>
<text value="Продвинутый"/>
</properties>
</component>
</children>
</grid>
<grid id="1a87d" binding="workspacePanel" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="1" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none" title="Предпоказ"/>
<children>
<component id="18903" class="javax.swing.JLabel" binding="colorLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="100" height="38"/>
<maximum-size width="100" height="38"/>
</grid>
</constraints>
<properties>
<font size="16"/>
<text value="Цвет"/>
</properties>
</component>
<component id="fc724" class="javax.swing.JLabel" binding="additionalColorLabel">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="0" indent="0" use-parent-layout="false">
<minimum-size width="100" height="38"/>
<maximum-size width="100" height="38"/>
</grid>
</constraints>
<properties>
<font size="16"/>
<text value="Доп. цвет"/>
</properties>
</component>
<grid id="47b0f" binding="pictureBox" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="0" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false">
<minimum-size width="200" height="200"/>
<maximum-size width="200" height="200"/>
</grid>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
</children>
</grid>
<component id="df1e6" class="javax.swing.JButton" binding="buttonAdd">
<constraints>
<grid row="1" column="1" row-span="2" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Добавить"/>
</properties>
</component>
<component id="22a26" class="javax.swing.JButton" binding="buttonCancel">
<constraints>
<grid row="1" column="2" row-span="2" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Отмена"/>
</properties>
</component>
</children>
</grid>
</form>

155
FormArtilleryConfig.java Normal file
View File

@ -0,0 +1,155 @@
import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.util.function.Consumer;
public class FormArtilleryConfig extends JFrame {
private final EventListener<DrawingArtillery> eventHandler = new EventListener<>();
private DrawingArtillery artillery;
private JPanel contentPanel;
private JPanel toolsPanel;
private JPanel workspacePanel;
private JButton buttonAdd;
private JButton buttonCancel;
private JLabel colorLabel;
private JLabel additionalColorLabel;
private JPanel pictureBox;
private JLabel speedLabel;
private JSpinner speedSpinner;
private JLabel weightLabel;
private JSpinner weightSpinner;
private JCheckBox checkBoxWeapon;
private JCheckBox checkBoxSalvoBattery;
private JPanel colorsPanel;
private JPanel redPanel;
private JPanel greenPanel;
private JPanel bluePanel;
private JPanel yellowPanel;
private JPanel whitePanel;
private JPanel grayPanel;
private JPanel blackPanel;
private JPanel purplePanel;
private JPanel rollersPanel;
private JLabel rollersLabel;
private JSpinner rollersSpinner;
private JLabel baseLabel;
private JLabel advancedLabel;
private JLabel baseRollersLabel;
private JLabel crossRollersLabel;
private JLabel squaredRollersLabel;
public FormArtilleryConfig() {
this.setTitle("Создание объекта");
this.setSize(840, 480);
this.setContentPane(contentPanel);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// Создание границ
colorLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
additionalColorLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
pictureBox.setBorder(BorderFactory.createDashedBorder(Color.BLACK));
baseLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
advancedLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
baseRollersLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
crossRollersLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
squaredRollersLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
// Задание ограничений
rollersSpinner.setModel(new SpinnerNumberModel(4, 4, 6, 1));
speedSpinner.setModel(new SpinnerNumberModel(100, 100, 1000, 1));
weightSpinner.setModel(new SpinnerNumberModel(100, 100, 1000, 1));
// Создание обработчиков
var dragAdapter = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
super.mouseReleased(e);
setCursor(new Cursor(Cursor.HAND_CURSOR));
}
@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
dispatchDrop((JComponent) e.getSource());
}
};
// Задание обработчиков
redPanel.addMouseListener(dragAdapter);
greenPanel.addMouseListener(dragAdapter);
bluePanel.addMouseListener(dragAdapter);
yellowPanel.addMouseListener(dragAdapter);
whitePanel.addMouseListener(dragAdapter);
grayPanel.addMouseListener(dragAdapter);
blackPanel.addMouseListener(dragAdapter);
purplePanel.addMouseListener(dragAdapter);
baseLabel.addMouseListener(dragAdapter);
advancedLabel.addMouseListener(dragAdapter);
baseRollersLabel.addMouseListener(dragAdapter);
crossRollersLabel.addMouseListener(dragAdapter);
squaredRollersLabel.addMouseListener(dragAdapter);
buttonAdd.addActionListener(e -> {
eventHandler.emit(artillery);
dispose();
});
buttonCancel.addActionListener(e -> dispose());
}
public void addListener(Consumer<DrawingArtillery> listener) {
eventHandler.addListener(listener);
}
public void dispatchDrop(JComponent droppedComponent) {
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
if (droppedComponent == null) {
return;
}
if (droppedComponent instanceof JPanel panel) {
if (colorLabel.getMousePosition() != null) {
artillery.setColor(panel.getBackground());
artillery.getRollers().setColor(panel.getBackground());
}
if (additionalColorLabel.getMousePosition() != null && artillery instanceof DrawingAdvancedArtillery advanced) {
advanced.setDopColor(panel.getBackground());
}
}
if (droppedComponent instanceof JLabel label && pictureBox.getMousePosition() != null) {
int speed = (Integer) speedSpinner.getValue();
int weight = (Integer) weightSpinner.getValue();
int rollersCount = (Integer) rollersSpinner.getValue();
boolean weapon = checkBoxWeapon.isSelected();
boolean salvoBattery = checkBoxSalvoBattery.isSelected();
if (label == baseLabel) {
artillery = new DrawingArtillery(speed, weight, Color.WHITE, rollersCount);
} else if (label == advancedLabel) {
artillery = new DrawingAdvancedArtillery(speed, weight, Color.WHITE, rollersCount, Color.WHITE, weapon, salvoBattery);
} else if (artillery != null && label == baseRollersLabel) {
artillery.setRollers(new DrawingRollers(rollersCount, artillery.getArtillery().getBodyColor()));
} else if (artillery != null && label == crossRollersLabel) {
artillery.setRollers(new DrawingCrossRollers(rollersCount, artillery.getArtillery().getBodyColor()));
} else if (artillery != null && label == squaredRollersLabel) {
artillery.setRollers(new DrawingSquaredRollers(rollersCount, artillery.getArtillery().getBodyColor()));
}
}
repaint();
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (artillery != null) {
g = pictureBox.getGraphics();
artillery.setPosition(60, 75, pictureBox.getWidth(), pictureBox.getHeight());
artillery.drawTransport((Graphics2D) g);
}
}
}

30
FormGallery.form Normal file
View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="FormGallery">
<grid id="27dc6" binding="contentPane" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="323" height="234"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="632d3" binding="pictureBox" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
<component id="7e5f8" class="javax.swing.JButton" binding="buttonRefresh">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Обновить"/>
</properties>
</component>
</children>
</grid>
</form>

66
FormGallery.java Normal file
View File

@ -0,0 +1,66 @@
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class FormGallery extends JFrame {
private static final Random rnd = new Random();
private JPanel contentPane;
private JButton buttonRefresh;
private JPanel pictureBox;
private IDrawingObject first;
private IDrawingObject second;
private IDrawingObject third;
private final EntityWithRollers<EntityArtillery, IDrawingRollers> storage;
public FormGallery() {
setTitle("Галлерея");
setContentPane(contentPane);
storage = new EntityWithRollers<>(20);
for(int i = 0; i < 20; i++) {
if (rnd.nextBoolean()) {
storage.add(new EntityAdvancedArtillery(
rnd.nextInt(100, 300),
rnd.nextInt(1000, 2000),
new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256)),
new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256)),
rnd.nextBoolean(),
rnd.nextBoolean()
));
} else {
storage.add(new EntityArtillery(
rnd.nextInt(100, 300),
rnd.nextInt(1000, 2000),
new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256))
));
}
storage.add(RollersType.random(rnd.nextInt(4, 7), new Color(rnd.nextInt(0, 256), rnd.nextInt(0, 256), rnd.nextInt(0, 256))));
}
buttonRefresh.addActionListener(e -> {
first = storage.constructArtillery();
second = storage.constructArtillery();
third = storage.constructArtillery();
first.setObject(0, 10, pictureBox.getWidth(), pictureBox.getHeight());
second.setObject(90, 10, pictureBox.getWidth(), pictureBox.getHeight());
third.setObject(190, 10, pictureBox.getWidth(), pictureBox.getHeight());
repaint();
});
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2g = (Graphics2D) pictureBox.getGraphics();
if (first != null && second != null && third != null) {
first.drawingObject(g2g);
second.drawingObject(g2g);
third.drawingObject(g2g);
}
}
}

View File

@ -0,0 +1,219 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="FormMapWithSetArtilleries">
<grid id="27dc6" binding="paneArtilleries" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="649" height="532"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<grid id="fcfe1" binding="pictureBox" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="7" hsize-policy="7" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
<grid id="f232" binding="toolsGroup" layout-manager="GridLayoutManager" row-count="10" column-count="4" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="0" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="d7a62" class="javax.swing.JLabel" binding="toolsLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Инструменты"/>
</properties>
</component>
<hspacer id="1c91f">
<constraints>
<grid row="0" column="1" row-span="1" col-span="3" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
</hspacer>
<component id="52049" class="javax.swing.JButton" binding="buttonAddArtillery">
<constraints>
<grid row="2" column="0" row-span="1" col-span="4" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Добавить артиллерию"/>
</properties>
</component>
<component id="2f9ed" class="javax.swing.JFormattedTextField" binding="textBoxPosition">
<constraints>
<grid row="3" column="0" row-span="1" col-span="4" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="1dbb5" class="javax.swing.JButton" binding="buttonRemoveArtillery">
<constraints>
<grid row="4" column="0" row-span="1" col-span="4" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<actionCommand value=""/>
<text value="Удалить артиллерию"/>
</properties>
</component>
<component id="4e6ca" class="javax.swing.JButton" binding="buttonShowStorage">
<constraints>
<grid row="5" column="0" row-span="1" col-span="4" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Посмотреть хранилище"/>
</properties>
</component>
<component id="51371" class="javax.swing.JButton" binding="buttonShowOnMap">
<constraints>
<grid row="6" column="0" row-span="1" col-span="4" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Посмотреть карту"/>
</properties>
</component>
<component id="fb3e4" class="javax.swing.JButton" binding="buttonUp">
<constraints>
<grid row="8" column="1" row-span="1" col-span="3" vsize-policy="0" hsize-policy="0" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<preferred-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<borderPainted value="true"/>
<contentAreaFilled value="false"/>
<icon value="Resources/ArrowUp.png"/>
<text value=""/>
</properties>
</component>
<component id="328f6" class="javax.swing.JButton" binding="buttonDown">
<constraints>
<grid row="9" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<preferred-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<contentAreaFilled value="false"/>
<icon value="Resources/ArrowDown.png"/>
<text value=""/>
</properties>
</component>
<component id="4f2dc" class="javax.swing.JButton" binding="buttonLeft">
<constraints>
<grid row="9" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<preferred-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<contentAreaFilled value="false"/>
<icon value="Resources/ArrowLeft.png"/>
<label value=""/>
<text value=""/>
</properties>
</component>
<component id="bac06" class="javax.swing.JButton" binding="buttonRight">
<constraints>
<grid row="9" column="3" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false">
<minimum-size width="30" height="30"/>
<preferred-size width="30" height="30"/>
<maximum-size width="30" height="30"/>
</grid>
</constraints>
<properties>
<contentAreaFilled value="false"/>
<icon value="Resources/ArrowRight.png"/>
<label value=""/>
<text value=""/>
</properties>
</component>
<grid id="7448e" binding="mapsGroup" layout-manager="GridLayoutManager" row-count="6" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="1" column="0" row-span="1" col-span="4" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="3bd55" class="javax.swing.JLabel" binding="mapsLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Карты"/>
</properties>
</component>
<hspacer id="b4c1d">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
</hspacer>
<component id="6a0f5" class="javax.swing.JComboBox" binding="comboBoxMapSelector">
<constraints>
<grid row="2" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="2" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<model>
<item value="Простая карта"/>
<item value="Лесная карта"/>
</model>
</properties>
</component>
<component id="a344e" class="javax.swing.JTextField" binding="textFieldMapName">
<constraints>
<grid row="1" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
<properties/>
</component>
<component id="b8791" class="javax.swing.JButton" binding="buttonAddMap">
<constraints>
<grid row="3" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Добавить карту"/>
</properties>
</component>
<component id="89547" class="javax.swing.JList" binding="listBoxMaps">
<constraints>
<grid row="4" column="0" row-span="1" col-span="2" vsize-policy="6" hsize-policy="2" anchor="0" fill="3" indent="0" use-parent-layout="false">
<preferred-size width="150" height="50"/>
</grid>
</constraints>
<properties/>
</component>
<component id="643d3" class="javax.swing.JButton" binding="buttonDeleteMap">
<constraints>
<grid row="5" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Удалить карту"/>
</properties>
</component>
</children>
</grid>
<component id="490e6" class="javax.swing.JButton" binding="buttonShowDeleted">
<constraints>
<grid row="7" column="0" row-span="1" col-span="4" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Посмотреть удалённую артиллерию"/>
</properties>
</component>
</children>
</grid>
</children>
</grid>
</form>

View File

@ -0,0 +1,328 @@
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;
import java.awt.*;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Optional;
import java.util.Stack;
public class FormMapWithSetArtilleries extends JFrame {
private JMenuBar menuBar;
private JPanel pictureBox;
private JPanel toolsGroup;
private JLabel toolsLabel;
private JComboBox<String> comboBoxMapSelector;
private JButton buttonAddArtillery;
private JPanel paneArtilleries;
private JFormattedTextField textBoxPosition;
private JButton buttonRemoveArtillery;
private JButton buttonShowStorage;
private JButton buttonUp;
private JButton buttonDown;
private JButton buttonLeft;
private JButton buttonRight;
private JButton buttonShowOnMap;
private JLabel mapsLabel;
private JTextField textFieldMapName;
private JButton buttonAddMap;
private JList<String> listBoxMaps;
private JPanel mapsGroup;
private JButton buttonDeleteMap;
private JButton buttonShowDeleted;
private Image bufferedImage;
private final HashMap<String, AbstractMap> _mapsDict = new HashMap<>() {{
put("Простая карта", new SimpleMap());
put("Лесная карта", new ForestMap());
}};
private final MapsCollection _mapsCollection;
private final Stack<IDrawingObject> deletedObjects = new Stack<>();
private Logger logger;
public FormMapWithSetArtilleries(Logger logger) {
this();
this.logger = logger;
}
public FormMapWithSetArtilleries() {
this.setTitle("Artillery");
this.setContentPane(paneArtilleries);
this.setSize(640, 530);
this.setVisible(true);
try {
textBoxPosition.setFormatterFactory(new DefaultFormatterFactory(new MaskFormatter("##")));
} catch (ParseException e) {
e.printStackTrace();
}
_mapsCollection = new MapsCollection(pictureBox.getWidth(), pictureBox.getHeight());
menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("Файл");
menuBar.add(fileMenu);
JMenuItem saveMenuItem = new JMenuItem("Сохранить");
saveMenuItem.addActionListener(e -> {
JFileChooser dialog = new JFileChooser();
dialog.setFileFilter(new FileNameExtensionFilter("TXT file", "txt"));
dialog.showSaveDialog(this);
try {
_mapsCollection.saveData(dialog.getSelectedFile().getAbsolutePath());
logger.info("Сохранение в файл \"" + dialog.getSelectedFile().getAbsolutePath() + "\"");
JOptionPane.showMessageDialog(this, "Сохранение прошло успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception ex) {
logger.error("Ошибка сохранения в файл: " + ex.getMessage());
JOptionPane.showMessageDialog(this, "Не сохранилось: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
}
});
fileMenu.add(saveMenuItem);
JMenuItem loadMenuItem = new JMenuItem("Загрузить");
loadMenuItem.addActionListener(e -> {
JFileChooser dialog = new JFileChooser();
dialog.setFileFilter(new FileNameExtensionFilter("TXT file", "txt"));
dialog.showOpenDialog(this);
try {
_mapsCollection.loadData(dialog.getSelectedFile().getAbsolutePath());
reloadMaps();
logger.info("Загрузка из файла \"" + dialog.getSelectedFile().getAbsolutePath() + "\"");
JOptionPane.showMessageDialog(this, "Загрузка прошла успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception ex) {
logger.error("Ошибка загрузки из файла: " + ex.getMessage());
JOptionPane.showMessageDialog(this, "Не загрузилось: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
}
});
fileMenu.add(loadMenuItem);
JMenuItem saveMapMenuItem = new JMenuItem("Сохранить карту");
saveMapMenuItem.addActionListener(e -> {
JFileChooser dialog = new JFileChooser();
dialog.setFileFilter(new FileNameExtensionFilter("TXT file", "txt"));
dialog.showSaveDialog(this);
try {
_mapsCollection.saveMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse(""), dialog.getSelectedFile().getAbsolutePath());
logger.info("Сохранение карты в файл \"" + dialog.getSelectedFile().getAbsolutePath() + "\"");
JOptionPane.showMessageDialog(this, "Сохранение прошло успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception ex) {
logger.error("Ошибка сохранения карты в файл: " + ex.getMessage());
JOptionPane.showMessageDialog(this, "Не сохранилось: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
}
});
fileMenu.add(saveMapMenuItem);
JMenuItem loadMapMenuItem = new JMenuItem("Загрузить карту");
loadMapMenuItem.addActionListener(e -> {
JFileChooser dialog = new JFileChooser();
dialog.setFileFilter(new FileNameExtensionFilter("TXT file", "txt"));
dialog.showOpenDialog(this);
try {
_mapsCollection.loadMap(dialog.getSelectedFile().getAbsolutePath());
reloadMaps();
logger.info("Загрузка карты из файла \"" + dialog.getSelectedFile().getAbsolutePath() + "\"");
JOptionPane.showMessageDialog(this, "Загрузка прошла успешно", "Успех", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception ex) {
logger.error("Ошибка загрузки карты из файла: " + ex.getMessage());
JOptionPane.showMessageDialog(this, "Не загрузилось: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
}
});
fileMenu.add(loadMapMenuItem);
setJMenuBar(menuBar);
comboBoxMapSelector.removeAllItems();
for (var key : _mapsDict.keySet()) {
comboBoxMapSelector.addItem(key);
}
buttonAddMap.addActionListener(e -> {
if (comboBoxMapSelector.getSelectedIndex() == -1 || textFieldMapName.getText() == null || textFieldMapName.getText().isEmpty()) {
logger.warn("Не удалось добавить карту: Не все данные заполнены");
JOptionPane.showMessageDialog(this, "Не все данные заполнены", "Ошибка", JOptionPane.ERROR_MESSAGE);
return;
}
if (!_mapsDict.containsKey((String)comboBoxMapSelector.getSelectedItem())) {
logger.warn("Не удалось добавить карту: Нет такой карты");
JOptionPane.showMessageDialog(this, "Нет такой карты", "Ошибка", JOptionPane.ERROR_MESSAGE);
return;
}
_mapsCollection.addMap(textFieldMapName.getText(), _mapsDict.get((String)comboBoxMapSelector.getSelectedItem()));
reloadMaps();
logger.info("Добавлена карта \"" + textFieldMapName.getText() + "\" типа " + comboBoxMapSelector.getSelectedItem());
});
buttonDeleteMap.addActionListener(e -> {
if (listBoxMaps.getSelectedIndex() == -1) {
return;
}
if (JOptionPane.showConfirmDialog(this, "Удалить карту " + listBoxMaps.getSelectedValue() + "?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
_mapsCollection.deleteMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse(""));
logger.info("Удалена карта \"" + listBoxMaps.getSelectedValue() + "\"");
reloadMaps();
}
});
listBoxMaps.addListSelectionListener(e -> {
if (listBoxMaps.getSelectedValue() != null) {
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showSet();
repaint();
logger.info("Переход на карту \"" + listBoxMaps.getSelectedValue() + "\"");
}
});
buttonAddArtillery.addActionListener(e -> {
FormArtilleryConfig form = new FormArtilleryConfig();
form.addListener(artillery -> {
if (listBoxMaps.getSelectedIndex() == -1) {
return;
}
if (artillery != null) {
try {
DrawingObjectArtillery objectArtillery = new DrawingObjectArtillery(artillery);
if (_mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).addArtillery(objectArtillery) != -1) {
JOptionPane.showMessageDialog(this, "Объект добавлен", "Успех", JOptionPane.INFORMATION_MESSAGE);
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showSet();
repaint();
logger.info("Добавлен новый объект");
} else {
logger.warn("Не удалось добавить объект");
JOptionPane.showMessageDialog(this, "Не удалось добавить объект", "Провал", JOptionPane.INFORMATION_MESSAGE);
}
} catch (StorageOverflowException ex) {
logger.warn("Ошибка переполнения хранилища: " + ex.getMessage());
JOptionPane.showMessageDialog(this, "Ошибка переполнения хранилища: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception ex) {
logger.fatal("Неизвестная ошибка: " + ex.getMessage());
JOptionPane.showMessageDialog(this, "Неизвестная ошибка: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
}
}
});
form.setVisible(true);
});
buttonRemoveArtillery.addActionListener(e -> {
String text = textBoxPosition.getText();
if (text == null || text.isEmpty()) {
return;
}
if (JOptionPane.showConfirmDialog(this, "Удалить объект?", "Удаление", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) {
return;
}
int position = Integer.parseInt(text);
try {
IDrawingObject deleted = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).removeArtilleryAt(position);
if (deleted != null) {
deletedObjects.push(deleted);
JOptionPane.showMessageDialog(this, "Объект удалён", "Успех", JOptionPane.INFORMATION_MESSAGE);
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showSet();
repaint();
logger.info("Удалён объект");
} else {
logger.warn("Не удалось удалить объект по позиции " + position + ". Объект равен null");
JOptionPane.showMessageDialog(this, "Не удалось удалить объект", "Провал", JOptionPane.INFORMATION_MESSAGE);
}
} catch (ArtilleryNotFoundException ex) {
logger.warn("Ошибка удаления: " + ex.getMessage());
JOptionPane.showMessageDialog(this, "Не удалось найти артиллерию по позиции: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception ex) {
logger.error("Неизвестная ошибка: " + ex.getMessage());
JOptionPane.showMessageDialog(this, "Неизвестная ошибка: " + ex.getMessage(), "Провал", JOptionPane.INFORMATION_MESSAGE);
}
});
buttonShowStorage.addActionListener(e -> {
if (listBoxMaps.getSelectedIndex() == -1) {
return;
}
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showSet();
repaint();
});
buttonShowOnMap.addActionListener(e -> {
if (listBoxMaps.getSelectedIndex() == -1) {
return;
}
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).showOnMap();
repaint();
});
buttonShowDeleted.addActionListener(e -> {
if (!deletedObjects.empty()) {
DrawingObjectArtillery deleted = (DrawingObjectArtillery) deletedObjects.pop();
FormArtillery dialog = new FormArtillery(deleted.getArtillery());
dialog.setSize(800, 500);
dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} else {
JOptionPane.showMessageDialog(this, "Стек удалённых объектов пуст", "Провал", JOptionPane.INFORMATION_MESSAGE);
}
});
buttonLeft.addActionListener(e -> {
if (listBoxMaps.getSelectedIndex() != -1) {
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).moveObject(Direction.Left);
repaint();
}
});
buttonRight.addActionListener(e -> {
if (listBoxMaps.getSelectedIndex() != -1) {
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).moveObject(Direction.Right);
repaint();
}
});
buttonUp.addActionListener(e -> {
if (listBoxMaps.getSelectedIndex() != -1) {
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).moveObject(Direction.Up);
repaint();
}
});
buttonDown.addActionListener(e -> {
if (listBoxMaps.getSelectedIndex() != -1) {
bufferedImage = _mapsCollection.getMap(Optional.ofNullable(listBoxMaps.getSelectedValue()).orElse("")).moveObject(Direction.Down);
repaint();
}
});
}
private void reloadMaps() {
int index = listBoxMaps.getSelectedIndex();
listBoxMaps.setListData(_mapsCollection.getKeys().toArray(new String[0]));
int size = listBoxMaps.getModel().getSize();
if (size > 0 && (index == -1 || index >= size)) {
listBoxMaps.setSelectedIndex(0);
} else if (index > -1 && index < size) {
listBoxMaps.setSelectedIndex(index);
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (bufferedImage != null) {
pictureBox.paintComponents(bufferedImage.getGraphics());
pictureBox.getGraphics().drawImage(bufferedImage, 0, 0, null);
}
}
}

10
IDrawingObject.java Normal file
View File

@ -0,0 +1,10 @@
import java.awt.*;
public interface IDrawingObject {
float getStep();
void setObject(int x, int y, int width, int height);
void moveObject(Direction direction);
void drawingObject(Graphics2D g);
float[] getCurrentPosition();
String getInfo();
}

8
IDrawingRollers.java Normal file
View File

@ -0,0 +1,8 @@
import java.awt.*;
public interface IDrawingRollers {
void setRollersCount(int num);
void setColor(Color color);
void draw(Graphics2D g, int x, int y, int artilleryWidth, int artilleryHeight);
int getRollersCount();
}

View File

@ -0,0 +1,148 @@
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Iterator;
public class MapWithSetArtilleriesGeneric<T extends IDrawingObject, U extends AbstractMap> {
public final int _pictureWidth;
public final int _pictureHeight;
public final int _placeSizeWidth = 210;
public final int _placeSizeHeight = 90;
public final SetArtilleriesGeneric<T> _setArtilleries;
private final U _map;
public MapWithSetArtilleriesGeneric(int picWidth, int picHeight, U map) {
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_setArtilleries = new SetArtilleriesGeneric<>(width * height);
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
}
public U getMap() {
return _map;
}
public int addArtillery(T artillery) {
return _setArtilleries.insert(artillery);
}
public T removeArtilleryAt(int position) {
return _setArtilleries.remove(position);
}
public Image showSet() {
BufferedImage img = new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = (Graphics2D) img.getGraphics();
drawBackground(g2d);
drawArtilleries(g2d);
return img;
}
public Image showOnMap() {
shaking();
for (T artillery : _setArtilleries.getArtilleries()) {
return _map.createMap(_pictureWidth, _pictureHeight, artillery);
}
return new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB);
}
public Image moveObject(Direction direction) {
if (_map != null) {
return _map.moveObject(direction);
}
return new BufferedImage(_pictureWidth, _pictureHeight, BufferedImage.TYPE_INT_ARGB);
}
private void shaking() {
int j = _setArtilleries.getCount() - 1;
for (int i = 0; i < _setArtilleries.getCount(); i++)
{
if (_setArtilleries.get(i) == null)
{
for (; j > i; j--)
{
var artillery = _setArtilleries.get(j);
if (artillery != null)
{
_setArtilleries.insert(artillery, i);
_setArtilleries.remove(j);
break;
}
}
if (j <= i)
{
return;
}
}
}
}
private void drawBackground(Graphics2D g) {
Color pen = Color.black;
Color box = new Color(0, 100, 0, 255);
Color flag = Color.red;
Stroke normalStroke = new BasicStroke(1);
Stroke penStroke = new BasicStroke(3);
Stroke thinPenStroke = new BasicStroke(2);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{
g.setColor(pen);
g.setStroke(penStroke);
g.drawLine(i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
g.setColor(box);
g.fillRect(i * _placeSizeWidth + 5, j * _placeSizeHeight + _placeSizeHeight * 3 / 4 - 5, _placeSizeWidth / 3 - 5, _placeSizeHeight / 3 - 5);
g.setColor(pen);
g.setStroke(thinPenStroke);
g.drawLine(i * _placeSizeWidth + 5, j * _placeSizeHeight + _placeSizeHeight * 3 / 4 - 5, i * _placeSizeWidth + _placeSizeWidth / 3, j * _placeSizeHeight + _placeSizeHeight * 3 / 4 + _placeSizeHeight / 3 - 10);
g.drawLine(i * _placeSizeWidth + 5, j * _placeSizeHeight + _placeSizeHeight * 3 / 4 + _placeSizeHeight / 3 - 10, i * _placeSizeWidth + _placeSizeWidth / 3, j * _placeSizeHeight + _placeSizeHeight * 3 / 4 - 5);
g.setColor(flag);
g.fillRect(i * _placeSizeWidth + _placeSizeWidth * 5 / 12, j * _placeSizeHeight + _placeSizeHeight * 5 / 8 - 5, _placeSizeWidth / 5, _placeSizeHeight / 5);
g.setColor(pen);
g.setStroke(thinPenStroke);
g.drawLine(i * _placeSizeWidth + _placeSizeWidth * 5 / 12, j * _placeSizeHeight + _placeSizeHeight - 5, i * _placeSizeWidth + _placeSizeWidth * 5 / 12, j * _placeSizeHeight + _placeSizeHeight * 5 / 8 - 5);
}
g.setColor(pen);
g.setStroke(penStroke);
g.drawLine(i * _placeSizeWidth, 0, i * _placeSizeWidth, (_pictureHeight / _placeSizeHeight) * _placeSizeHeight);
}
g.setStroke(normalStroke);
}
private void drawArtilleries(Graphics2D g) {
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int index = 0;
for (T artillery : _setArtilleries.getArtilleries())
{
artillery.setObject(index % width * _placeSizeWidth + 10, (height - 1 - index / width) * _placeSizeHeight + 10, _pictureWidth, _pictureHeight);
artillery.drawingObject(g);
index++;
}
}
public String getData(char separatorType, char separatorData) {
StringBuilder data = new StringBuilder(String.format("%s%c", _map.getClass().getSimpleName(), separatorType));
for (var artillery : _setArtilleries.getArtilleries()) {
data.append(String.format("%s%c", artillery.getInfo(), separatorData));
}
return data.toString();
}
@SuppressWarnings("unchecked")
public void loadData(String[] records) {
for (int i = records.length - 1; i >= 0; i--) {
_setArtilleries.insert((T) DrawingObjectArtillery.create(records[i]));
}
}
}

161
MapsCollection.java Normal file
View File

@ -0,0 +1,161 @@
import java.io.*;
import java.nio.file.NoSuchFileException;
import java.util.HashMap;
import java.util.Set;
public class MapsCollection {
private final HashMap<String, MapWithSetArtilleriesGeneric<IDrawingObject, AbstractMap>> _mapsStorage;
private final int _pictureWidth;
private final int _pictureHeight;
private final char separatorDict = '|';
private final char separatorData = ';';
public Set<String> getKeys() {
return _mapsStorage.keySet();
}
public MapsCollection(int pictureWidth, int pictureHeight) {
_mapsStorage = new HashMap<>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
public void addMap(String name, AbstractMap map) {
if (!_mapsStorage.containsKey(name)) {
_mapsStorage.put(name, new MapWithSetArtilleriesGeneric<>(_pictureWidth, _pictureHeight, map));
}
}
public void deleteMap(String name) {
_mapsStorage.remove(name);
}
public MapWithSetArtilleriesGeneric<IDrawingObject, AbstractMap> getMap(String name) {
return _mapsStorage.getOrDefault(name, null);
}
public IDrawingObject getArtillery(String mapName, int index) {
var map = _mapsStorage.getOrDefault(mapName, null);
if (map != null) {
return map._setArtilleries.get(index);
}
return null;
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public void saveData(String filename) throws IOException {
File file = new File(filename);
if (file.exists()) {
file.delete();
}
file.createNewFile();
try (PrintWriter writer = new PrintWriter(file)) {
writer.println("MapsCollection");
for (var storage : _mapsStorage.entrySet()) {
writer.println(String.format("%s%c%s", storage.getKey(), separatorDict, storage.getValue().getData(separatorDict, separatorData)));
}
}
}
public void loadData(String filename) throws IOException {
File file = new File(filename);
if (!file.exists()) {
throw new FileNotFoundException("Файл не найден");
}
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String currentLine = reader.readLine();
if (currentLine == null || !currentLine.contains("MapsCollection")) {
throw new FileFormatException("Неверный формат файла");
}
_mapsStorage.clear();
while ((currentLine = reader.readLine()) != null) {
var elements = currentLine.split(String.format("\\%c", separatorDict));
AbstractMap map = switch (elements[1]) {
case "SimpleMap" -> new SimpleMap();
case "ForestMap" -> new ForestMap();
default -> null;
};
_mapsStorage.put(elements[0], new MapWithSetArtilleriesGeneric<>(_pictureWidth, _pictureHeight, map));
_mapsStorage.get(elements[0]).loadData(elements[2].split(separatorData + "\n?"));
}
}
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public void saveMap(String mapName, String filename) throws Exception {
File file = new File(filename);
if (file.exists()) {
file.delete();
}
file.createNewFile();
MapWithSetArtilleriesGeneric<IDrawingObject, AbstractMap> map = _mapsStorage.getOrDefault(mapName, null);
if (map == null) {
throw new IndexOutOfBoundsException();
}
try (PrintWriter writer = new PrintWriter(file)) {
writer.println("Map");
writer.println(mapName);
writer.println(map.getMap().getClass().getSimpleName());
for (var artillery : map._setArtilleries.getArtilleries()) {
writer.println(artillery.getInfo());
}
}
}
public void loadMap(String filename) throws IOException {
File file = new File(filename);
if (!file.exists()) {
throw new FileNotFoundException("Файл не найден");
}
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String currentLine = reader.readLine();
if (currentLine == null || !currentLine.contains("Map")) {
throw new FileFormatException("Неверный формат файла");
}
String mapName = reader.readLine();
MapWithSetArtilleriesGeneric<IDrawingObject, AbstractMap> map;
if (_mapsStorage.containsKey(mapName)) {
map = _mapsStorage.get(mapName);
if (!map.getMap().getClass().getSimpleName().equals(reader.readLine())) {
throw new FileFormatException("Неверный формат файла");
}
map._setArtilleries.clear();
} else {
map = switch (reader.readLine()) {
case "SimpleMap" -> new MapWithSetArtilleriesGeneric<>(_pictureWidth, _pictureHeight, new SimpleMap());
case "ForestMap" -> new MapWithSetArtilleriesGeneric<>(_pictureWidth, _pictureHeight, new ForestMap());
default -> null;
};
}
while ((currentLine = reader.readLine()) != null) {
map._setArtilleries.insert(DrawingObjectArtillery.create(currentLine));
}
_mapsStorage.put(mapName, map);
}
}
}

View File

@ -1,10 +1,9 @@
import javax.swing.*;
import org.apache.logging.log4j.*;
public class Program {
public static void main(String[] args) {
FormArtillery form = new FormArtillery();
form.setSize(640, 480);
form.setVisible(true);
FormMapWithSetArtilleries form = new FormMapWithSetArtilleries(LogManager.getLogger(Program.class));
form.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}

View File

@ -1,5 +1,18 @@
public enum RollersCount {
Four,
Five,
Six
Six;
public int getValue() {
return switch (this) {
case Four -> 4;
case Five -> 5;
case Six -> 6;
};
}
@Override
public String toString() {
return Integer.toString(getValue());
}
}

17
RollersType.java Normal file
View File

@ -0,0 +1,17 @@
import java.awt.*;
import java.util.Random;
public enum RollersType {
Standard,
Squared,
Cross;
public static IDrawingRollers random(int rollersCount, Color bodyColor) {
return switch (new Random().nextInt(RollersType.values().length)) {
case 0 -> new DrawingRollers(rollersCount, bodyColor);
case 1 -> new DrawingSquaredRollers(rollersCount, bodyColor);
case 2 -> new DrawingCrossRollers(rollersCount, bodyColor);
default -> null;
};
}
}

View File

@ -0,0 +1,68 @@
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Objects;
public class SetArtilleriesGeneric<T> {
private final ArrayList<T> _places;
private final int _maxCount;
public int getCount() {
return _places.size();
}
public SetArtilleriesGeneric(int count) {
_maxCount = count;
_places = new ArrayList<>(count);
}
public int insert(T artillery) {
return insert(artillery, 0);
}
public int insert(T artillery, int position) {
if (getCount() == _maxCount) {
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position > getCount()) {
return -1;
}
_places.add(position, artillery);
return position;
}
public T remove(int position) {
if (position < 0 || position >= getCount())
{
return null;
}
T result = _places.get(position);
if (result == null) {
throw new ArtilleryNotFoundException(position);
}
_places.remove(position);
return result;
}
public T get(int position) {
if (position < 0 || position >= getCount()) {
return null;
}
return _places.get(position);
}
public Iterable<T> getArtilleries() {
return () -> _places.stream().filter(Objects::nonNull).iterator();
}
public void clear() {
_places.clear();
}
}

40
SimpleMap.java Normal file
View File

@ -0,0 +1,40 @@
import java.awt.*;
import java.util.Arrays;
public class SimpleMap extends AbstractMap {
private final Color barrierColor = Color.black;
private final Color roadColor = Color.gray;
@Override
protected void drawBarrierPart(Graphics2D g, int i, int j) {
g.setColor(barrierColor);
g.fillRect(j * (int) _size_x, i * (int) _size_y, (int) _size_x, (int) _size_y);
}
@Override
protected void drawRoadPart(Graphics2D g, int i, int j) {
g.setColor(roadColor);
g.fillRect(j * (int) _size_x, i * (int) _size_y, (int) _size_x, (int) _size_y);
}
@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[] row : _map) {
Arrays.fill(row, _freeRoad);
}
while (counter < 50)
{
int x = _random.nextInt(0, 100);
int y = _random.nextInt(0, 100);
if (_map[y][x] == _freeRoad)
{
_map[y][x] = _barrier;
counter++;
}
}
}
}

View File

@ -0,0 +1,19 @@
public class StorageOverflowException extends RuntimeException{
public StorageOverflowException() {
}
public StorageOverflowException(String message) {
super(message);
}
public StorageOverflowException(int count) {
super("В наборе превышено допустимое количество: " + count);
}
public StorageOverflowException(String message, Throwable cause) {
super(message, cause);
}
public StorageOverflowException(Throwable cause) {
super(cause);
}
}

25
log4j2.xml Normal file
View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info" >
<Appenders>
<File name="error" fileName="error.log" append="true">
<PatternLayout>
<Pattern>%-5level %msg (%d{dd.MM.yyyy})%n</Pattern>
</PatternLayout>
<ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY"/>
</File>
<File name="info" fileName="info.log" append="true">
<PatternLayout>
<Pattern>%-5level %msg (%d{dd.MM.yyyy})%n</Pattern>
</PatternLayout>
<ThresholdFilter level="WARN" onMatch="DENY" onMismatch="ACCEPT"/>
</File>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="info" />
<AppenderRef ref="error" />
</Root>
</Loggers>
</Configuration>