一步一步学Repast 第二章(把界面显示出来)

这一章我们来讨论下CarryDropSpace,它主要负责界面上的工作。来看一下它的代码:

  1. // CarryDropSpace.java
  2. package demo;
  3.  
  4. import uchicago.src.sim.space.Object2DGrid; //这是space包中最常见的类,它是以一种非连续的格子来存放object,以x轴和y轴来标识。
  5.  
  6.   
  7.  
  8.  
  9. public class CarryDropSpace ...{
  10. private Object2DGrid moneySpace;
  11.  
  12.   public CarryDropSpace(int xSize, int ySize)...{
  13.     moneySpace = new Object2DGrid(xSize, ySize);
  14.  
  15.     for(int i = 0; i < xSize; i++)...{
  16.       for(int j = 0; j < ySize; j++)...{
  17.         moneySpace.putObjectAt(i,j,new Integer(0))//把所有的格子都放满 Integer(0) 这个对象。
  18.       }
  19.     }
  20.   }
  21.  
  22.   public void spreadMoney(int money)...{
  23.     // Randomly place money in moneySpace
  24.     for(int i = 0; i < money; i++)...{
  25.  
  26.       // Choose coordinates
  27.       int x = (int)(Math.random()*(moneySpace.getSizeX()));
  28.       int y = (int)(Math.random()*(moneySpace.getSizeY()));
  29.  
  30.       // Get the value of the object at those coordinates
  31.       int currentValue = getMoneyAt(x, y);
  32.       // Replace the Integer object with another one with the new value
  33.       moneySpace.putObjectAt(x,y,new Integer(currentValue + 1));   //随机改变money个格子里的对象为 Integer(1)
  34.      }
  35.   }
  36.  
  37.   public int getMoneyAt(int x, int y)...{
  38.     int i;
  39.     if(moneySpace.getObjectAt(x,y)!= null)...{
  40.       i = ((Integer)moneySpace.getObjectAt(x,y)).intValue();
  41.     }
  42.     else...{
  43.       i = 0;
  44.     }
  45.     return i;
  46.   }
  47.  
  48.   public Object2DGrid getCurrentMoneySpace()...{
  49.     return moneySpace;
  50.   }
  51.  
  52. }

阅读全文 »

标签:, , , , , , , , ,