📄 ant.java
字号:
/* * This code is from the book: * * Winder, R and Roberts, G (2000) Developing Java * Software, second edition, John Wiley & Sons. * * It is copyright (c) 2000 Russel Winder and Graham Roberts. */import SimFrameWork.Patch ;import SimFrameWork.Turtle ;import SimFrameWork.RandomGen ;/** * This class provides Ant objects for the simple ant foraging * simulation, by specializing the Turtle class. * * @version 2.0 March 1999 * @author Graham Roberts */class Ant extends Turtle { /** * Ant creation. An ant does not initially carry a wood chip. * * @param p patch ant is initially located on. */ Ant(Patch p) { super(p) ; chip = false ; } /** * Update ant by one time step. */ public void update() { // Move ant a random distance. move() ; // If ant has a chip and if the current patch already has // at least one chip on it then assume it is a pile and // drop chip. int val = location.value() ; if (chip && (val > 0)) { location.incrValue() ; chip = false ; return ; } // If the ant is not carrying anything and there is a chip // available pick it up. if (!chip && (val > 0)) { location.decrValue() ; chip = true ; } } /** * Test if ant is carrying a wood chip. * * @return return true if the ant is carrying a wood chip. */ public boolean isLoaded() { return chip ; } /** * Move ant a random distance in a random direction. */ private void move() { int distance = RandomGen.getNext(3) ; int direction = RandomGen.getNext(8) ; Patch p = location ; for (int i = 0 ; i < distance ; ++i) { Patch t = p.getNeighbour(direction) ; if (t != null) { p = t ; } } location.removeTurtle(this) ; location = p ; location.addTurtle(this) ; } /** * Set to true when ant is carrying a woodchip. */ private boolean chip ;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -