/* * file name: Project3Tester.java * purpose: Guided tester for CS231 Project 3 (Agent-Based Simulation). * * How to run (no -ea flag needed): * javac *.java * java Project3Tester runs the tasks in order and stops at the * first task that still needs work * java Project3Tester 5 runs only Task 5 * * You do not need to edit this file. It will not crash if your code throws * an exception or gets stuck in a loop - it reports what happened and where. */ import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class Project3Tester { private static final long DEFAULT_TIME_LIMIT_MS = 5000; private static List buildTasks() { List tasks = new ArrayList<>(); tasks.add(new Task(1, "LinkedList: addLast() and indexOf()", DEFAULT_TIME_LIMIT_MS, Project3Tester::task1)); tasks.add(new Task(2, "The abstract Agent class", DEFAULT_TIME_LIMIT_MS, Project3Tester::task2)); tasks.add(new Task(3, "SocialAgent and AntiSocialAgent (inheritance)", DEFAULT_TIME_LIMIT_MS, Project3Tester::task3)); tasks.add(new Task(4, "Landscape basics", DEFAULT_TIME_LIMIT_MS, Project3Tester::task4)); tasks.add(new Task(5, "Landscape: getNeighbors(), removeAgent(), counting", DEFAULT_TIME_LIMIT_MS, Project3Tester::task5)); tasks.add(new Task(6, "moveRandomly() and updateState()", DEFAULT_TIME_LIMIT_MS, Project3Tester::task6)); tasks.add(new Task(7, "Landscape.updateAgents()", DEFAULT_TIME_LIMIT_MS, Project3Tester::task7)); tasks.add(new Task(8, "AgentSimulation.runExpt()", 120000, Project3Tester::task8)); return tasks; } // ------------------------------------------------------------------ // TASK 1 - LinkedList additions // ------------------------------------------------------------------ private static void task1() throws Throwable { // A quick reminder check that the Lab 3 list still works. boolean labOk; try { LinkedList lab = new LinkedList(); lab.add(2); lab.add(1); lab.add(2, 3); int total = 0; for (Integer v : lab) { total += v; } labOk = lab.size() == 3 && Objects.equals(1, lab.get(0)) && total == 6; } catch (Exception e) { labOk = false; } check("Lab 3 methods still work (add, add(index), size, get, iterator)", labOk, "Your Lab 3 LinkedList is not finished yet. Copy your finished LinkedList.java\n" + "into this folder, or run java LinkedListTester and finish the lab first."); if (!labOk) { return; } LinkedList list = new LinkedList(); list.addLast("a"); checkEquals("addLast(\"a\") on an empty list: toString()", "[a]", list.toString(), "On an empty list there is no last Node to attach to. Which method handles an empty list?"); checkEquals("addLast(\"a\") on an empty list: size()", 1, list.size(), "addLast must increase size."); list.addLast("b"); list.addLast("c"); checkEquals("then addLast(\"b\"), addLast(\"c\"): toString()", "[a, b, c]", list.toString(), "Walk until you reach the Node whose next is null, then attach the new Node there."); checkEquals("size() after three addLast calls", 3, list.size(), ""); list.add("front"); list.addLast("end"); checkEquals("then add(\"front\"), addLast(\"end\")", "[front, a, b, c, end]", list.toString(), "add() and addLast() must work together."); checkEquals("get(4) is the item added last", "end", list.get(4), ""); LinkedList dup = new LinkedList(); dup.addLast("A"); dup.addLast("B"); dup.addLast("C"); dup.addLast("B"); checkEquals("[A, B, C, B].indexOf(\"A\")", 0, dup.indexOf("A"), "The head is at index 0."); checkEquals("[A, B, C, B].indexOf(\"B\") (first match)", 1, dup.indexOf("B"), "Return as soon as you find the FIRST match."); checkEquals("[A, B, C, B].indexOf(\"C\")", 2, dup.indexOf("C"), "Count positions as you walk: the head is 0, the next Node is 1, ..."); checkEquals("[A, B, C, B].indexOf(\"Z\")", -1, dup.indexOf("Z"), "Return -1 only after checking every Node."); checkEquals("[A, B, C, B].indexOf(new String(\"C\"))", 2, dup.indexOf(new String("C")), "Compare with item.equals(o), not ==."); checkEquals("empty list .indexOf(\"A\")", -1, new LinkedList().indexOf("A"), ""); } // ------------------------------------------------------------------ // TASK 2 - Agent // ------------------------------------------------------------------ private static void task2() throws Throwable { check("Agent is declared abstract", Modifier.isAbstract(Agent.class.getModifiers()), "public abstract class Agent"); Method upd = Agent.class.getDeclaredMethod("updateState", Landscape.class); Method drw = Agent.class.getDeclaredMethod("draw", Graphics.class); check("updateState(Landscape) is abstract in Agent", Modifier.isAbstract(upd.getModifiers()), "public abstract void updateState(Landscape scape); (no body - just a semicolon)"); check("draw(Graphics) is abstract in Agent", Modifier.isAbstract(drw.getModifiers()), ""); Field radius = findField(Agent.class, "radius"); Field moved = findField(Agent.class, "moved"); check("Agent has an int field named radius", radius != null && radius.getType() == int.class, "Declare it in Agent: protected int radius;"); check("Agent has a boolean field named moved", moved != null && moved.getType() == boolean.class, "Declare it in Agent: protected boolean moved;"); if (radius != null) { check("radius is protected", Modifier.isProtected(radius.getModifiers()), "Subclasses need to read radius directly, so it must be protected."); } if (moved != null) { check("moved is protected", Modifier.isProtected(moved.getModifiers()), "Subclasses set moved in updateState() and read it in draw(), so it must be protected."); } int privateDoubles = 0; boolean anyStaticInstanceData = false; boolean anyPublic = false; for (Field f : Agent.class.getDeclaredFields()) { int m = f.getModifiers(); if (f.getType() == double.class && Modifier.isPrivate(m) && !Modifier.isStatic(m)) { privateDoubles++; } if (Modifier.isStatic(m) && !f.getType().getName().equals("java.util.Random")) { anyStaticInstanceData = true; } if (Modifier.isPublic(m)) { anyPublic = true; } } check("the x and y position are private double fields", privateDoubles >= 2, "Declare them in Agent: private double x; private double y;"); check("no position/radius/moved field is static", !anyStaticInstanceData, "A static field is shared by EVERY Agent. Each Agent needs its own x, y, radius and moved."); check("no fields are public", !anyPublic, ""); Agent a = new SocialAgent(3.0244, 4.2451, 25); checkEquals("new SocialAgent(3.0244, 4.2451, 25).getX()", 3.0244, a.getX(), "The Agent constructor must store x0 in x."); checkEquals("getY()", 4.2451, a.getY(), "The Agent constructor must store y0 in y."); checkEquals("getRadius()", 25, a.getRadius(), "The Agent constructor must store radius."); checkEquals("getMoved() of a brand-new agent", false, a.getMoved(), "A new agent has not moved yet."); checkEquals("toString()", "(3.024, 4.245)", a.toString(), "Use String.format(\"(%.3f, %.3f)\", x, y)"); a.setX(12.5); a.setY(7.25); a.setRadius(40); checkEquals("after setX(12.5): getX()", 12.5, a.getX(), ""); checkEquals("after setY(7.25): getY()", 7.25, a.getY(), ""); checkEquals("after setRadius(40): getRadius()", 40, a.getRadius(), ""); Agent b = new SocialAgent(1.0, 2.0, 5); checkEquals("creating a second agent does not change the first: getX()", 12.5, a.getX(), "If this changed, your fields are probably static (shared by all agents)."); checkEquals("second agent getX()", 1.0, b.getX(), ""); } // ------------------------------------------------------------------ // TASK 3 - Subclasses // ------------------------------------------------------------------ private static void task3() throws Throwable { check("SocialAgent extends Agent", SocialAgent.class.getSuperclass() == Agent.class, "public class SocialAgent extends Agent"); check("AntiSocialAgent extends Agent", AntiSocialAgent.class.getSuperclass() == Agent.class, "public class AntiSocialAgent extends Agent"); for (Class sub : new Class[] { SocialAgent.class, AntiSocialAgent.class }) { String shadowed = ""; for (String name : new String[] { "x", "y", "radius", "moved" }) { if (findDeclaredField(sub, name) != null) { shadowed += name + " "; } } check(sub.getName() + " does not redeclare x, y, radius or moved", shadowed.isEmpty(), "Remove these fields from " + sub.getName() + ": " + shadowed + "\n" + "They are inherited from Agent. Redeclaring one creates a second variable\n" + "that hides the inherited one, so Agent's methods and yours see different values."); } Agent anti = new AntiSocialAgent(7.5, 8.5, 50); checkEquals("new AntiSocialAgent(7.5, 8.5, 50).getX()", 7.5, anti.getX(), "Pass the constructor's parameters on to super(...)."); checkEquals("getY()", 8.5, anti.getY(), ""); checkEquals("getRadius()", 50, anti.getRadius(), ""); checkEquals("getMoved()", false, anti.getMoved(), ""); LinkedList mixed = new LinkedList(); mixed.add(new SocialAgent(1, 1, 5)); mixed.add(new AntiSocialAgent(2, 2, 5)); mixed.add(new SocialAgent(3, 3, 5)); int social = 0; int antisocial = 0; for (Agent ag : mixed) { if (ag instanceof SocialAgent) { social++; } if (ag instanceof AntiSocialAgent) { antisocial++; } } checkEquals("one LinkedList holds both kinds (social, antisocial)", "2, 1", social + ", " + antisocial, "Because both classes extend Agent, a LinkedList can hold either kind."); checkEquals("SocialAgent.draw() color when moved == false", new Color(0, 0, 255), drawnColor(new SocialAgent(5, 5, 5), false), "Copy the draw() code from the Project 3 page into SocialAgent."); checkEquals("SocialAgent.draw() color when moved == true", new Color(125, 125, 255), drawnColor(new SocialAgent(5, 5, 5), true), "draw() should read the inherited, protected moved field."); checkEquals("AntiSocialAgent.draw() color when moved == false", new Color(255, 0, 0), drawnColor(new AntiSocialAgent(5, 5, 5), false), "Write draw() in AntiSocialAgent using red instead of blue."); checkEquals("AntiSocialAgent.draw() color when moved == true", new Color(255, 125, 125), drawnColor(new AntiSocialAgent(5, 5, 5), true), ""); } // ------------------------------------------------------------------ // TASK 4 - Landscape basics // ------------------------------------------------------------------ private static void task4() throws Throwable { boolean hasLinkedListField = false; boolean hasOtherCollection = false; for (Field f : Landscape.class.getDeclaredFields()) { if (f.getType() == LinkedList.class) { hasLinkedListField = true; } if (f.getType().isArray() || java.util.Collection.class.isAssignableFrom(f.getType())) { hasOtherCollection = true; } } check("Landscape stores its agents in a field of type LinkedList (yours)", hasLinkedListField, "private LinkedList agents; (do not import java.util.LinkedList)"); check("Landscape does not use an array or java.util collection for agents", !hasOtherCollection, "This project exercises YOUR LinkedList - store the agents there."); Landscape scape = new Landscape(100, 200); checkEquals("new Landscape(100, 200).getWidth()", 100, scape.getWidth(), ""); checkEquals("getHeight()", 200, scape.getHeight(), "Check that width and height are not swapped."); check("getAgents() is not null for a new Landscape", scape.getAgents() != null, "The constructor must create the list: agents = new LinkedList();"); if (scape.getAgents() == null) { return; } checkEquals("a new Landscape holds this many agents", 0, scape.getAgents().size(), ""); Agent first = new SocialAgent(10, 10, 5); Agent second = new AntiSocialAgent(20, 20, 5); Agent third = new SocialAgent(30, 30, 5); scape.addAgent(first); scape.addAgent(second); scape.addAgent(third); checkEquals("after adding 3 agents: getAgents().size()", 3, scape.getAgents().size(), "addAgent should add to the Landscape's list."); check("addAgent inserts at the BEGINNING (the last agent added is at index 0)", scape.getAgents().get(0) == third && scape.getAgents().get(2) == first, "Use the LinkedList method that inserts at the head: add(item)."); check("getAgents() returns the Landscape's own list (same object each call)", scape.getAgents() == scape.getAgents(), "Return the field itself, not a new list."); String text = scape.toString(); check("toString() mentions the number of agents (3)", text != null && text.contains("3"), "For example: \"Landscape 100x200 with 3 agents (2 social, 1 antisocial)\""); Landscape small = new Landscape(30, 30); small.addAgent(new SocialAgent(10, 10, 5)); BufferedImage img = new BufferedImage(30, 30, BufferedImage.TYPE_INT_RGB); Graphics g = img.getGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, 30, 30); small.draw(g); g.dispose(); checkEquals("Landscape.draw() draws its agents (pixel color at the agent)", new Color(0, 0, 255), new Color(img.getRGB(12, 12)), "draw(g) should loop over the agents and call each agent's draw(g)."); } // ------------------------------------------------------------------ // TASK 5 - getNeighbors, removeAgent, counting // ------------------------------------------------------------------ private static void task5() throws Throwable { Landscape scape = new Landscape(100, 100); Agent a1 = new SocialAgent(10, 10, 5); // the center Agent a2 = new SocialAgent(13, 14, 5); // distance exactly 5 Agent a3 = new AntiSocialAgent(10, 20, 5); // distance 10 Agent a4 = new SocialAgent(50, 50, 5); // far away Agent a5 = new AntiSocialAgent(10, 15, 5); // distance exactly 5 scape.addAgent(a1); scape.addAgent(a2); scape.addAgent(a3); scape.addAgent(a4); scape.addAgent(a5); // Landscape list order: a5, a4, a3, a2, a1 LinkedList near = scape.getNeighbors(10, 10, 5); check("getNeighbors returns a list (not null)", near != null, ""); if (near == null) { return; } checkEquals("getNeighbors(10, 10, 5): how many agents", 3, near.size(), "Agents at distance exactly 5 count (use <=). Agents at distance 10 do not.\n" + "The agent at (10, 10) itself is at distance 0, so it counts too."); checkEquals("which agents (in order)", "a5 a2 a1", names(near, a1, a2, a3, a4, a5), "Keep the Landscape's order. add(item) reverses the order; addLast(item) keeps it."); check("getNeighbors returns a NEW list, not the Landscape's own list", near != scape.getAgents(), "Create a new LinkedList inside getNeighbors and fill it."); checkEquals("the Landscape still holds 5 agents after getNeighbors", 5, scape.getAgents().size(), "getNeighbors must not change the Landscape's list."); checkEquals("getNeighbors(50, 50, 0)", "a4", names(scape.getNeighbors(50, 50, 0), a1, a2, a3, a4, a5), ""); checkEquals("getNeighbors(90, 90, 3) (nobody nearby): size()", 0, scape.getNeighbors(90, 90, 3).size(), ""); checkEquals("getNeighbors(10, 10, 100) finds everyone, in order", "a5 a4 a3 a2 a1", names(scape.getNeighbors(10, 10, 100), a1, a2, a3, a4, a5), ""); checkEquals("countSocialAgents() on (a5 anti, a4, a3 anti, a2, a1)", 3, scape.countSocialAgents(), "Loop over the agents and use instanceof SocialAgent."); checkEquals("countAntiSocialAgents()", 2, scape.countAntiSocialAgents(), ""); checkEquals("removeAgent(a3) (in the middle) returns", true, scape.removeAgent(a3), "Find the position with indexOf(a), then remove(position)."); checkEquals("then the list is", "a5 a4 a2 a1", names(scape.getAgents(), a1, a2, a3, a4, a5), ""); checkEquals("removeAgent(a3) again returns", false, scape.removeAgent(a3), "indexOf returns -1 when the agent is not there. Do not call remove(-1)!"); checkEquals("removeAgent(a5) (the head) returns", true, scape.removeAgent(a5), ""); checkEquals("removeAgent(a1) (the last agent) returns", true, scape.removeAgent(a1), ""); checkEquals("then the list is", "a4 a2", names(scape.getAgents(), a1, a2, a3, a4, a5), ""); Agent lookalike = new SocialAgent(13, 14, 5); // same position as a2, but a different agent checkEquals("removeAgent(a different agent at a2's position) returns", false, scape.removeAgent(lookalike), "Only the exact agent object should be removed."); checkEquals("counts after removals (social, antisocial)", "2, 0", scape.countSocialAgents() + ", " + scape.countAntiSocialAgents(), ""); } // ------------------------------------------------------------------ // TASK 6 - moveRandomly and updateState // ------------------------------------------------------------------ private static void task6() throws Throwable { // --- moveRandomly --- Landscape big = new Landscape(1000, 1000); Agent walker = new SocialAgent(500, 500, 5); big.addAgent(walker); boolean stepsOk = true; boolean sawNegX = false, sawPosX = false, sawNegY = false, sawPosY = false; double worst = 0; for (int i = 0; i < 300; i++) { double oldX = walker.getX(); double oldY = walker.getY(); walker.moveRandomly(big); double dx = walker.getX() - oldX; double dy = walker.getY() - oldY; worst = Math.max(worst, Math.max(Math.abs(dx), Math.abs(dy))); if (Math.abs(dx) > 10 || Math.abs(dy) > 10) { stepsOk = false; } sawNegX |= dx < 0; sawPosX |= dx > 0; sawNegY |= dy < 0; sawPosY |= dy > 0; } check("moveRandomly() changes x and y by at most 10 each (largest step seen: " + String.format("%.2f", worst) + ")", stepsOk, "gen.nextDouble() * 20 - 10 gives a value between -10 and 10."); check("moveRandomly() moves left AND right, up AND down", sawNegX && sawPosX && sawNegY && sawPosY, "The change must be able to be negative or positive, in both x and y."); Landscape box = new Landscape(100, 100); Agent cornerLow = new SocialAgent(0, 0, 5); Agent cornerHigh = new SocialAgent(100, 100, 5); boolean inside = true; for (int i = 0; i < 300; i++) { cornerLow.moveRandomly(box); cornerHigh.moveRandomly(box); for (Agent c : new Agent[] { cornerLow, cornerHigh }) { if (c.getX() < 0 || c.getX() > 100 || c.getY() < 0 || c.getY() > 100) { inside = false; } } } check("moveRandomly() keeps agents inside 0..width and 0..height", inside, "Clamp: x = Math.max(0, Math.min(scape.getWidth(), newX)); (same idea for y)"); // --- SocialAgent.updateState --- checkSocial("alone", 0, 4, true, "Alone, the neighbor list holds only the agent itself (1 < 4), so it moves."); checkSocial("with 2 other agents nearby (3 in the list)", 2, 4, true, "3 agents in the list is fewer than 4, so it moves."); checkSocial("with 3 other agents nearby (4 in the list)", 3, 4, false, "4 agents in the list is NOT fewer than 4, so it stays. Use < 4, not <= 4."); checkSocial("with 4 other agents nearby (5 in the list)", 4, 4, false, ""); checkSocial("with 3 other agents just OUTSIDE its radius", 3, 6, true, "Only agents within the agent's own radius count. Use getNeighbors(getX(), getY(), radius)."); Landscape s = new Landscape(100, 100); Agent mover = new SocialAgent(50, 50, 5); s.addAgent(mover); mover.updateState(s); // alone: moves double px = mover.getX(), py = mover.getY(); s.addAgent(new SocialAgent(px + 1, py, 5)); s.addAgent(new SocialAgent(px, py + 1, 5)); s.addAgent(new SocialAgent(px - 1, py, 5)); mover.updateState(s); // now crowded: stays checkEquals("SocialAgent that moved last step, now in a crowd: getMoved()", false, mover.getMoved(), "Set moved to false when the agent does not move - every time, not just at creation."); // --- AntiSocialAgent.updateState --- checkAnti("alone", 0, 5, 5, false, "Alone, the list holds only the agent itself (1 is not > 1), so it stays."); checkAnti("with 1 other agent nearby", 1, 5, 4, true, "2 agents in the list is more than 1, so it moves."); checkAnti("with 1 other agent just OUTSIDE its radius", 1, 5, 6, false, ""); checkAnti("radius 10, with 1 other agent at distance 8", 1, 10, 8, true, "Use the agent's own radius field, not a fixed number."); } private static void checkSocial(String situation, int others, double distance, boolean shouldMove, String hint) { Landscape scape = new Landscape(100, 100); Agent a1 = new SocialAgent(50, 50, 5); scape.addAgent(a1); addRing(scape, 50, 50, others, distance); a1.updateState(scape); reportMove("SocialAgent (radius 5) " + situation, a1, shouldMove, hint); } private static void checkAnti(String situation, int others, int radius, double distance, boolean shouldMove, String hint) { Landscape scape = new Landscape(100, 100); Agent a1 = new AntiSocialAgent(50, 50, radius); scape.addAgent(a1); addRing(scape, 50, 50, others, distance); a1.updateState(scape); reportMove("AntiSocialAgent " + situation, a1, shouldMove, hint); } private static void addRing(Landscape scape, double cx, double cy, int count, double distance) { for (int i = 0; i < count; i++) { double angle = 2 * Math.PI * i / Math.max(count, 1); double x = cx + distance * Math.cos(angle); double y = cy + distance * Math.sin(angle); scape.addAgent(new SocialAgent(x, y, 5)); } } private static void reportMove(String situation, Agent a, boolean shouldMove, String hint) { boolean positionChanged = a.getX() != 50 || a.getY() != 50; String expected = shouldMove ? "moves, getMoved() == true" : "stays at (50, 50), getMoved() == false"; String actual = (positionChanged ? "moved to " + a : "stayed at (50, 50)") + ", getMoved() == " + a.getMoved(); boolean ok = shouldMove ? (positionChanged && a.getMoved()) : (!positionChanged && !a.getMoved()); if (ok) { passed++; System.out.println(" [PASS] " + situation + " -> " + (shouldMove ? "moves" : "stays")); } else { failed++; System.out.println(" [FAIL] " + situation); System.out.println(" expected: " + expected); System.out.println(" got: " + actual); printHint(hint); } } // ------------------------------------------------------------------ // TASK 7 - updateAgents // ------------------------------------------------------------------ private static void task7() throws Throwable { checkEquals("updateAgents() on an empty Landscape returns", 0, new Landscape(100, 100).updateAgents(), "If there are no agents, return 0 right away."); Landscape one = new Landscape(100, 100); one.addAgent(new SocialAgent(50, 50, 5)); one.updateAgents(); checkEquals("one SocialAgent, after updateAgents(): (agents, social, antisocial)", "1, 0, 1", one.getAgents().size() + ", " + one.countSocialAgents() + ", " + one.countAntiSocialAgents(), "The random index must be able to be ANY index from 0 to size()-1.\n" + "gen.nextInt(agents.size()) does that; gen.nextInt(agents.size() - 1) does not."); // Ten SocialAgents spread far apart, each with radius 7. Landscape scape = new Landscape(1000, 1000); double[][] spots = new double[10][]; for (int i = 0; i < 10; i++) { spots[i] = new double[] { 50 + 100 * i, 50 + 90 * i }; scape.addAgent(new SocialAgent(spots[i][0], spots[i][1], 7)); } int movedReported = scape.updateAgents(); LinkedList agents = scape.getAgents(); checkEquals("10 agents, after one updateAgents(): number of agents", 10, agents.size(), "One agent is removed and one is added, so the size stays the same."); checkEquals("(social, antisocial)", "9, 1", scape.countSocialAgents() + ", " + scape.countAntiSocialAgents(), "Remove one agent with remove(index) and add one new AntiSocialAgent."); Agent head = agents.get(0); check("the new AntiSocialAgent is at the head of the list", head instanceof AntiSocialAgent, "Add the new agent with addAgent(), which inserts at the beginning."); checkEquals("the new AntiSocialAgent copied the removed agent's radius", 7, head.getRadius(), "new AntiSocialAgent(old.getX(), old.getY(), old.getRadius())"); boolean copiedSpot = false; for (double[] spot : spots) { if (spot[0] == head.getX() && spot[1] == head.getY()) { copiedSpot = true; } } check("the new AntiSocialAgent took the removed agent's position", copiedSpot, "Save the removed agent's x and y before creating the new agent."); int actuallyMoved = 0; for (Agent a : agents) { if (a.getMoved()) { actuallyMoved++; } } checkEquals("the value returned equals the number of agents with getMoved() == true", actuallyMoved, movedReported, "Count the agents whose getMoved() is true AFTER calling updateState on them."); checkEquals("number of agents that moved (9 lonely SocialAgents move; the lone AntiSocialAgent stays)", 9, movedReported, "Every agent must get its updateState(this) called once."); Landscape many = new Landscape(5000, 5000); for (int i = 0; i < 40; i++) { many.addAgent(new SocialAgent(100 + 120 * i, 100 + 120 * i, 5)); } for (int i = 0; i < 40; i++) { many.updateAgents(); } int converted = many.countAntiSocialAgents(); check("after 40 updates on 40 agents, many different agents were replaced (" + converted + " AntiSocialAgents)", converted >= 12, "Pick a NEW random index on every call to updateAgents(), from all positions in the list."); } // ------------------------------------------------------------------ // TASK 8 - runExpt // ------------------------------------------------------------------ private static void task8() throws Throwable { int zero = AgentSimulation.runExpt(0, false); check("runExpt(0, false) runs without crashing and returns 0 or 1 (got " + zero + ")", zero == 0 || zero == 1, "With no agents, nobody moves, so the loop should stop right away."); System.out.println(" (running 20 simulations with N = 50 ...)"); int avg50 = average(50, 20); checkRange("average iterations for N = 50 over 20 runs", avg50, 160, 330); System.out.println(" (running 10 simulations with N = 100 ...)"); int avg100 = average(100, 10); checkRange("average iterations for N = 100 over 10 runs", avg100, 380, 660); System.out.println(" (running 1 simulation with N = 250 ... this can take several seconds)"); int big = AgentSimulation.runExpt(250, false); checkEquals("runExpt(250, false) (crowded: should hit the 5000-iteration limit)", 5000, big, "The loop must stop after exactly 5000 iterations: use iterations < 5000."); } private static int average(int n, int trials) throws InterruptedException { long sum = 0; for (int i = 0; i < trials; i++) { sum += AgentSimulation.runExpt(n, false); } return (int) (sum / trials); } private static void checkRange(String description, int value, int low, int high) { boolean ok = value >= low && value <= high; if (ok) { passed++; System.out.println(" [PASS] " + description + " -> " + value); } else { failed++; System.out.println(" [FAIL] " + description); System.out.println(" expected: between " + low + " and " + high); System.out.println(" got: " + value); printHint("Check: a 500 x 500 Landscape, N SocialAgents with radius 25 at random positions,\n" + "a loop that continues while agents moved AND iterations < 5000, and that you\n" + "return the iteration count. If Tasks 6 and 7 pass, compare runExpt to the page."); } } // ================================================================== // Helpers for the tasks // ================================================================== private static String names(LinkedList list, Agent a1, Agent a2, Agent a3, Agent a4, Agent a5) { if (list == null) { return "null"; } StringBuilder sb = new StringBuilder(); int guard = 0; for (Agent a : list) { if (guard++ > 20) { break; } String n = a == a1 ? "a1" : a == a2 ? "a2" : a == a3 ? "a3" : a == a4 ? "a4" : a == a5 ? "a5" : "?"; if (sb.length() > 0) { sb.append(' '); } sb.append(n); } return sb.toString(); } private static Color drawnColor(Agent a, boolean moved) throws Exception { Field f = findField(Agent.class, "moved"); if (f == null) { return null; } f.setAccessible(true); f.setBoolean(a, moved); BufferedImage img = new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB); Graphics g = img.getGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, 20, 20); a.draw(g); g.dispose(); return new Color(img.getRGB(7, 7)); } private static Field findField(Class start, String name) { for (Class c = start; c != null; c = c.getSuperclass()) { Field f = findDeclaredField(c, name); if (f != null) { return f; } } return null; } private static Field findDeclaredField(Class c, String name) { for (Field f : c.getDeclaredFields()) { if (f.getName().equals(name)) { return f; } } return null; } // ================================================================== // Tester machinery - you do not need to read below this line. // ================================================================== @FunctionalInterface private interface TaskBody { void run() throws Throwable; } private static class Task { final int number; final String title; final long timeLimitMs; final TaskBody body; Task(int number, String title, long timeLimitMs, TaskBody body) { this.number = number; this.title = title; this.timeLimitMs = timeLimitMs; this.body = body; } } private enum Result { PASS, FAIL, CRASH, TIMEOUT } private static int passed; private static int failed; private static void check(String description, boolean ok, String hint) { if (ok) { passed++; System.out.println(" [PASS] " + description); } else { failed++; System.out.println(" [FAIL] " + description); printHint(hint); } } private static void checkEquals(String description, Object expected, Object actual, String hint) { if (Objects.equals(expected, actual)) { passed++; System.out.println(" [PASS] " + description + " -> " + show(actual)); } else { failed++; System.out.println(" [FAIL] " + description); System.out.println(" expected: " + show(expected)); System.out.println(" got: " + show(actual)); printHint(hint); } } private static String show(Object o) { if (o instanceof String) { return "\"" + o + "\""; } if (o instanceof Color) { Color c = (Color) o; return "Color(" + c.getRed() + ", " + c.getGreen() + ", " + c.getBlue() + ")"; } return String.valueOf(o); } private static void printHint(String hint) { if (hint == null || hint.isEmpty()) { return; } String[] lines = hint.split("\n"); System.out.println(" hint: " + lines[0]); for (int i = 1; i < lines.length; i++) { System.out.println(" " + lines[i]); } } private static boolean isStudentFrame(StackTraceElement e) { String c = e.getClassName(); int dollar = c.indexOf('$'); String outer = dollar >= 0 ? c.substring(0, dollar) : c; return outer.equals("LinkedList") || outer.equals("Agent") || outer.equals("SocialAgent") || outer.equals("AntiSocialAgent") || outer.equals("Landscape") || outer.equals("AgentSimulation") || outer.equals("LandscapeDisplay"); } private static void reportCrash(Throwable e) { if (e instanceof java.lang.reflect.InvocationTargetException && e.getCause() != null) { e = e.getCause(); } System.out.println(); System.out.println(" [CRASH] Your code threw " + e.getClass().getName()); if (e.getMessage() != null) { System.out.println(" message: " + e.getMessage()); } int shown = 0; for (StackTraceElement frame : e.getStackTrace()) { if (isStudentFrame(frame) && shown < 4) { System.out.println(" at: " + frame.getClassName().replace('$', '.') + "." + frame.getMethodName() + " (" + frame.getFileName() + " line " + frame.getLineNumber() + ")"); shown++; } } if (e instanceof NullPointerException) { printHint("A NullPointerException means a method was called on a reference that is null.\n" + "Did the Landscape constructor create the agent list and the Random object?\n" + "Does getNeighbors return a list (not null)? Does a LinkedList loop walk past the end?"); } else if (e instanceof IllegalArgumentException && String.valueOf(e.getMessage()).contains("bound")) { printHint("gen.nextInt(n) needs n > 0. Return early when the list is empty, and use\n" + "gen.nextInt(agents.size()) - not agents.size() - 1."); } else if (e instanceof java.awt.HeadlessException) { printHint("runExpt tried to open a window. When showDisplay is false, do not create a\n" + "LandscapeDisplay (and do not call repaint or sleep)."); } else if (e instanceof StackOverflowError) { printHint("A method keeps calling itself forever. Check toString() and updateState()."); } } private static Result runTask(Task t) { passed = 0; failed = 0; System.out.println(); System.out.println("------------------------------------------------------------"); System.out.println(" Task " + t.number + " - " + t.title); System.out.println("------------------------------------------------------------"); final Throwable[] error = new Throwable[1]; Thread worker = new Thread(() -> { try { t.body.run(); } catch (Throwable e) { error[0] = e; } }); worker.setDaemon(true); worker.start(); try { worker.join(t.timeLimitMs); } catch (InterruptedException ignored) { } if (worker.isAlive()) { System.out.println(); System.out.println(" [TIMEOUT] Task " + t.number + " did not finish within " + (t.timeLimitMs / 1000) + " seconds."); if (t.number == 8) { printHint("Either the loop in runExpt never stops, or each step is far too slow.\n" + "Slow is usually a loop like for (i...) agents.get(i) - each get(i) walks\n" + "from the head, so the loop is O(n^2). Use a for-each loop over the agents.\n" + "Also make sure runExpt does not sleep when showDisplay is false."); } else { printHint("This almost always means an infinite loop. In a loop that walks a list,\n" + "make sure the loop variable moves forward every time, and that the\n" + "loop's stopping condition can actually become true."); } return Result.TIMEOUT; } if (error[0] != null) { reportCrash(error[0]); return Result.CRASH; } System.out.println(); System.out.println(" " + passed + " checks passed, " + failed + " failed."); return failed == 0 ? Result.PASS : Result.FAIL; } private static void banner(String... lines) { System.out.println(); System.out.println("============================================================"); for (String line : lines) { System.out.println(" " + line); } System.out.println("============================================================"); } public static void main(String[] args) { System.setProperty("java.awt.headless", "true"); List tasks = buildTasks(); banner("CS231 Project 3 - Agent-Based Simulation Tester", "Tasks run in order. The tester stops at the first task that needs work.", "Tip: run a single task with java Project3Tester "); if (args.length > 0) { int which; try { which = Integer.parseInt(args[0]); } catch (NumberFormatException e) { which = -1; } if (which < 1 || which > tasks.size()) { System.out.println("Please give a task number from 1 to " + tasks.size() + "."); return; } Result r = runTask(tasks.get(which - 1)); System.out.println(); System.out.println(r == Result.PASS ? "Task " + which + " is complete." : "Task " + which + " still needs work."); System.exit(0); } int completed = 0; for (Task t : tasks) { Result r = runTask(t); if (r != Result.PASS) { banner("Task " + t.number + " still needs work. (" + completed + " of " + tasks.size() + " tasks complete)", "Read the [FAIL] / [CRASH] messages above, experiment on your own,", "fix your code, recompile (javac *.java), and run the tester again."); System.exit(0); } completed++; System.out.println(" Task " + t.number + " complete."); if (t.number == 5) { banner("Your Landscape is ready to display.", "Run java LandscapeDisplay and confirm the window shows 100 blue", "and 100 red agents before continuing."); } } banner("All " + tasks.size() + " Project 3 tasks complete!", "Remember: the tester performs basic checks only.", "Next: run the simulation with the display, then do the Exploration."); System.exit(0); } }