PIbd-23. Zakharov R.A. Lab work 03 #4

Closed
Zakharov_Rostislav wants to merge 7 commits from Lab3 into Lab2
12 changed files with 400 additions and 5 deletions

View File

@ -1,7 +1,9 @@
import frames.FrameBattleship;
import frames.FrameShipsCollection;
import frames.HardFrame;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException { new FrameBattleship(); }
public static void main(String[] args) throws IOException { new HardFrame(); }
}

View File

@ -5,6 +5,17 @@ import java.awt.*;
public class DrawingBlocks implements IDrawBlocks{
private BlocksNumber number;
@Override
public int getNumber() {
int x = 0;
if(number == BlocksNumber.TWO)
x = 2;
else if(number == BlocksNumber.FOUR)
x = 4;
else if(number == BlocksNumber.SIX)
x = 6;
return x;
}
@Override
public void setNumber(int x){
if(x <= 2)
number = BlocksNumber.TWO;
@ -14,6 +25,10 @@ public class DrawingBlocks implements IDrawBlocks{
number = BlocksNumber.SIX;
}
@Override
public int getType() {
return 0;
}
@Override
public void drawBlocks(Graphics2D graphics2D, int _startX, int _startY){
graphics2D.fillRect(_startX+52, _startY+12, 6, 6);
graphics2D.fillRect(_startX+52, _startY+32, 6, 6);

View File

@ -5,6 +5,17 @@ import java.awt.*;
public class DrawingCrossBlocks implements IDrawBlocks{
private BlocksNumber number;
@Override
public int getNumber() {
int x = 0;
if(number == BlocksNumber.TWO)
x = 2;
else if(number == BlocksNumber.FOUR)
x = 4;
else if(number == BlocksNumber.SIX)
x = 6;
return x;
}
@Override
public void setNumber(int x){
if(x <= 2)
number = BlocksNumber.TWO;
@ -14,6 +25,10 @@ public class DrawingCrossBlocks implements IDrawBlocks{
number = BlocksNumber.SIX;
}
@Override
public int getType() {
return 2;
}
@Override
public void drawBlocks(Graphics2D graphics2D, int _startX, int _startY){
graphics2D.fillRect(_startX+54, _startY+12, 2, 6);
graphics2D.fillRect(_startX+52, _startY+14, 6, 2);

View File

@ -5,6 +5,17 @@ import java.awt.*;
public class DrawingRoundBlocks implements IDrawBlocks{
private BlocksNumber number;
@Override
public int getNumber() {
int x = 0;
if(number == BlocksNumber.TWO)
x = 2;
else if(number == BlocksNumber.FOUR)
x = 4;
else if(number == BlocksNumber.SIX)
x = 6;
return x;
}
@Override
public void setNumber(int x){
if(x <= 2)
number = BlocksNumber.TWO;
@ -14,6 +25,10 @@ public class DrawingRoundBlocks implements IDrawBlocks{
number = BlocksNumber.SIX;
}
@Override
public int getType() {
return 1;
}
@Override
public void drawBlocks(Graphics2D graphics2D, int _startX, int _startY){
graphics2D.fillOval(_startX+50, _startY+11, 8, 8);
graphics2D.fillOval(_startX+50, _startY+31, 8, 8);

View File

@ -1,6 +1,7 @@
package drawing_objects;
import entities.EntityShip;
import movement_strategy.*;
import java.awt.*;
@ -18,6 +19,7 @@ public class DrawingShip {
public int getWidth() {return shipWidth;}
private int shipHeight = 50;
public int getHeight() {return shipHeight;}
public IMoveableObject getMoveableObject() {return new DrawingObjectShip(this);}
public DrawingShip(int speed, double weight, Color bodyColor, int width, int height, int blocksType, int blocksNumber) {
if (width < shipWidth || height < shipHeight)
return;

View File

@ -3,6 +3,8 @@ package drawing_objects;
import java.awt.*;
public interface IDrawBlocks {
int getNumber();
void setNumber(int x);
int getType();
void drawBlocks(Graphics2D graphics2D, int _startX, int _startY);
}

View File

@ -20,6 +20,9 @@ import java.util.Random;
public class FrameBattleship extends JFrame {
private DrawingShip drawingShip;
private AbstractStrategy abstractStrategy;
public JButton selectShipButton;
private DrawingShip selectedShip;
public DrawingShip getSelectedShip() {return selectedShip;}
private JComboBox<String> comboBoxStrategy;
private JComponent pictureBoxBattleship;
public FrameBattleship() throws IOException {
@ -40,6 +43,7 @@ public class FrameBattleship extends JFrame {
JButton stepButton = new JButton("Шаг");
JButton createShipButton = new JButton("Создать корабль");
JButton createBattleshipButton = new JButton("Создать линкор");
selectShipButton = new JButton("Выбрать корабль");
JButton rightButton = new JButton(new ImageIcon(ImageIO.read(new File("images/right.png"))));
rightButton.setPreferredSize(new Dimension(30,30));
JButton leftButton = new JButton(new ImageIcon(ImageIO.read(new File("images/left.png"))));
@ -75,6 +79,9 @@ public class FrameBattleship extends JFrame {
constraints.gridx = 1;
constraints.gridy = 0;
createPanel.add(createBattleshipButton, constraints);
constraints.gridx = 2;
constraints.gridy = 0;
createPanel.add(selectShipButton, constraints);
//addition to movementPanel
constraints.gridx = 2;
constraints.gridy = 1;
@ -110,16 +117,19 @@ public class FrameBattleship extends JFrame {
private void buttonCreateBattleshipClick() {
Random random = new Random();
pictureBoxBattleship.setBounds(0,0,getContentPane().getWidth(),getContentPane().getHeight());
drawingShip = new DrawingBattleship(random.nextInt(200) + 100, random.nextInt(2000) + 1000, new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)),
new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)), random.nextBoolean(), random.nextBoolean(), pictureBoxBattleship.getWidth(), pictureBoxBattleship.getHeight(), random.nextInt(3),(random.nextInt(3)+1)*2);
Color bodyColor = JColorChooser.showDialog(this,"Выбор базового цвета", null);
Color additColor = JColorChooser.showDialog(this,"Выбор дополнительного цвета", null);
drawingShip = new DrawingBattleship(random.nextInt(200) + 100, random.nextInt(2000) + 1000, bodyColor, additColor, random.nextBoolean(),
random.nextBoolean(), pictureBoxBattleship.getWidth(), pictureBoxBattleship.getHeight(), random.nextInt(3),(random.nextInt(3)+1)*2);
drawingShip.setPosition(random.nextInt(90) + 10, random.nextInt(90) + 10);
draw();
}
private void buttonCreateShipClick(){
Random random = new Random();
pictureBoxBattleship.setBounds(0,0,getContentPane().getWidth(),getContentPane().getHeight());
drawingShip = new DrawingShip(random.nextInt(200) + 100, random.nextInt(2000) + 1000, new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)),
pictureBoxBattleship.getWidth(), pictureBoxBattleship.getHeight(), random.nextInt(3),(random.nextInt(3)+1)*2);
Color bodyColor = JColorChooser.showDialog(this,"Выбор цвета", null);
drawingShip = new DrawingShip(random.nextInt(200) + 100, random.nextInt(2000) + 1000, bodyColor, pictureBoxBattleship.getWidth(),
pictureBoxBattleship.getHeight(), random.nextInt(3),(random.nextInt(3)+1)*2);
drawingShip.setPosition(random.nextInt(90) + 10, random.nextInt(90) + 10);
draw();
}
@ -168,4 +178,10 @@ public class FrameBattleship extends JFrame {
}
pictureBoxBattleship.repaint();
}
public void select(){
if (drawingShip == null) {
return;
}
selectedShip = drawingShip;
}
}

View File

@ -0,0 +1,95 @@
package frames;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import drawing_objects.DrawingShip;
import generics.ShipsGenericCollection;
import movement_strategy.DrawingObjectShip;
public class FrameShipsCollection extends JFrame {
private ShipsGenericCollection<DrawingShip, DrawingObjectShip> ships;
JComponent pictureBoxCollection;
TextField textFieldNumber;
public FrameShipsCollection(){
super("Набор кораблей");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createGui();
ships = new ShipsGenericCollection<>(pictureBoxCollection.getWidth(), pictureBoxCollection.getHeight());
setVisible(true);
}
private void createGui(){
//components initialisation
pictureBoxCollection = new JComponent(){
public void paintComponent(Graphics graphics){
super.paintComponent(graphics);
Graphics2D graphics2D = (Graphics2D) graphics;
if (ships != null) ships.showShips(graphics2D);
super.repaint();
}
};
pictureBoxCollection.setPreferredSize(new Dimension(700, 450));
JButton buttonAddShip = new JButton("Добавить корабль");
textFieldNumber = new TextField();
JButton buttonRemoveShip = new JButton("Удалить корабль");
JButton buttonRefreshCollection = new JButton("Обновить коллекцию");
//ActionListeners and ActionCommand addition
buttonAddShip.addActionListener(e -> buttonAddShipClick());
buttonRemoveShip.addActionListener(e -> buttonRemoveShipClick());
buttonRefreshCollection.addActionListener(e -> buttonRefreshCollectionClick());
//addition to frame
JPanel panelCollection = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.insets.left = constraints.insets.right = 2;
constraints.insets.top = constraints.insets.bottom = 25;
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 0;
constraints.gridy = 0;
panelCollection.add(buttonAddShip, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
panelCollection.add(textFieldNumber, constraints);
constraints.gridx = 0;
constraints.gridy = 2;
panelCollection.add(buttonRemoveShip, constraints);
constraints.gridx = 0;
constraints.gridy = 3;
panelCollection.add(buttonRefreshCollection, constraints);
setLayout(new BorderLayout());
add(panelCollection, BorderLayout.EAST);
add(pictureBoxCollection, BorderLayout.CENTER);
pack();
}
private void buttonAddShipClick() {
FrameBattleship form;
try {
form = new FrameBattleship();
} catch (IOException e) {
throw new RuntimeException(e);
}
form.selectShipButton.addActionListener(e->{
form.select();
DrawingShip ship = form.getSelectedShip();
form.dispose();
if (ships.insert(ship)) {
JOptionPane.showMessageDialog(this, "Объект добавлен");
pictureBoxCollection.repaint();
}
else {
JOptionPane.showMessageDialog(this, "Не удалось добавить объект");
}
});
}
private void buttonRemoveShipClick(){
int pos = Integer.parseInt(textFieldNumber.getText());
if (ships.remove(pos)){
JOptionPane.showMessageDialog(this, "Объект удален");
pictureBoxCollection.repaint();
}
else{
JOptionPane.showMessageDialog(this, "Не удалось удалить объект");
}
}
private void buttonRefreshCollectionClick(){pictureBoxCollection.repaint();}
}

51
src/frames/HardFrame.java Normal file
View File

@ -0,0 +1,51 @@
package frames;
import drawing_objects.DrawingShip;
import drawing_objects.IDrawBlocks;
import entities.EntityShip;
import generics.HardGeneric;
import javax.swing.*;
import java.awt.*;
public class HardFrame extends JFrame {
HardGeneric<EntityShip, IDrawBlocks> generic;
DrawingShip drawing;
private final JComponent pictureBox;
private final int pictureBoxWidth = 200;
private final int pictureBoxHeight = 100;
public HardFrame(){
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
pictureBox = new JComponent(){
public void paintComponent(Graphics graphics){
super.paintComponent(graphics);
Graphics2D graphics2D = (Graphics2D) graphics;
if (drawing != null) drawing.drawTransport(graphics2D);
super.repaint();
}
};
pictureBox.setPreferredSize(new Dimension(pictureBoxWidth, pictureBoxHeight));
JButton buttonMakeObject = new JButton("Создать новый объект");
generic = new HardGeneric<>(10, 25, pictureBoxWidth, pictureBoxHeight);
boolean check;
do{
check = generic.insertShip(generic.makeRandomShip());
}while(check);
do {
check = generic.insertBlock(generic.makeRandomBlock());
}while(check);
buttonMakeObject.addActionListener(e -> {
DrawingShip drawingShip = generic.makeObject();
drawingShip.setPosition(pictureBoxWidth / 2 - drawingShip.getWidth()/2, pictureBoxHeight / 2 - drawingShip.getHeight()/2);
drawing = drawingShip;
draw();
});
setLayout(new BorderLayout());
add(pictureBox, BorderLayout.CENTER);
add(buttonMakeObject, BorderLayout.SOUTH);
pack();
setVisible(true);
}
void draw(){pictureBox.repaint();}
}

View File

@ -0,0 +1,77 @@
package generics;
import drawing_objects.*;
import entities.EntityBattleship;
import entities.EntityShip;
import java.awt.*;
import java.util.Random;
public class HardGeneric<T extends EntityShip, U extends IDrawBlocks>{
T[] ships;
U[] blocks;
private int shipsNumber;
private int blocksNumber;
private final int PICTURE_WIDTH;
private final int PICTURE_HEIGHT;
public HardGeneric(int shipsCount, int blocksCount, int width, int height){
shipsNumber = 0;
blocksNumber = 0;
ships = (T[]) new EntityShip[shipsCount];
blocks = (U[]) new IDrawBlocks[blocksCount];
PICTURE_HEIGHT = height;
PICTURE_WIDTH = width;
}
public boolean insertShip(T entityShip){
Review

Методы добавления должны быть полиморфными

Методы добавления должны быть полиморфными
if(ships[ships.length-1] != null)
return false;
for(int i = shipsNumber -1; i>= 0; i--) {
ships[i + 1] = ships[i];
}
shipsNumber++;
ships[0] = entityShip;
return true;
}
public boolean insertBlock(U block){
if(blocks[blocks.length-1] != null)
return false;
for(int i = blocksNumber -1; i>= 0; i--) {
blocks[i + 1] = blocks[i];
}
blocksNumber++;
blocks[0] = block;
return true;
}
public DrawingShip makeObject(){
Random rand = new Random();
EntityShip entity = ships[rand.nextInt(0, shipsNumber)];
IDrawBlocks block = blocks[rand.nextInt(0, blocksNumber)];
if (entity instanceof EntityBattleship)
return new DrawingBattleship(entity.getSpeed(), entity.getWeight(), entity.getBodyColor(), ((EntityBattleship) entity).getAdditionalColor(),
((EntityBattleship) entity).getTurret(), ((EntityBattleship) entity).getRocketLauncher(), PICTURE_WIDTH, PICTURE_HEIGHT, block.getType(), block.getNumber());
return new DrawingShip(entity.getSpeed(), entity.getWeight(), entity.getBodyColor(), PICTURE_WIDTH, PICTURE_HEIGHT, block.getType(), block.getNumber());
}
public EntityShip makeRandomShip(){
Random random = new Random();
if (random.nextInt(2) == 0) {
return new EntityShip(random.nextInt(100, 300), random.nextDouble(1000, 3000),
new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
} else {
return new EntityBattleship(random.nextInt(100, 300), random.nextDouble(1000, 3000),
new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)),
new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)),
random.nextBoolean(), random.nextBoolean());
}
}
public IDrawBlocks makeRandomBlock(){
Random random = new Random();
IDrawBlocks block;
switch (random.nextInt(3)){
case 1 -> block = new DrawingRoundBlocks();
case 2 -> block = new DrawingCrossBlocks();
default -> block = new DrawingBlocks();
}
block.setNumber((random.nextInt(3) + 1) * 2);
return block;
}
}

View File

@ -0,0 +1,41 @@
package generics;
import java.lang.reflect.Array;
public class SetGeneric<T extends Object>{
private final T[] places;
public int getCount() {return places.length;}
public SetGeneric(int count, Class<T> type){
places = (T[]) Array.newInstance(type, count);
}
public boolean insert(T ship){
return insert(ship, 0);
}
public boolean insert(T ship, int position){
if (!(position >= 0 && position < places.length))
return false;
if (places[position] != null)
{
int ind = position;
while (ind < places.length && places[ind] != null)
ind++;
if (ind == places.length)
return false;
for (int i = ind - 1; i >= position; i--)
places[i + 1] = places[i];
}
places[position] = ship;
return true;
}
public boolean remove(int position){
if(!(position >= 0 && position < getCount()))
return false;
places[position] = null;
return true;
}
public T get(int position){
if(!(position >= 0 && position < getCount()))
return null;
return places[position];
}
}

View File

@ -0,0 +1,64 @@
package generics;
import drawing_objects.*;
import movement_strategy.*;
import java.awt.*;
public class ShipsGenericCollection<T extends DrawingShip, U extends IMoveableObject>{
private int pictureWidth;
private int pictureHeight;
private final int placeSizeWidth = 220;
private final int placeSizeHeight = 60;
private SetGeneric<T> collection;
public ShipsGenericCollection(int picWidth, int picHeight){
int width = picWidth / placeSizeWidth;
int height = picHeight / placeSizeHeight;
pictureWidth = picWidth;
pictureHeight = picHeight;
collection = new SetGeneric<T>(width * height, (Class<T>) DrawingShip.class);
}
public boolean insert ( T obj) {
if (obj != null)
return collection.insert(obj);
return false;
}
public boolean remove (int pos){
T obj = collection.get(pos);
if (obj != null)
return collection.remove(pos);
return false;
}
public U getU(int pos){
if(collection.get(pos) == null)
return null;
return (U)collection.get(pos).getMoveableObject();
}
public void showShips(Graphics2D graphics2D){
DrawBackground(graphics2D);
DrawObjects(graphics2D);
}
private void DrawBackground(Graphics2D g){
BasicStroke stroke = new BasicStroke(3);
g.setStroke(stroke);
for (int i = 0; i < pictureWidth / placeSizeWidth; i++){
for (int j = 0; j < pictureHeight / placeSizeHeight + 1; ++j){
g.drawLine(i * placeSizeWidth, j * placeSizeHeight, i *
placeSizeWidth + placeSizeWidth / 2, j * placeSizeHeight);
}
g.drawLine(i * placeSizeWidth, 0, i * placeSizeWidth,
pictureHeight / placeSizeHeight * placeSizeHeight);
}
}
private void DrawObjects(Graphics2D g){
for (int i = 0; i < collection.getCount(); i++){
DrawingShip ship = collection.get(i);
if (ship != null)
{
int inRow = pictureWidth / placeSizeWidth;
ship.setPosition(i % inRow * placeSizeWidth, (collection.getCount() / inRow - 1 - i / inRow) * placeSizeHeight + 5);
ship.drawTransport(g);
}
}
}
}