实例介绍
是学习repastS的官方入门资料,是一个僵尸吃人的典型例子。
REPAST JAVA GETTING STARTED Top Level Elements Select working se Deselect Working Set Edit Active Working Set. v6,1 Window Working Set v l ReLog Resource Filter Filte Package Presentation y Show Referenced Libraries' Node V R Link with Editor FIGURE 3. Disabling the ReLogo Filter New Class Wizard. The Repast Simphony project wizard creates a source directory and default package into which we can crcatc thcsc agent classes. In our casc, the package is zombies", which can be seen immediately under the src directory" The wizard has also created two additional files under the jzombies package: ModelInitializer groovy and ModelInitializer. agent. These are not necessary for this tutorial and so can be deleted (1)Click on the ModelInitializer groovy file 2 Press the delete key on your keyboard (3) Repeat for the ModelInitializer agent file We will now create our Zombie and human classes (1)Right click on the jzombies folder under src Click the new class wizard button(Fig (3) Type Zombie for the name (4)Optionally, click the generate comments box. This won't comment the code for you, of course, but it does leave a placeholder 5)Repeat steps 1-4, but type Human for the name of the class You should now see Zombie. java and Human. java files in the jzombies packages un derneath the src folder, and these files should be open in Fclipse's editor pane. (If they arc not opcn, doublc click on cach filc to open it). Lct's bogin with the Zombies. The Package names typically use an internet domain name as the basis for a package name, but for the purposes of this tutorial "zombies"is perfectly fine. See Java Tutorial: packages for more info nICK cOllieR MICHAEL NORTH- REPAST DEVELOPMENT TEAM Java Element Filters O Name filter patterns (matching names will be hidden The patterns are separated by comma. where any string Select the elements to exclude from the view TYoI PuDIC eDE 3 口Nan- shared projects M Package declarations Static fields and methods v Synthetic members Filter description Select all Deselect all Cancel Ok FIGURe 4. Filler window ReLog a Java FIGURE 5. Sclccting the Java Pcrspcctivc Zombies behavior is to wander around looking for Ilumans to infect. More specifically each iteration of the simulation, each Zombie will determine where the most humans are within its local area and move there. Once there it will attempt to infect a Iluman at that location and turn it into a Zombie Rather than implementing that all at once, we will begin by implementing the movement To do this we will locate the Zombies and Humans within a ContinuousSpace and a grid A Continuous Space allows us to use floating point numbers(e. g. 1.5) as the coordinates REPAST JAVA GETTING STARTED 回画]0,」 Package Explorer 5 v哆 zombies src 出 zombies FIGurE 6. New Class wizard butte of a Zombie's and Humans location, and the grid allows us to do neighborhood and proximity queries(i.e. who is near me?")using discrete integer Grid coordinates Let's begin by adding some field variables and a constructor to the Zombie class. Note that copying the text straight from this document may lead to irregular spacing and other issues in the Eclipse editor 1 public class Zombie t private Continuous space <object> space private grid<object> grid; public Zombie(Continuous Space<object> space, Grid<Object> grid) his space space this grid grid 10} LISTING 1. Zombie Constructor and variables Line 3 and 4 are field variables to hold the space and grid in which the zombie will be located. The Zombie will move about the Continuous space and we will simply round the Continuous Space location to determine the corresponding grid location. Lines 6-9 constitute the constructor which sets the values of the space and grid variables. The space and grid variables have Object as their template parameter. This allows use to put anything in them and prevents Eclipse from giving us spurious warnings. You may need to add the appropriate imports for Continuous Space and Grid. These imports looks like More details on Continuous Space and Grid can found in the Repast Java aPi documentation and the Repast reference 6 nICK cOllieR MICHAEL NORTH- REPAST DEVELOPMENT TEAM 1 import repast simphony space. continuous Continuous space; 2 import repast simphony space grid. Grid; LISTING 2. Zombie Imports You can add these automatically in Eclipse by right clicking on the type(e. g grid) that needs an import and choosing Source- Add import from the menu. As new code is added during the tutorial, you will need to add the appropriate imports. Whenever you see the red squiggle, use Eclipse to add the necessary imports ow lets add a method to Zombie that will be called every iteration of the simulatiorpk We will call this method step 1 public void step()i // get the grid location of this Zombie 234567 GridPoint pt grid getLocation(this); // use the GridcellNgh class to create Gridcells for // the surrounding neighborhood GridcellNgh<Human> nghCreator new GridCelINgh <Human>(grid, pt Human class, 1, 1) 9 List<GridCell<Human>> gridCells = nghCreator getNeighborhood(true) 10 SimUtilities. shuffle(gridCells, RandomHelper getUniform()); 11 GridPoint pointwithMostHumans null int maxcount 14 for (gridCell<Human> cell gridCells)t if (cell size> maxCount)i 16 pointwithMostHumans cell. getpoint ( 17 max Count cell size o 19 20} LISTING 3. step Method Line 3 gets the location of this Zombie(this refers to the object whose method is calling the code) in the grid. We then use a GridCellNgh to create a List of GridCells containing Humans. A GridCellNgh is used to retreive a list of GridCells that represent REpast Simphony also provides a wizard for adding typical snippets of code. This wizard can be activated using the top hat icon in the Eclipse toolbar. The wizard produces groovy compatible code so some additional work may need to be done to make it Java compatible REPAST JAVA GETTING STARTED the contents and location of the neighboring cells around a GridPoint. The constructor to GridCellNgh takes the grid whose cells we want to get, the point whose neighboring grid cells we want, the Class of the items we want in the cells, and the extent along the appropriate dimensions. Lines 7 and 8 specify the grid and the location of this Zombie as the point whose neighboring cells we want. By specifying the human class in the constructor and as a template parameter wc filter out any non-Humans. Conscquently, our Grid Cells will on contain Humans. We then call getNeighborhood passing true to it. By passing true the returned list of Grid Cclls will contain the ccnter ccll whcrc the Zombic is currently located. USing SimUtilities. shuffle, we shuffle the list of GridCells Without the shuffle, the Zombies will always movc in the samc direction when all cclls are equal. We use the RandomHelper class to provide us with a random generator for the shuffle. The remaining code iterates through the list of GridCells and determines which one of them has the largest size. A GridCells size is a measure of the number of objects it contains and thus the cell with the greatest size contains the most Humans Now that we have discovered the location with the most Humans (i.e. pointWithMostHumans) we want to move the Zombie towards that location. We will first write this method then add the code to call it in the step() method 1 public void moveTowards(gridPoint pt) only move if we are not already in this grid location if ( pt equals(grid getLocation (this)))t NdPoint my Point space getLocation(this) NdPoint otherpoint IdPoint (pt. getxO, pt. getY() double angle = SpatialMath calcAngleFor2DMovement (space myPoint, otherPoint) space. moveByVector(this, 1, angle, 0) my Point space getLocation(this) grid moveTo(this, (int)my Point. getX(, (int)my Point. getY(); 11 12 LISTING 4. move Towards method moveTowards( begins with a check to make sure that the Zombie is not already at the location we want to move towards. Then we get the Zombies current location in space as a NdPoint. NdPoint stores its coordinates as doubles and thus it is appropriate when working with ContinuousSpaces. We want the Zombie to move towards the GridPoint pt but in order to make this sort of movement using a Continuous Space we need to convert that gridPoint to a NdPoint. line 5 does that We then use the SpatialMath method calcAngleFor2DMovement to calculate the angle along which the Zombie should move if it is to move towards the gridPoint. Line 8 then performs this movement and moves the Zombie in the Continuous Space 1 units along the calculated angle. The last two lines nICK cOllieR MICHAEL NORTH- REPAST DEVELOPMENT TEAM update the Zombies position in the Grid by converting its location in the Continuous Space to int coordinates al riate for a grid Once you've written this moveTowards()method, add a call to it in the step() method The end of the step( should now look like 1 for (gridCell<Human> cell ridCells)t if (cell size maxCount)t pointwithMostHumans cell getPoint O; maxCount cell size 6} 7 moveTowards(pointWithMost Humans) LISTING 5. Slep with Move Towards Added Notc the addition of the call to moveTowards() following the for loop We want, the step method to be ca lled every iteration of the simulation. We can do this y adding an @ScheduledMethod annotation on it. Obviously, the mcthod itsclf is part of a class. and thus what we are actually scheduling are invocations of this method on instances of this class. For example, if we have 10 Zombies, then we can schedule this method to be called on each of those Zoinbies. The annotation has a variety of paramelers Chal are used to specify when and how often the method will be called, the number of object instances Lo invoke the inethod ol, and so on 1 @ScheduledMethod (start = 1, interval =1) 2 public void stept // get the grid location of this Zombie GridPoint pt grid. getLocation(this); LISTING 6. Step Method with Annotation The parameters here in line l will schedule the step method to be called on all Zombies starting at tick(timestep)1 and every tick thereafter Let's now turn to the code for the Humans. Select Human java in Eclipse's editor pane. The basic behavior for a Iluman is to react when a Zombie comes within its local neighborhood by running away from the area with the most Zombies. Additionally, Humans have a certain amount of energy that is expended in running away. If this energy is 0 or less then a Human is unable to run. We begin by creating the relevant field variables and constructor ASee the Repast Java API documentation and the Repast Reference for more information on the @ScheduledMethod annotation REPAST JAVA GETTING STARTED 1 public class Human t private continuous Space <object> space; 34567 private Grid<object> grid private int energy, startingenergy; public Human ContinuousSpace <object> space, Grid<object> grid int energy) 9 this space space; this grid grid; this energy startingEnergy = energy i LISTING 7. Human Constructor and Variables The Human constructor is identical to that of the Zombie with the addition of int energy and startingEnergy. energy will be used to track the current amount of energy a Human has. startingEnergy will be used to set the energy level back to its starting level after a Human has had a rest The main behavior of a Human is implemented in its run method nICK cOllieR MICHAEL NORTH- REPAST DEVELOPMENT TEAM 1 public void run(t / get the grid location of this Human 234567 GridPoint pt grid getLocation(this) // use the GridcellNgh class to create Gridcells for / the surrounding neighborhood GridcellNgh< Zombie> ngh Creator =new GridcellNgh<Zombie>(grid, pt Zombie, class List<GridCell<Zombie>> gridCells nghCreator getNeighborhood(true); SimUtilities. shuffle(gridCells, RandomHelper getUniformO) 10 11 Gridpoint pointwithLeastzombies = null int minCount =Integer MAX-VALUE; 13 for (GridCell<Zombie> cell gridCells)t 14 if (cell size< minCount)i 15 pointwithLeastZombies cell. getPoint( 16 minCount cell size( 18 19 20 if (energy >0)i 21 moveTowards(pointWithleastZombies) y else i energy startingEnergy 24 25} LISTING 8. The Run method This looks much like the Zombie code. A GridCellNgh is used to find the Zombies in the neighboring grid cells. It then determines which of these cells has the least Zombies and attempts to move towards that. Note that move Towards is only called if the energy level is greater than 0. If energy does equal 0, the Human doesnt move and energy is set back to its starting level. A Iluman's moveTowards looks like 【实例截图】
【核心代码】
标签:
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论