Guest User

Untitled

a guest
Jul 20th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.04 KB | None | 0 0
  1. import java.awt.*;
  2. import java.awt.event.ActionEvent;
  3. import java.awt.event.ActionListener;
  4. import java.io.*;
  5. import java.util.ArrayList;
  6. import java.util.regex.*;
  7. import javax.swing.*;
  8.  
  9.  
  10. @SuppressWarnings("serial")
  11. public class RobotRouteFrame extends JFrame implements ActionListener
  12. {
  13. private RobotRouteWorld m_objWorld = null; // Draws everything.
  14. private RobotRouteScriptFrame m_objScript = null; // Script JFrame.
  15. private Robot m_objRobot = null; // Robot.
  16. private boolean m_bUseTrig = false; // Use trigonometry or not?
  17.  
  18. /**
  19. * Constructor.
  20. * @param strTitle Frame title.
  21. */
  22. public RobotRouteFrame(String strTitle)
  23. {
  24. super(strTitle);
  25. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  26.  
  27. // Objects.
  28. m_objRobot = new Robot();
  29. m_objWorld = new RobotRouteWorld();
  30. m_objScript = new RobotRouteScriptFrame("Script Output");
  31. m_objScript.pack();
  32.  
  33. // Associate the robot with the world.
  34. m_objWorld.setRobot(m_objRobot);
  35.  
  36. // Create layout.
  37. createComponents();
  38. }
  39.  
  40. /**
  41. * Create components and add to content pane.
  42. */
  43. public void createComponents()
  44. {
  45. JPanel objMainPanel = new JPanel(new GridLayout(1, 1));
  46. JPanel objBtnPanel = new JPanel(new GridLayout(1, 0));
  47.  
  48. // Create the buttons.
  49. JButton btnLandmarks = new JButton("Load Landmarks");
  50. JButton btnWaypoints = new JButton("Load Waypoints");
  51. JButton btnResetGUI = new JButton("Reset World");
  52. JButton btnViewScript = new JButton("View Script");
  53. JButton btnViewStats = new JButton("View Statistics");
  54.  
  55. // Set the actions.
  56. btnLandmarks.addActionListener(this);
  57. btnLandmarks.setActionCommand("landmarks");
  58. btnWaypoints.addActionListener(this);
  59. btnWaypoints.setActionCommand("waypoints");
  60. btnViewScript.addActionListener(this);
  61. btnViewScript.setActionCommand("script");
  62. btnViewStats.addActionListener(this);
  63. btnViewStats.setActionCommand("stats");
  64. btnResetGUI.addActionListener(this);
  65. btnResetGUI.setActionCommand("reset");
  66.  
  67. // Add the buttons to the panel.
  68. objBtnPanel.add(btnLandmarks);
  69. objBtnPanel.add(btnWaypoints);
  70. objBtnPanel.add(btnViewScript);
  71. objBtnPanel.add(btnViewStats);
  72. objBtnPanel.add(btnResetGUI);
  73.  
  74. // Add the World to the main panel.
  75. objMainPanel.add(m_objWorld);
  76.  
  77. // Add our main panel.
  78. getContentPane().add(objMainPanel, BorderLayout.CENTER);
  79. getContentPane().add(objBtnPanel, BorderLayout.PAGE_END);
  80.  
  81. // Can we load anything right away?
  82. CheckForFiles();
  83. }
  84.  
  85. /**
  86. * Check if we have existing landmarks/waypints files in the current directory.
  87. */
  88. private void CheckForFiles()
  89. {
  90. File fTmpL = new File(".//landmarks.dat");
  91. File fTmpW = new File(".//waypoints.dat");
  92.  
  93. // See if we can load a landmarks file.
  94. if (fTmpL.exists() && fTmpL.canRead() && fTmpL.isFile())
  95. {
  96. if (JOptionPane.showConfirmDialog(null,
  97. "A landmarks.dat file has been discovered. Would you like to load it?", "Question:",
  98. JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
  99. {
  100. ParseLandmarksFile(fTmpL);
  101. }
  102. }
  103.  
  104. // See if we can load a waypoints file.
  105. if (fTmpW.exists() && fTmpW.canRead() && fTmpW.isFile())
  106. {
  107. if (JOptionPane.showConfirmDialog(null,
  108. "A waypoints.dat file has been discovered. Would you like to load it?", "Question:",
  109. JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
  110. {
  111. // Trig or not.
  112. if (JOptionPane.showConfirmDialog(null, "Trigonometry (yes) or non-trigonometry (no)?", "Question:",
  113. JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
  114. m_bUseTrig = true;
  115. else
  116. m_bUseTrig = false;
  117.  
  118. // Load!
  119. ParseWaypointsFile(fTmpW);
  120. }
  121. }
  122. }
  123.  
  124. /**
  125. * Load landmarks from a .dat file.
  126. */
  127. private void LoadLandmarks()
  128. {
  129. JFileChooser objFile = new JFileChooser();
  130.  
  131. objFile.setAcceptAllFileFilterUsed(false);
  132. objFile.setDialogTitle("Choose Landmarks Data File");
  133. objFile.addChoosableFileFilter(new RobotRouteFileFilter());
  134.  
  135. // Open the dialog.
  136. int iRes = objFile.showOpenDialog(this);
  137. if (iRes == JFileChooser.APPROVE_OPTION)
  138. ParseLandmarksFile(objFile.getSelectedFile());
  139. }
  140.  
  141. /**
  142. * Load waypoints from a .dat file.
  143. */
  144. private void LoadWaypoints()
  145. {
  146. JFileChooser objFile = new JFileChooser();
  147.  
  148. objFile.setAcceptAllFileFilterUsed(false);
  149. objFile.setDialogTitle("Choose Waypoints Data File");
  150. objFile.addChoosableFileFilter(new RobotRouteFileFilter());
  151.  
  152. // Open the dialog.
  153. int iRes = objFile.showOpenDialog(this);
  154. if (iRes == JFileChooser.APPROVE_OPTION)
  155. {
  156. if (JOptionPane.showConfirmDialog(null,
  157. "Trigonometry (yes) or non-trigonometry (no)?",
  158. "Question:",
  159. JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
  160. m_bUseTrig = true;
  161. else
  162. m_bUseTrig = false;
  163. ParseWaypointsFile(objFile.getSelectedFile());
  164. }
  165. }
  166.  
  167. /**
  168. * Parse the landmarks file.
  169. * @param objData File object.
  170. */
  171. private void ParseLandmarksFile(File objData)
  172. {
  173. BufferedReader objBuff = null;
  174. try
  175. {
  176. // Check file name.
  177. if (!objData.getName().equalsIgnoreCase("landmarks.dat"))
  178. throw new Exception("Invalid file name. Must be \"landmarks.dat\".");
  179.  
  180. // Make sure we can read the file.
  181. if (objData.isFile() && objData.canRead())
  182. {
  183. // Read the file. Hopefully it contains landmarks!
  184. objBuff = new BufferedReader(new FileReader(objData));
  185.  
  186. // Look for things we recognise.
  187. Pattern objPatn = Pattern.compile("(\\d{1,2})\\s+(\\d{1,2})\\s+(.+)");
  188. final ArrayList<Landmark> arrLM = new ArrayList<Landmark>();
  189. String strBuff;
  190.  
  191. // Read line by line.
  192. while ((strBuff = objBuff.readLine()) != null)
  193. {
  194. Matcher objMatch = objPatn.matcher(strBuff);
  195. if (objMatch.find() && objMatch.groupCount() == 3)
  196. {
  197. String strX = objMatch.group(1);
  198. String strY = objMatch.group(2);
  199. String strName = objMatch.group(3);
  200.  
  201. try
  202. {
  203. arrLM.add(new Landmark(
  204. Integer.parseInt(strX),
  205. Integer.parseInt(strY), strName
  206. ));
  207. }
  208.  
  209. // Skip bad input.
  210. catch (NumberFormatException nfe)
  211. {
  212. ShowError("Invalid landmark detected - ignoring.");
  213. continue;
  214. }
  215. }
  216. }
  217.  
  218. // Set landmarks.
  219. m_objRobot.setLandmarks(arrLM);
  220. m_objWorld.drawLandmarks(arrLM);
  221. }
  222. else
  223. throw new Exception("The selected file cannot be read.");
  224. }
  225. catch (Exception e)
  226. {
  227. ShowError(e.getMessage());
  228. }
  229. finally
  230. {
  231. try { if (objBuff != null) objBuff.close(); } catch (Exception e) {}
  232. }
  233. }
  234.  
  235. /**
  236. * Load waypoints from a .dat file.
  237. */
  238. private void ParseWaypointsFile(File objData)
  239. {
  240. BufferedReader objBuff = null;
  241. try
  242. {
  243. // Check file name.
  244. if (!objData.getName().equalsIgnoreCase("waypoints.dat"))
  245. throw new Exception("Invalid file name. Must be \"waypoints.dat\".");
  246.  
  247. // Make sure we can read the file.
  248. if (objData.isFile() && objData.canRead())
  249. {
  250. // Read the file. Hopefully it contains waypoints!
  251. objBuff = new BufferedReader(new FileReader(objData));
  252.  
  253. // Look for things we understand.
  254. Pattern objPatn = Pattern.compile("(\\d{1,2})\\s+(\\d{1,2})");
  255. ArrayList<int[]> arrWP = new ArrayList<int[]>();
  256. String strBuff;
  257.  
  258. // Read line by line.
  259. while ((strBuff = objBuff.readLine()) != null)
  260. {
  261. Matcher objMatch = objPatn.matcher(strBuff);
  262. if (objMatch.find() && objMatch.groupCount() == 2)
  263. {
  264. String strX = objMatch.group(1);
  265. String strY = objMatch.group(2);
  266.  
  267. try
  268. {
  269. arrWP.add(new int[] {
  270. Integer.parseInt(strX),
  271. Integer.parseInt(strY)
  272. });
  273. }
  274.  
  275. // Skip bad input.
  276. catch (NumberFormatException nfe)
  277. {
  278. ShowError("Invalid waypoint detected - ignoring.");
  279. continue;
  280. }
  281. }
  282. }
  283.  
  284. // Get the robot to do its thing.
  285. m_objRobot.setWorld(m_objWorld);
  286. m_objRobot.setWaypoints(arrWP);
  287.  
  288. m_objWorld.setRobot(m_objRobot);
  289. m_objWorld.drawRoute(arrWP, m_bUseTrig);
  290.  
  291. // Need to draw route first (if using trig).
  292. m_objRobot.doFollowRoute(m_bUseTrig);
  293.  
  294. // Set script.
  295. m_objScript.m_txtScript.setText(m_objRobot.getScriptAsString("\r\n"));
  296. }
  297. else
  298. throw new Exception("The selected file cannot be read.");
  299. }
  300. catch (Exception e)
  301. {
  302. ShowError(e.getMessage());
  303. }
  304. finally
  305. {
  306. try { if (objBuff != null) objBuff.close(); } catch (Exception e) {}
  307. }
  308. }
  309.  
  310. /**
  311. * Show an error dialog.
  312. * @param strErr Error message.
  313. */
  314. private void ShowError(String strErr)
  315. {
  316. JOptionPane.showMessageDialog(this, strErr, "Error:",
  317. JOptionPane.ERROR_MESSAGE
  318. );
  319. }
  320.  
  321. /**
  322. * Perform an action.
  323. */
  324. @Override
  325. public void actionPerformed(ActionEvent arg)
  326. {
  327. // Perform an action.
  328. if (arg.getActionCommand().equals("landmarks"))
  329. LoadLandmarks();
  330.  
  331. // Load waypoints.
  332. else if (arg.getActionCommand().equals("waypoints"))
  333. LoadWaypoints();
  334.  
  335. // Reset GUI.
  336. else if (arg.getActionCommand().equals("reset"))
  337. {
  338. m_objWorld.resetGUI();
  339. m_objRobot.resetRobot();
  340. m_objScript.setScript(m_objRobot.getScript());
  341. }
  342.  
  343. // Script.
  344. else if (arg.getActionCommand().equals("script"))
  345. {
  346. m_objScript.setScript(m_objRobot.getScript());
  347. m_objScript.setVisible(true);
  348. }
  349.  
  350. // Stats.
  351. else if (arg.getActionCommand().equals("stats"))
  352. {
  353. String strMsg = "Statistics:\n\n";
  354. if (m_bUseTrig)
  355. {
  356. // Landmarks.
  357. ArrayList<Landmark> arrLM = m_objRobot.getSeenLandmarksTrig();
  358.  
  359. strMsg += "Landmarks:\n====================================\n";
  360. if (arrLM != null && arrLM.size() > 0)
  361. {
  362. for (Landmark objLM : arrLM)
  363. strMsg += "Saw \"" + objLM.getName() + "\" at (" + objLM.getX() + ", " + objLM.getY() + ")\n";
  364. }
  365. else
  366. strMsg += "Saw no landmarks.\n";
  367.  
  368. // Distance.
  369. double dDistU = m_objRobot.getDistanceTravelled();
  370. double dDistP = m_objRobot.getDistanceTravelledInPixels();
  371. strMsg += "\nDistance:\n====================================\n";
  372. strMsg += "Distance Travelled: " + dDistU; // + " (" + dDistP + " pixels)";
  373. }
  374. else
  375. {
  376. // Landmarks.
  377. ArrayList<Landmark> arrLM = m_objRobot.getSeenLandmarks();
  378.  
  379. strMsg += "Landmarks:\n====================================\n";
  380. if (arrLM != null && arrLM.size() > 0)
  381. {
  382. for (Landmark objLM : arrLM)
  383. strMsg += "Saw \"" + objLM.getName() + "\" at (" + objLM.getX() + ", " + objLM.getY() + ")\n";
  384. }
  385. else
  386. strMsg += "Saw no landmarks.\n";
  387.  
  388. // Distance.
  389. int iDist = (int)m_objRobot.getDistanceTravelled();
  390. strMsg += "\nDistance:\n====================================\n";
  391. strMsg += "Distance Travelled: " + iDist;
  392. }
  393. JOptionPane.showMessageDialog(null, strMsg);
  394. }
  395. }
  396. }
Add Comment
Please, Sign In to add comment