package aima.agents; import java.awt.*; import java.awt.event.*; import java.util.*; public class GridComponent extends Component implements ActionListener { protected int width, height; protected GridApplet frame; protected GridEnvironment environment; /** This constructor requires a Frame and a desired size */ public GridComponent(GridApplet frame, GridEnvironment env, int width, int height) { this.frame = frame; this.environment = env; this.width = width; this.height = height; enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK); } public Dimension getPreferredSize() { return new Dimension(width, height); } int boxSize = 30, minBoxSize = 20; /** Draw the grid lines, and stuff inside. */ public void paint(Graphics g) { int xSize = environment.xSize, ySize = environment.ySize; // Draw the grid lines int xWin = this.getSize().width, yWin = this.getSize().height; boxSize = java.lang.Math.max(minBoxSize, java.lang.Math.min(xWin/xSize, yWin/ySize)); for(int i = 0; i <= xSize; i++) { g.drawLine(i*boxSize, 0, i*boxSize, ySize*boxSize); g.drawLine(0, i*boxSize, xSize*boxSize, i*boxSize); } Vector objs = environment.objects; for (int i = 0; i < objs.size(); i++) { Thing obj = (Thing)objs.elementAt(i); Point p = obj.location; if (p != null) { if (obj instanceof Dirt) g.fillOval(p.x * boxSize + 5, p.y * boxSize + 5, 10, 10); if (obj instanceof AgentThing) { g.setColor(Color.blue); g.fillRect(p.x * boxSize + 3, p.y * boxSize + 3, 14, 14); g.drawLine(p.x*boxSize+10, p.y*boxSize+10, p.x*boxSize+10 + obj.heading.x*12, p.y*boxSize+10 + obj.heading.y*12); g.setColor(Color.black); } if (obj instanceof Wall) { g.setColor(Color.gray); g.fillRect(p.x * boxSize + 1, p.y * boxSize + 1, 18, 18); g.setColor(Color.black); } } } } public void actionPerformed(ActionEvent event) { System.out.println("GridComponent sees " + event); } /** When the mouse moves, display where we are. */ public void processMouseMotionEvent(MouseEvent e) { frame.cellLabel.setText(e.getX()/boxSize + "," + e.getY()/boxSize); super.processMouseMotionEvent(e); // Important! } }