现在把FoxAndRabbit给码出来:
package foxnrabbit;import java.util.ArrayList;import java.util.List;import javax.swing.JFrame;import ICell.ICell;import animal.Animal;import animal.Fox;import animal.Rabbit;import field.Field;import field.Location;import field.View;public class FoxAndRabbit { private Field field; private View view; public FoxAndRabbit(int size) { field = new Field(size, size); for(int row = 0; row < field.getHeight(); row ++) { for(int col = 0; col < field.getWidth(); col ++) { double probability = Math.random(); if(probability < 0.05) { field.place(row, col, new Fox()); }else if(probability < 0.15) { field.place(row, col, new Rabbit()); } } } view = new View(field); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setTitle("FoxAndRabbit"); frame.add(view); frame.pack(); frame.setVisible(true); } public void start(int steps) { for(int i = 0; i < steps; i ++) { step(); view.repaint(); try { Thread.sleep(200); } catch (Exception e) { e.printStackTrace(); } } } public void step() { for(int row = 0; row < field.getHeight(); row ++) { for(int col = 0; col < field.getWidth(); col ++) { ICell cell = field.get(row, col); if(cell != null) { Animal animal = (Animal) cell; animal.grow(); System.out.println(animal); if(animal.isAlive()){ //move Location[] freeAdj = field.getFreeAdj(row, col); if(freeAdj.length > 0) { Location moveloc = animal.move(row, col, freeAdj); if(moveloc != null) { field.move(row, col, moveloc); } } //feed,注意,吃掉的animal一定要remove出来; ICell[] neighbour = field.getNeighbour(row, col); ListlistofRabbit = new ArrayList (); if(neighbour.length > 0) { for(ICell c : neighbour) { if(c instanceof Rabbit) { listofRabbit.add((Rabbit) c); } } if(!listofRabbit.isEmpty()){ Animal fed = animal.feed(row, col, listofRabbit); if(fed != null) { field.remove((ICell) fed); } } } //breed Animal baby = animal.breed(); if(baby != null) { field.placeRandomAdj(row, col, (ICell)baby); } }else { field.remove(row, col); } } } } } public static void main(String[] args) { FoxAndRabbit fnr = new FoxAndRabbit(40); fnr.start(150); }}