import java.io.*; // For BufferedWriter public class WolfDeerSimulation { /* Linked lists for tracking wolves and deer */ private AgentNode wolves; private AgentNode deer; /** Accessors for wolves and deer */ public AgentNode getWolves(){return wolves;} public AgentNode getDeer(){return deer;} /* A BufferedWriter for writing to */ public BufferedWriter output; /** * Constructor to set output to null **/ public WolfDeerSimulation() { output = null; } /** * Open the input file and set the BufferedWriter to speak to it. **/ public void openFile(String filename){ // Try to open the file try { // create a writer output = new BufferedWriter(new FileWriter(filename)); } catch (Exception ex) { System.out.println("Trouble opening the file " + filename); // If any problem, make it null again output = null; } } public void run() { World w = new World(); w.setAutoRepaint(false); // Start the lists wolves = new AgentNode(); deer = new AgentNode(); // create some deer int numDeer = 20; for (int i = 0; i < numDeer; i++) { deer.add(new AgentNode(new Deer(w,this))); } // create some wolves int numWolves = 5; for (int i = 0; i < numWolves; i++) { wolves.add(new AgentNode(new Wolf(w,this))); } // declare a wolf and deer Wolf currentWolf = null; Deer currentDeer = null; AgentNode currentNode = null; // loop for a set number of timesteps (50 here) for (int t = 0; t < 50; t++) { // loop through all the wolves currentNode = (AgentNode) wolves.getNext(); while (currentNode != null) { currentWolf = (Wolf) currentNode.getAgent(); currentWolf.act(); currentNode = (AgentNode) currentNode.getNext(); } // loop through all the deer currentNode = (AgentNode) deer.getNext(); while (currentNode != null) { currentDeer = (Deer) currentNode.getAgent(); currentDeer.act(); currentNode = (AgentNode) currentNode.getNext(); } // repaint the world to show the movement w.repaint(); // Let's figure out where we stand... System.out.println(">>> Timestep: "+t); System.out.println("Wolves left: "+wolves.getNext().count()); System.out.println("Deer left: "+deer.getNext().count()); // If we have an open file, write the counts to it if (output != null) { // Try it try{ output.write(wolves.getNext().count()+"\t"+deer.getNext().count()); output.newLine(); } catch (Exception ex) { System.out.println("Couldn't write the data!"); System.out.println(ex.getMessage()); // Make output null so that we don't keep trying output = null; } } // Wait for one second //Thread.sleep(1000); } // If we have an open file, close it and null the variable if (output != null){ try{ output.close();} catch (Exception ex) {System.out.println("Something went wrong closing the file");} finally { // No matter what, mark the file as not-there output = null;} } } }