appletbots
Class World

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by javax.swing.JPanel
                  extended by appletbots.World
All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, javax.accessibility.Accessible
Direct Known Subclasses:
GatherersWorld

public class World
extends javax.swing.JPanel

This class represents a world in which multiple agents can exist and interact with each other or with objects in the world. The positions and velocities of objects and agents are kept internally. The positions cannot be accessed by the agents or the objects themselves. This keeps all agent algorithms completely vector-based and, therefore, scalable.

Author:
Erik Rasmussen
See Also:
Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class javax.swing.JPanel
javax.swing.JPanel.AccessibleJPanel
 
Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent
 
Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
 
Field Summary
protected  int delay
          The number of milliseconds to sleep in between time cycles
protected  java.util.List listeners
          Registered listeners
protected static int MAX_ADD_OBJECT_ATTEMPTS
          The maximum number of attempts (1000) that should be made trying to add an object randomly to the world.
protected  java.util.Map objectsTable
          A hashtable mapping each object to its location and velocity datum
protected  WorldObject selectedObject
          The object that is currently selected
protected  java.awt.Color selectedObjectColor
          The color to paint the object that is selected
protected  java.awt.Color selectedSight
          The color in which to paint the "sight circle" of the selected object
protected  WorldThread thread
          The thread driving the world
protected  long time
          The number of time cycles that have passed
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
World(int width, int height)
          Constructs a new world with the given dimensions
 
Method Summary
 void addListener(WorldListener listener)
          Registers a listener for this world
 void addObject(WorldObject object)
          Adds an object to a random position in the world.
 void addObject(WorldObject object, Point location, Vector velocity)
          Adds an object to the world at the given position with the given initial velocity
 void addObject(WorldObject object, Vector velocity)
          Adds an object to a random position in the world with the given initial velocity
 void dropItem(CarrierAgent agent, CarriableObject item)
          Drops an item from a CarrierAgent
 WorldObject getClosestObjectOfType(Agent agent, java.lang.Class type)
          Returns the closest object of the given type to the given agent that is seen by the agent
protected  WorldObjectData getData(WorldObject object)
          Returns the location and velocity data for the given object
 int getDelay()
          Returns the number of milliseconds to wait between time cycles
protected  double getDistanceBetweenObjects(WorldObject a, WorldObject b)
          Returns the distance between the two objects
 java.util.List getNeighbors(Agent agent)
          Returns all the other agents that can be seen by the given agent, normally called by the given agent himself.
protected  WorldObject getObjectAt(int x, int y)
          Returns the object at the given x and y coordinates.
protected  Point getRandomPoint()
          Returns a random point in the world
protected  Point getRandomPoint(int distance)
          Returns a random point in the world within a given distance from the boundaries
 java.util.List getSeenObjects(Agent agent)
          Returns all the objects that can be seen by the given agent, normally called by the given agent himself.
 long getTime()
          Returns the number of elapsed time cycles
 Vector getVectorToObject(WorldObject a, WorldObject b)
          Returns a vector from the first object to the second object.
 Vector getVelocity(WorldObject object)
          Returns the velocity for the given object
 int getWorldHeight()
          Returns the height (in pixels) of the world
 int getWorldWidth()
          Returns the width (in pixels) of the world
 void importObjects(World world)
          Imports all the objects from another world into this one
 void incrementTime()
          Called by the WorldThread.
protected  boolean inWorld(Point location, int size)
          Returns whether or not an object with the given size at the given location would be complete inside the boundaries of the world
 boolean isRunning()
          Returns whether or not the world thread is running
 java.util.Comparator objectDistanceComparator(WorldObject object)
          Returns a comparator to sort other objects by their distance to the given object
 void paint(java.awt.Graphics g)
          Paints the world (invoked by Swing)
protected  void paintObject(WorldObject object, java.awt.Graphics g)
          Paints an individual object in the world
protected  void paintObjects(java.awt.Graphics g)
          Paints the objects in the world
 void removeObject(WorldObject object)
          Removes an object from the world
 void selectObject(WorldObject object)
          Selects the given object
 void selectObjectAt(int x, int y)
          Selects the object at the given location
 void setDelay(int delay)
          Sets the number of milliseconds to wait between time cycles
 void setSelectedObjectColor(java.awt.Color selectedObjectColor)
          Sets the color to paint the selected object
 void setSelectedSight(java.awt.Color selectedSight)
          Sets the color with which to paint the selected object's "sight circle"
 void startThread()
          Starts the world thread
 void stopThread()
          Stops the world thread
 
Methods inherited from class javax.swing.JPanel
getAccessibleContext, getUI, getUIClassID, paramString, setUI, updateUI
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addNotify, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyBinding, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeNotify, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

MAX_ADD_OBJECT_ATTEMPTS

protected static final int MAX_ADD_OBJECT_ATTEMPTS
The maximum number of attempts (1000) that should be made trying to add an object randomly to the world. This is to prevent infinite loops if there is no space for the object.

See Also:
Constant Field Values

objectsTable

protected java.util.Map objectsTable
A hashtable mapping each object to its location and velocity datum


delay

protected int delay
The number of milliseconds to sleep in between time cycles


thread

protected WorldThread thread
The thread driving the world


time

protected long time
The number of time cycles that have passed


listeners

protected java.util.List listeners
Registered listeners


selectedObject

protected WorldObject selectedObject
The object that is currently selected


selectedObjectColor

protected java.awt.Color selectedObjectColor
The color to paint the object that is selected


selectedSight

protected java.awt.Color selectedSight
The color in which to paint the "sight circle" of the selected object

Constructor Detail

World

public World(int width,
             int height)
Constructs a new world with the given dimensions

Parameters:
width - The width of the world in pixels
height - The height of the world in pixels
Method Detail

paint

public void paint(java.awt.Graphics g)
Paints the world (invoked by Swing)

Overrides:
paint in class javax.swing.JComponent
Parameters:
g - The graphics object on which to paint the world

paintObjects

protected void paintObjects(java.awt.Graphics g)
Paints the objects in the world

Parameters:
g - The graphics object on which to paint the objects

paintObject

protected void paintObject(WorldObject object,
                           java.awt.Graphics g)
Paints an individual object in the world

Parameters:
object - The object to paint
g - The graphics object on which to paint the object

addObject

public void addObject(WorldObject object)
               throws CollisionException
Adds an object to a random position in the world. The object will have an initial speed of 0.

Parameters:
object - The object to add
Throws:
CollisionException - Thrown if the object cannot be added randomly to the world in MAX_ADD_OBJECT_ATTEMPTS

addObject

public void addObject(WorldObject object,
                      Vector velocity)
               throws CollisionException
Adds an object to a random position in the world with the given initial velocity

Parameters:
object - The object to add
velocity - The initial velocity
Throws:
CollisionException - Thrown if the object cannot be added randomly to the world in MAX_ADD_OBJECT_ATTEMPTS

addObject

public void addObject(WorldObject object,
                      Point location,
                      Vector velocity)
               throws CollisionException,
                      OutOfThisWorldException
Adds an object to the world at the given position with the given initial velocity

Parameters:
object - The object to add
location - The location to add the object
velocity - The initial velocity
Throws:
CollisionException - Thrown if the location given is at least partially occupied by another object
OutOfThisWorldException - Thrown if the location given will place at least part of the object outside the boundaries of the world

getRandomPoint

protected Point getRandomPoint()
Returns a random point in the world

Returns:
A random point in the world

getRandomPoint

protected Point getRandomPoint(int distance)
Returns a random point in the world within a given distance from the boundaries

Parameters:
distance - The minimum distance from the boundaries that the point can be
Returns:
A random point in the world within a given distance from the boundaries

removeObject

public void removeObject(WorldObject object)
Removes an object from the world

Parameters:
object - The object to remove

getData

protected WorldObjectData getData(WorldObject object)
Returns the location and velocity data for the given object

Parameters:
object - The object to get the data for
Returns:
The location and velocity data for the given object

getVelocity

public Vector getVelocity(WorldObject object)
Returns the velocity for the given object

Parameters:
object - The object to get the velocity of
Returns:
The velocity for the given object

incrementTime

public void incrementTime()
Called by the WorldThread. This method does three things: it allows all the agents to observe the world, moves all the objects, and repaints the world.


getDelay

public int getDelay()
Returns the number of milliseconds to wait between time cycles

Returns:
The number of milliseconds to wait between time cycles

setDelay

public void setDelay(int delay)
Sets the number of milliseconds to wait between time cycles

Parameters:
delay - The number of milliseconds to wait between time cycles

startThread

public void startThread()
Starts the world thread


stopThread

public void stopThread()
Stops the world thread


isRunning

public boolean isRunning()
Returns whether or not the world thread is running

Returns:
Whether or not the world thread is running

getSeenObjects

public java.util.List getSeenObjects(Agent agent)
Returns all the objects that can be seen by the given agent, normally called by the given agent himself.

THIS METHOD WILL NOT RETURN OTHER AGENTS! To get seen agents, use getNeighbors().

Parameters:
agent - The agent for which to get the seen objects
Returns:
All the objects the given agent can see

getNeighbors

public java.util.List getNeighbors(Agent agent)
Returns all the other agents that can be seen by the given agent, normally called by the given agent himself.

Parameters:
agent - The agent for which to return the seen neighbors
Returns:
All the agents that the given agent can see

getVectorToObject

public Vector getVectorToObject(WorldObject a,
                                WorldObject b)
Returns a vector from the first object to the second object. This is useful when an agent wants to move towards an object. The returned vector is the direction in which the agent should move.

Note: The vector returned is not from the center of the first object to the center of the second object! The vector returned is the vector that, if added to the first object's location, would place the object so that it was touching the second object. In other words, it's the vector from the center of the first object to the center of the object minus the radii of the both objects.

Parameters:
a - The first object
b - The second object
Returns:
A vector from the first object to the second object

getDistanceBetweenObjects

protected double getDistanceBetweenObjects(WorldObject a,
                                           WorldObject b)
Returns the distance between the two objects

Parameters:
a - An object
b - Another object
Returns:
The distance between the two objects

getWorldWidth

public int getWorldWidth()
Returns the width (in pixels) of the world

Returns:
The width (in pixels) of the world

getWorldHeight

public int getWorldHeight()
Returns the height (in pixels) of the world

Returns:
The height (in pixels) of the world

getTime

public long getTime()
Returns the number of elapsed time cycles

Returns:
The number of elapsed time cycles

importObjects

public void importObjects(World world)
Imports all the objects from another world into this one

Parameters:
world - The world to import the objects from

inWorld

protected boolean inWorld(Point location,
                          int size)
Returns whether or not an object with the given size at the given location would be complete inside the boundaries of the world

Parameters:
location - The location of the hypothetical object
size - The size of the hypothetical object
Returns:
Whether or not an object with the given size at the given location would be complete inside the boundaries of the world

getObjectAt

protected WorldObject getObjectAt(int x,
                                  int y)
Returns the object at the given x and y coordinates. Used for user interaction and mouse-clicks.

Parameters:
x - The x coordinate
y - The y coordinate
Returns:
The object at the given location

selectObjectAt

public void selectObjectAt(int x,
                           int y)
Selects the object at the given location

Parameters:
x - The x coordinate
y - The y coordinate

selectObject

public void selectObject(WorldObject object)
Selects the given object

Parameters:
object - The object to select

setSelectedObjectColor

public void setSelectedObjectColor(java.awt.Color selectedObjectColor)
Sets the color to paint the selected object

Parameters:
selectedObjectColor - The color to paint the selected object

setSelectedSight

public void setSelectedSight(java.awt.Color selectedSight)
Sets the color with which to paint the selected object's "sight circle"

Parameters:
selectedSight - The color with which to paint the selected object's "sight circle"

dropItem

public void dropItem(CarrierAgent agent,
                     CarriableObject item)
              throws CollisionException
Drops an item from a CarrierAgent

Parameters:
agent - The agent dropping the item
item - The object beind dropped
Throws:
CollisionException - Thrown if the item cannot be placed within the "pickup distance"

addListener

public void addListener(WorldListener listener)
Registers a listener for this world


getClosestObjectOfType

public WorldObject getClosestObjectOfType(Agent agent,
                                          java.lang.Class type)
Returns the closest object of the given type to the given agent that is seen by the agent

Parameters:
agent - The agent to get an object near
type - The type of objects to search for
Returns:
The closest seen object of the given type to the given agent

objectDistanceComparator

public java.util.Comparator objectDistanceComparator(WorldObject object)
Returns a comparator to sort other objects by their distance to the given object

Parameters:
object - The object to compare distances to
Returns:
A comparator to sort other objects by their distance to the given object