diff --git a/robots/src/gui/GameVisualizer.java b/robots/src/gui/GameVisualizer.java index f82cfd8f8..4e96c1090 100644 --- a/robots/src/gui/GameVisualizer.java +++ b/robots/src/gui/GameVisualizer.java @@ -4,36 +4,27 @@ import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; -import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.util.Timer; import java.util.TimerTask; -import javax.swing.JPanel; +import javax.swing.*; + +import static gui.RobotModel.round; public class GameVisualizer extends JPanel { + public RobotModel robotModel = new RobotModel(); + public RobotCoordinatesWindow robotCoordinatesWindow = new RobotCoordinatesWindow(robotModel); private final Timer m_timer = initTimer(); - - private static Timer initTimer() + private static Timer initTimer() { Timer timer = new Timer("events generator", true); return timer; } - - private volatile double m_robotPositionX = 100; - private volatile double m_robotPositionY = 100; - private volatile double m_robotDirection = 0; - - private volatile int m_targetPositionX = 150; - private volatile int m_targetPositionY = 100; - - private static final double maxVelocity = 0.1; - private static final double maxAngularVelocity = 0.001; - - public GameVisualizer() + public GameVisualizer() { m_timer.schedule(new TimerTask() { @@ -48,7 +39,7 @@ public void run() @Override public void run() { - onModelUpdateEvent(); + robotModel.onModelUpdateEvent(); } }, 0, 10); addMouseListener(new MouseAdapter() @@ -56,120 +47,23 @@ public void run() @Override public void mouseClicked(MouseEvent e) { - setTargetPosition(e.getPoint()); + robotModel.setTargetPosition(e.getPoint()); repaint(); } }); setDoubleBuffered(true); } - - protected void setTargetPosition(Point p) - { - m_targetPositionX = p.x; - m_targetPositionY = p.y; - } - protected void onRedrawEvent() { EventQueue.invokeLater(this::repaint); } - - private static double distance(double x1, double y1, double x2, double y2) - { - double diffX = x1 - x2; - double diffY = y1 - y2; - return Math.sqrt(diffX * diffX + diffY * diffY); - } - - private static double angleTo(double fromX, double fromY, double toX, double toY) - { - double diffX = toX - fromX; - double diffY = toY - fromY; - - return asNormalizedRadians(Math.atan2(diffY, diffX)); - } - - protected void onModelUpdateEvent() - { - double distance = distance(m_targetPositionX, m_targetPositionY, - m_robotPositionX, m_robotPositionY); - if (distance < 0.5) - { - return; - } - double velocity = maxVelocity; - double angleToTarget = angleTo(m_robotPositionX, m_robotPositionY, m_targetPositionX, m_targetPositionY); - double angularVelocity = 0; - if (angleToTarget > m_robotDirection) - { - angularVelocity = maxAngularVelocity; - } - if (angleToTarget < m_robotDirection) - { - angularVelocity = -maxAngularVelocity; - } - - moveRobot(velocity, angularVelocity, 10); - } - - private static double applyLimits(double value, double min, double max) - { - if (value < min) - return min; - if (value > max) - return max; - return value; - } - - private void moveRobot(double velocity, double angularVelocity, double duration) - { - velocity = applyLimits(velocity, 0, maxVelocity); - angularVelocity = applyLimits(angularVelocity, -maxAngularVelocity, maxAngularVelocity); - double newX = m_robotPositionX + velocity / angularVelocity * - (Math.sin(m_robotDirection + angularVelocity * duration) - - Math.sin(m_robotDirection)); - if (!Double.isFinite(newX)) - { - newX = m_robotPositionX + velocity * duration * Math.cos(m_robotDirection); - } - double newY = m_robotPositionY - velocity / angularVelocity * - (Math.cos(m_robotDirection + angularVelocity * duration) - - Math.cos(m_robotDirection)); - if (!Double.isFinite(newY)) - { - newY = m_robotPositionY + velocity * duration * Math.sin(m_robotDirection); - } - m_robotPositionX = newX; - m_robotPositionY = newY; - double newDirection = asNormalizedRadians(m_robotDirection + angularVelocity * duration); - m_robotDirection = newDirection; - } - - private static double asNormalizedRadians(double angle) - { - while (angle < 0) - { - angle += 2*Math.PI; - } - while (angle >= 2*Math.PI) - { - angle -= 2*Math.PI; - } - return angle; - } - - private static int round(double value) - { - return (int)(value + 0.5); - } - @Override public void paint(Graphics g) { super.paint(g); - Graphics2D g2d = (Graphics2D)g; - drawRobot(g2d, round(m_robotPositionX), round(m_robotPositionY), m_robotDirection); - drawTarget(g2d, m_targetPositionX, m_targetPositionY); + Graphics2D g2d = (Graphics2D)g; + drawRobot(g2d, round(robotModel.m_robotPositionX), round(robotModel.m_robotPositionY), robotModel.m_robotDirection); + drawTarget(g2d, robotModel.m_targetPositionX, robotModel.m_targetPositionY); } private static void fillOval(Graphics g, int centerX, int centerY, int diam1, int diam2) @@ -181,12 +75,11 @@ private static void drawOval(Graphics g, int centerX, int centerY, int diam1, in { g.drawOval(centerX - diam1 / 2, centerY - diam2 / 2, diam1, diam2); } - private void drawRobot(Graphics2D g, int x, int y, double direction) { - int robotCenterX = round(m_robotPositionX); - int robotCenterY = round(m_robotPositionY); - AffineTransform t = AffineTransform.getRotateInstance(direction, robotCenterX, robotCenterY); + int robotCenterX = round(robotModel.m_robotPositionX); + int robotCenterY = round(robotModel.m_robotPositionY); + AffineTransform t = AffineTransform.getRotateInstance(robotModel.m_robotDirection, robotCenterX, robotCenterY); g.setTransform(t); g.setColor(Color.MAGENTA); fillOval(g, robotCenterX, robotCenterY, 30, 10); @@ -197,7 +90,6 @@ private void drawRobot(Graphics2D g, int x, int y, double direction) g.setColor(Color.BLACK); drawOval(g, robotCenterX + 10, robotCenterY, 5, 5); } - private void drawTarget(Graphics2D g, int x, int y) { AffineTransform t = AffineTransform.getRotateInstance(0, 0, 0); diff --git a/robots/src/gui/GameWindow.java b/robots/src/gui/GameWindow.java index ecb63c00f..7475fef39 100644 --- a/robots/src/gui/GameWindow.java +++ b/robots/src/gui/GameWindow.java @@ -1,20 +1,24 @@ package gui; import java.awt.BorderLayout; +import java.util.ResourceBundle; import javax.swing.JInternalFrame; import javax.swing.JPanel; -public class GameWindow extends JInternalFrame -{ - private final GameVisualizer m_visualizer; - public GameWindow() - { - super("Игровое поле", true, true, true, true); - m_visualizer = new GameVisualizer(); +public class GameWindow extends JInternalFrame { + public final GameVisualizer m_visualizer = new GameVisualizer(); + //private ResourceBundle messages; + + public GameWindow() { + super(MainApplicationFrame.messages.getString("game.window.title"), true, true, true, true); JPanel panel = new JPanel(new BorderLayout()); panel.add(m_visualizer, BorderLayout.CENTER); getContentPane().add(panel); pack(); } + + public void updateTitle() { + setTitle(MainApplicationFrame.messages.getString("game.window.title")); + } } diff --git a/robots/src/gui/LogWindow.java b/robots/src/gui/LogWindow.java index 723d3e2fc..c9c00da13 100644 --- a/robots/src/gui/LogWindow.java +++ b/robots/src/gui/LogWindow.java @@ -18,7 +18,7 @@ public class LogWindow extends JInternalFrame implements LogChangeListener public LogWindow(LogWindowSource logSource) { - super("Протокол работы", true, true, true, true); + super(MainApplicationFrame.messages.getString("protocol.window.title"), true, true, true, true); m_logSource = logSource; m_logSource.registerListener(this); m_logContent = new TextArea(""); @@ -29,6 +29,7 @@ public LogWindow(LogWindowSource logSource) getContentPane().add(panel); pack(); updateLogContent(); + updateTitleP(); } private void updateLogContent() @@ -40,6 +41,10 @@ private void updateLogContent() } m_logContent.setText(content.toString()); m_logContent.invalidate(); + updateTitleP(); + } + public void updateTitleP() { + setTitle(MainApplicationFrame.messages.getString("protocol.window.title")); } @Override diff --git a/robots/src/gui/MainApplicationFrame.java b/robots/src/gui/MainApplicationFrame.java index 62e943ee1..83570bd54 100644 --- a/robots/src/gui/MainApplicationFrame.java +++ b/robots/src/gui/MainApplicationFrame.java @@ -3,109 +3,72 @@ import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.KeyEvent; +import java.text.MessageFormat; +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import java.util.concurrent.ConcurrentHashMap; -import javax.swing.JDesktopPane; -import javax.swing.JFrame; -import javax.swing.JInternalFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.SwingUtilities; -import javax.swing.UIManager; -import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.*; import log.Logger; -/** - * Что требуется сделать: - * 1. Метод создания меню перегружен функционалом и трудно читается. - * Следует разделить его на серию более простых методов (или вообще выделить отдельный класс). - * - */ -public class MainApplicationFrame extends JFrame -{ +public class MainApplicationFrame extends JFrame { private final JDesktopPane desktopPane = new JDesktopPane(); - + public static ResourceBundle messages; + private final ConcurrentHashMap messageFormatCache = new ConcurrentHashMap<>(); + private final GameWindow gameWindow; + public MainApplicationFrame() { - //Make the big window be indented 50 pixels from each edge - //of the screen. - int inset = 50; + // Set default locale + changeLocale(Locale.getDefault()); + + // Make the big window be indented 50 pixels from each edge of the screen. + int inset = 50; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setBounds(inset, inset, - screenSize.width - inset*2, - screenSize.height - inset*2); + screenSize.width - inset * 2, + screenSize.height - inset * 2); setContentPane(desktopPane); - - + LogWindow logWindow = createLogWindow(); addWindow(logWindow); - GameWindow gameWindow = new GameWindow(); - gameWindow.setSize(400, 400); + gameWindow = new GameWindow(); + gameWindow.setSize(400, 400); addWindow(gameWindow); - + addWindow(gameWindow.m_visualizer.robotCoordinatesWindow); setJMenuBar(generateMenuBar()); setDefaultCloseOperation(EXIT_ON_CLOSE); + //WindowStateManager.loadWindowStateFromFile(desktopPane); } - - protected LogWindow createLogWindow() - { + + protected LogWindow createLogWindow() { LogWindow logWindow = new LogWindow(Logger.getDefaultLogSource()); - logWindow.setLocation(10,10); + logWindow.setLocation(10, 10); logWindow.setSize(300, 800); setMinimumSize(logWindow.getSize()); logWindow.pack(); Logger.debug("Протокол работает"); return logWindow; } - - protected void addWindow(JInternalFrame frame) - { + + protected void addWindow(JInternalFrame frame) { desktopPane.add(frame); frame.setVisible(true); } - -// protected JMenuBar createMenuBar() { -// JMenuBar menuBar = new JMenuBar(); -// -// //Set up the lone menu. -// JMenu menu = new JMenu("Document"); -// menu.setMnemonic(KeyEvent.VK_D); -// menuBar.add(menu); -// -// //Set up the first menu item. -// JMenuItem menuItem = new JMenuItem("New"); -// menuItem.setMnemonic(KeyEvent.VK_N); -// menuItem.setAccelerator(KeyStroke.getKeyStroke( -// KeyEvent.VK_N, ActionEvent.ALT_MASK)); -// menuItem.setActionCommand("new"); -//// menuItem.addActionListener(this); -// menu.add(menuItem); -// -// //Set up the second menu item. -// menuItem = new JMenuItem("Quit"); -// menuItem.setMnemonic(KeyEvent.VK_Q); -// menuItem.setAccelerator(KeyStroke.getKeyStroke( -// KeyEvent.VK_Q, ActionEvent.ALT_MASK)); -// menuItem.setActionCommand("quit"); -//// menuItem.addActionListener(this); -// menu.add(menuItem); -// -// return menuBar; -// } - - private JMenuBar generateMenuBar() - { + + private JMenuBar generateMenuBar() { JMenuBar menuBar = new JMenuBar(); - - JMenu lookAndFeelMenu = new JMenu("Режим отображения"); + + JMenu lookAndFeelMenu = new JMenu(getMessage("menu.view")); lookAndFeelMenu.setMnemonic(KeyEvent.VK_V); lookAndFeelMenu.getAccessibleContext().setAccessibleDescription( "Управление режимом отображения приложения"); - + { - JMenuItem systemLookAndFeel = new JMenuItem("Системная схема", KeyEvent.VK_S); + JMenuItem systemLookAndFeel = new JMenuItem(getMessage("menu.view.system"), KeyEvent.VK_S); systemLookAndFeel.addActionListener((event) -> { setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); this.invalidate(); @@ -114,7 +77,7 @@ private JMenuBar generateMenuBar() } { - JMenuItem crossplatformLookAndFeel = new JMenuItem("Универсальная схема", KeyEvent.VK_S); + JMenuItem crossplatformLookAndFeel = new JMenuItem(getMessage("menu.view.crossplatform"), KeyEvent.VK_S); crossplatformLookAndFeel.addActionListener((event) -> { setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); this.invalidate(); @@ -122,35 +85,87 @@ private JMenuBar generateMenuBar() lookAndFeelMenu.add(crossplatformLookAndFeel); } - JMenu testMenu = new JMenu("Тесты"); + JMenu testMenu = new JMenu(getMessage("menu.tests")); testMenu.setMnemonic(KeyEvent.VK_T); testMenu.getAccessibleContext().setAccessibleDescription( "Тестовые команды"); - + { - JMenuItem addLogMessageItem = new JMenuItem("Сообщение в лог", KeyEvent.VK_S); + JMenuItem addLogMessageItem = new JMenuItem(getMessage("menu.tests.addLogMessage"), KeyEvent.VK_S); addLogMessageItem.addActionListener((event) -> { Logger.debug("Новая строка"); }); testMenu.add(addLogMessageItem); } + JMenuItem exitItem = new JMenuItem(getMessage("menu.exit"), KeyEvent.VK_E); + exitItem.addActionListener((event) -> { + WindowStateManager.saveWindowStateToFile(desktopPane); + UIManager.put("OptionPane.yesButtonText", "Да"); + UIManager.put("OptionPane.noButtonText", "Нет"); + UIManager.put("OptionPane.cancelButtonText", "Извиняюсь!"); + int result = JOptionPane.showConfirmDialog(this, getMessage("menu.exit.confirm"), getMessage("menu.exit"), + JOptionPane.YES_NO_CANCEL_OPTION); + + if (result == JOptionPane.YES_OPTION) { + System.exit(0); + } + }); + + JMenu languageMenu = new JMenu("Язык"); + { + JMenuItem russianItem = new JMenuItem("Русский", KeyEvent.VK_R); + russianItem.addActionListener((event) -> { + changeLocale(Locale.forLanguageTag("ru-RU")); + updateUI(); + }); + languageMenu.add(russianItem); + } + { + JMenuItem englishItem = new JMenuItem("Английский", KeyEvent.VK_E); + englishItem.addActionListener((event) -> { + changeLocale(Locale.forLanguageTag("en-US")); + updateUI(); + }); + languageMenu.add(englishItem); + } + menuBar.add(lookAndFeelMenu); menuBar.add(testMenu); + menuBar.add(exitItem); + menuBar.add(languageMenu); return menuBar; } - - private void setLookAndFeel(String className) - { - try - { + + private void setLookAndFeel(String className) { + try { UIManager.setLookAndFeel(className); SwingUtilities.updateComponentTreeUI(this); - } - catch (ClassNotFoundException | InstantiationException - | IllegalAccessException | UnsupportedLookAndFeelException e) - { + } catch (ClassNotFoundException | InstantiationException + | IllegalAccessException | UnsupportedLookAndFeelException e) { // just ignore } } + + private void changeLocale(Locale locale) { + Locale.setDefault(locale); + try { + messages = ResourceBundle.getBundle("messages", locale); + } catch (MissingResourceException e) { + Logger.error("Resource bundle not found for locale: " + locale); + } + } + + private void updateUI() { + setJMenuBar(generateMenuBar()); + gameWindow.updateTitle(); + SwingUtilities.updateComponentTreeUI(this); + } + + private String getMessage(String key) { + String pattern = messages.getString(key); + MessageFormat messageFormat = messageFormatCache.computeIfAbsent(pattern, MessageFormat::new); + return messageFormat.format(new Object[]{}); + } } + diff --git a/robots/src/gui/RobotCoordinatesWindow.java b/robots/src/gui/RobotCoordinatesWindow.java new file mode 100644 index 000000000..7a92f841e --- /dev/null +++ b/robots/src/gui/RobotCoordinatesWindow.java @@ -0,0 +1,29 @@ +package gui; + +import javax.swing.*; +import java.util.Observable; +import java.util.Observer; + +public class RobotCoordinatesWindow extends JInternalFrame implements Observer { + private final JLabel coordinatesLabel; + public RobotCoordinatesWindow(RobotModel model) { + super(MainApplicationFrame.messages.getString("robot.coord.window.title")); + model.addObserver(this); + coordinatesLabel = new JLabel("X: " + model.getX() + ", Y: " + model.getY()); + this.add(coordinatesLabel); + this.setSize(300, 300); + this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + this.setVisible(true); + } + public void updateTitle() { + setTitle(MainApplicationFrame.messages.getString("robot.coord.window.title")); + } + @Override + public void update(Observable o, Object arg) { + if (o instanceof RobotModel) { + RobotModel model = (RobotModel) o; + coordinatesLabel.setText("X: " + model.getX() + ", Y: " + model.getY()); + updateTitle(); + } + } +} diff --git a/robots/src/gui/RobotModel.java b/robots/src/gui/RobotModel.java new file mode 100644 index 000000000..194742f58 --- /dev/null +++ b/robots/src/gui/RobotModel.java @@ -0,0 +1,139 @@ +package gui; + +import java.awt.Point; +import java.util.Observable; +import static java.lang.Math.abs; + + +public class RobotModel extends Observable{ + + protected volatile double m_robotPositionX = 100; + protected volatile double m_robotPositionY = 100; + protected volatile double m_robotDirection = 0; + + protected volatile int m_targetPositionX = 150; + protected volatile int m_targetPositionY = 100; + + private static final double maxVelocity = 0.1; + private static final double maxAngularVelocity = 0.001*3; + + + protected void setTargetPosition(Point p) + { + m_targetPositionX = p.x*2; + m_targetPositionY = p.y*2; + } + static int round(double value) + { + return (int)(value + 0.5); + } + private static double distance(double x1, double y1, double x2, double y2) + { + double diffX = x1 - x2; + double diffY = y1 - y2; + return Math.sqrt(diffX * diffX + diffY * diffY); + } + + private static double angleTo(double fromX, double fromY, double toX, double toY) + { + double diffX = toX - fromX; + double diffY = toY - fromY; + + return asNormalizedRadians(Math.atan2(diffY, diffX)); + } + + protected void onModelUpdateEvent() + { + double distance = distance(m_targetPositionX, m_targetPositionY, + m_robotPositionX, m_robotPositionY); + if (distance < 0.5) + { + return; + } + double velocity = maxVelocity; + double angleToTarget = angleTo(m_robotPositionX, m_robotPositionY, m_targetPositionX, m_targetPositionY); + double angularVelocity = 0; + if (abs(angleToTarget - m_robotDirection) < Math.PI) { + if (angleToTarget > m_robotDirection) { + angularVelocity = maxAngularVelocity; + } + else if (angleToTarget < m_robotDirection) { + angularVelocity = -maxAngularVelocity; + } + } + else { + if (angleToTarget > m_robotDirection) { + angularVelocity = -maxAngularVelocity; + } + else if (angleToTarget < m_robotDirection) { + angularVelocity = maxAngularVelocity; + } + } + + moveRobot(velocity, angularVelocity, 10); + setChanged(); + notifyObservers(); + } + + + private static double applyLimits(double value, double min, double max) + { + if (value < min) + return min; + if (value > max) + return max; + return value; + } + + private void moveRobot(double velocity, double angularVelocity, double duration) { + velocity = applyLimits(velocity, 0, maxVelocity); + angularVelocity = applyLimits(angularVelocity, -maxAngularVelocity, maxAngularVelocity); + double newX = m_robotPositionX + velocity / angularVelocity * + (Math.sin(m_robotDirection + angularVelocity * duration) - + Math.sin(m_robotDirection)); + + if (!Double.isFinite(newX)) { + newX = m_robotPositionX + velocity * duration * Math.cos(m_robotDirection); + } + double newY = m_robotPositionY - velocity / angularVelocity * + (Math.cos(m_robotDirection + angularVelocity * duration) - + Math.cos(m_robotDirection)); + if (!Double.isFinite(newY)) { + newY = m_robotPositionY + velocity * duration * Math.sin(m_robotDirection); + } + + + if (newX < 0) { + newX = 0; + m_robotDirection = Math.PI - m_robotDirection; + } + if (newY < 0) { + newY = 0; + m_robotDirection = -m_robotDirection; + } + + + m_robotPositionX = newX; + m_robotPositionY = newY; + m_robotDirection = asNormalizedRadians(m_robotDirection + angularVelocity * duration); +} + + private static double asNormalizedRadians(double angle) + { + while (angle < 0) + { + angle += 2*Math.PI; + } + while (angle >= 2*Math.PI) + { + angle -= 2*Math.PI; + } + return angle; + } + public double getX() { + return m_robotPositionX; + } + public double getY() { + return m_robotPositionY; + } +}