Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.io.*;
- import java.util.ArrayList;
- import java.util.regex.*;
- import javax.swing.*;
- @SuppressWarnings("serial")
- public class RobotRouteFrame extends JFrame implements ActionListener
- {
- private RobotRouteWorld m_objWorld = null; // Draws everything.
- private RobotRouteScriptFrame m_objScript = null; // Script JFrame.
- private Robot m_objRobot = null; // Robot.
- private boolean m_bUseTrig = false; // Use trigonometry or not?
- /**
- * Constructor.
- * @param strTitle Frame title.
- */
- public RobotRouteFrame(String strTitle)
- {
- super(strTitle);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- // Objects.
- m_objRobot = new Robot();
- m_objWorld = new RobotRouteWorld();
- m_objScript = new RobotRouteScriptFrame("Script Output");
- m_objScript.pack();
- // Associate the robot with the world.
- m_objWorld.setRobot(m_objRobot);
- // Create layout.
- createComponents();
- }
- /**
- * Create components and add to content pane.
- */
- public void createComponents()
- {
- JPanel objMainPanel = new JPanel(new GridLayout(1, 1));
- JPanel objBtnPanel = new JPanel(new GridLayout(1, 0));
- // Create the buttons.
- JButton btnLandmarks = new JButton("Load Landmarks");
- JButton btnWaypoints = new JButton("Load Waypoints");
- JButton btnResetGUI = new JButton("Reset World");
- JButton btnViewScript = new JButton("View Script");
- JButton btnViewStats = new JButton("View Statistics");
- // Set the actions.
- btnLandmarks.addActionListener(this);
- btnLandmarks.setActionCommand("landmarks");
- btnWaypoints.addActionListener(this);
- btnWaypoints.setActionCommand("waypoints");
- btnViewScript.addActionListener(this);
- btnViewScript.setActionCommand("script");
- btnViewStats.addActionListener(this);
- btnViewStats.setActionCommand("stats");
- btnResetGUI.addActionListener(this);
- btnResetGUI.setActionCommand("reset");
- // Add the buttons to the panel.
- objBtnPanel.add(btnLandmarks);
- objBtnPanel.add(btnWaypoints);
- objBtnPanel.add(btnViewScript);
- objBtnPanel.add(btnViewStats);
- objBtnPanel.add(btnResetGUI);
- // Add the World to the main panel.
- objMainPanel.add(m_objWorld);
- // Add our main panel.
- getContentPane().add(objMainPanel, BorderLayout.CENTER);
- getContentPane().add(objBtnPanel, BorderLayout.PAGE_END);
- // Can we load anything right away?
- CheckForFiles();
- }
- /**
- * Check if we have existing landmarks/waypints files in the current directory.
- */
- private void CheckForFiles()
- {
- File fTmpL = new File(".//landmarks.dat");
- File fTmpW = new File(".//waypoints.dat");
- // See if we can load a landmarks file.
- if (fTmpL.exists() && fTmpL.canRead() && fTmpL.isFile())
- {
- if (JOptionPane.showConfirmDialog(null,
- "A landmarks.dat file has been discovered. Would you like to load it?", "Question:",
- JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
- {
- ParseLandmarksFile(fTmpL);
- }
- }
- // See if we can load a waypoints file.
- if (fTmpW.exists() && fTmpW.canRead() && fTmpW.isFile())
- {
- if (JOptionPane.showConfirmDialog(null,
- "A waypoints.dat file has been discovered. Would you like to load it?", "Question:",
- JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
- {
- // Trig or not.
- if (JOptionPane.showConfirmDialog(null, "Trigonometry (yes) or non-trigonometry (no)?", "Question:",
- JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
- m_bUseTrig = true;
- else
- m_bUseTrig = false;
- // Load!
- ParseWaypointsFile(fTmpW);
- }
- }
- }
- /**
- * Load landmarks from a .dat file.
- */
- private void LoadLandmarks()
- {
- JFileChooser objFile = new JFileChooser();
- objFile.setAcceptAllFileFilterUsed(false);
- objFile.setDialogTitle("Choose Landmarks Data File");
- objFile.addChoosableFileFilter(new RobotRouteFileFilter());
- // Open the dialog.
- int iRes = objFile.showOpenDialog(this);
- if (iRes == JFileChooser.APPROVE_OPTION)
- ParseLandmarksFile(objFile.getSelectedFile());
- }
- /**
- * Load waypoints from a .dat file.
- */
- private void LoadWaypoints()
- {
- JFileChooser objFile = new JFileChooser();
- objFile.setAcceptAllFileFilterUsed(false);
- objFile.setDialogTitle("Choose Waypoints Data File");
- objFile.addChoosableFileFilter(new RobotRouteFileFilter());
- // Open the dialog.
- int iRes = objFile.showOpenDialog(this);
- if (iRes == JFileChooser.APPROVE_OPTION)
- {
- if (JOptionPane.showConfirmDialog(null,
- "Trigonometry (yes) or non-trigonometry (no)?",
- "Question:",
- JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
- m_bUseTrig = true;
- else
- m_bUseTrig = false;
- ParseWaypointsFile(objFile.getSelectedFile());
- }
- }
- /**
- * Parse the landmarks file.
- * @param objData File object.
- */
- private void ParseLandmarksFile(File objData)
- {
- BufferedReader objBuff = null;
- try
- {
- // Check file name.
- if (!objData.getName().equalsIgnoreCase("landmarks.dat"))
- throw new Exception("Invalid file name. Must be \"landmarks.dat\".");
- // Make sure we can read the file.
- if (objData.isFile() && objData.canRead())
- {
- // Read the file. Hopefully it contains landmarks!
- objBuff = new BufferedReader(new FileReader(objData));
- // Look for things we recognise.
- Pattern objPatn = Pattern.compile("(\\d{1,2})\\s+(\\d{1,2})\\s+(.+)");
- final ArrayList<Landmark> arrLM = new ArrayList<Landmark>();
- String strBuff;
- // Read line by line.
- while ((strBuff = objBuff.readLine()) != null)
- {
- Matcher objMatch = objPatn.matcher(strBuff);
- if (objMatch.find() && objMatch.groupCount() == 3)
- {
- String strX = objMatch.group(1);
- String strY = objMatch.group(2);
- String strName = objMatch.group(3);
- try
- {
- arrLM.add(new Landmark(
- Integer.parseInt(strX),
- Integer.parseInt(strY), strName
- ));
- }
- // Skip bad input.
- catch (NumberFormatException nfe)
- {
- ShowError("Invalid landmark detected - ignoring.");
- continue;
- }
- }
- }
- // Set landmarks.
- m_objRobot.setLandmarks(arrLM);
- m_objWorld.drawLandmarks(arrLM);
- }
- else
- throw new Exception("The selected file cannot be read.");
- }
- catch (Exception e)
- {
- ShowError(e.getMessage());
- }
- finally
- {
- try { if (objBuff != null) objBuff.close(); } catch (Exception e) {}
- }
- }
- /**
- * Load waypoints from a .dat file.
- */
- private void ParseWaypointsFile(File objData)
- {
- BufferedReader objBuff = null;
- try
- {
- // Check file name.
- if (!objData.getName().equalsIgnoreCase("waypoints.dat"))
- throw new Exception("Invalid file name. Must be \"waypoints.dat\".");
- // Make sure we can read the file.
- if (objData.isFile() && objData.canRead())
- {
- // Read the file. Hopefully it contains waypoints!
- objBuff = new BufferedReader(new FileReader(objData));
- // Look for things we understand.
- Pattern objPatn = Pattern.compile("(\\d{1,2})\\s+(\\d{1,2})");
- ArrayList<int[]> arrWP = new ArrayList<int[]>();
- String strBuff;
- // Read line by line.
- while ((strBuff = objBuff.readLine()) != null)
- {
- Matcher objMatch = objPatn.matcher(strBuff);
- if (objMatch.find() && objMatch.groupCount() == 2)
- {
- String strX = objMatch.group(1);
- String strY = objMatch.group(2);
- try
- {
- arrWP.add(new int[] {
- Integer.parseInt(strX),
- Integer.parseInt(strY)
- });
- }
- // Skip bad input.
- catch (NumberFormatException nfe)
- {
- ShowError("Invalid waypoint detected - ignoring.");
- continue;
- }
- }
- }
- // Get the robot to do its thing.
- m_objRobot.setWorld(m_objWorld);
- m_objRobot.setWaypoints(arrWP);
- m_objWorld.setRobot(m_objRobot);
- m_objWorld.drawRoute(arrWP, m_bUseTrig);
- // Need to draw route first (if using trig).
- m_objRobot.doFollowRoute(m_bUseTrig);
- // Set script.
- m_objScript.m_txtScript.setText(m_objRobot.getScriptAsString("\r\n"));
- }
- else
- throw new Exception("The selected file cannot be read.");
- }
- catch (Exception e)
- {
- ShowError(e.getMessage());
- }
- finally
- {
- try { if (objBuff != null) objBuff.close(); } catch (Exception e) {}
- }
- }
- /**
- * Show an error dialog.
- * @param strErr Error message.
- */
- private void ShowError(String strErr)
- {
- JOptionPane.showMessageDialog(this, strErr, "Error:",
- JOptionPane.ERROR_MESSAGE
- );
- }
- /**
- * Perform an action.
- */
- @Override
- public void actionPerformed(ActionEvent arg)
- {
- // Perform an action.
- if (arg.getActionCommand().equals("landmarks"))
- LoadLandmarks();
- // Load waypoints.
- else if (arg.getActionCommand().equals("waypoints"))
- LoadWaypoints();
- // Reset GUI.
- else if (arg.getActionCommand().equals("reset"))
- {
- m_objWorld.resetGUI();
- m_objRobot.resetRobot();
- m_objScript.setScript(m_objRobot.getScript());
- }
- // Script.
- else if (arg.getActionCommand().equals("script"))
- {
- m_objScript.setScript(m_objRobot.getScript());
- m_objScript.setVisible(true);
- }
- // Stats.
- else if (arg.getActionCommand().equals("stats"))
- {
- String strMsg = "Statistics:\n\n";
- if (m_bUseTrig)
- {
- // Landmarks.
- ArrayList<Landmark> arrLM = m_objRobot.getSeenLandmarksTrig();
- strMsg += "Landmarks:\n====================================\n";
- if (arrLM != null && arrLM.size() > 0)
- {
- for (Landmark objLM : arrLM)
- strMsg += "Saw \"" + objLM.getName() + "\" at (" + objLM.getX() + ", " + objLM.getY() + ")\n";
- }
- else
- strMsg += "Saw no landmarks.\n";
- // Distance.
- double dDistU = m_objRobot.getDistanceTravelled();
- double dDistP = m_objRobot.getDistanceTravelledInPixels();
- strMsg += "\nDistance:\n====================================\n";
- strMsg += "Distance Travelled: " + dDistU; // + " (" + dDistP + " pixels)";
- }
- else
- {
- // Landmarks.
- ArrayList<Landmark> arrLM = m_objRobot.getSeenLandmarks();
- strMsg += "Landmarks:\n====================================\n";
- if (arrLM != null && arrLM.size() > 0)
- {
- for (Landmark objLM : arrLM)
- strMsg += "Saw \"" + objLM.getName() + "\" at (" + objLM.getX() + ", " + objLM.getY() + ")\n";
- }
- else
- strMsg += "Saw no landmarks.\n";
- // Distance.
- int iDist = (int)m_objRobot.getDistanceTravelled();
- strMsg += "\nDistance:\n====================================\n";
- strMsg += "Distance Travelled: " + iDist;
- }
- JOptionPane.showMessageDialog(null, strMsg);
- }
- }
- }
Add Comment
Please, Sign In to add comment