狐狸和兔子:细胞自动机升级版

  • 包:foxandrabbit
    • 主程序(FoxAndRabbit)
  • 包:field
    • 数据处理(Field)
    • 图形绘制(View)
    • 存储移动位置(Location)
  • 包:Cell
    • 接口(Cell)
  • 包:animal
    • 动物类[父类](Animal)
    • 狐狸[子类](Fox)
    • 兔子[子类](Rabbit)

包:foxandrabbit

主程序(FoxAndRabbit)

package foxandrabbit;import java.util.ArrayList;
import javax.swing.JFrame;import field.Field;
import field.View;
import field.Location;import animal.Animal;
import animal.Fox;
import animal.Rabbit;import cell.Cell;public class FoxAndRabbit {//成员变量private Field theField;//Field变量,用来管理新的网格private View theView;//继承自Jpanel的类,用来显示图形/*------构造函数------*/public FoxAndRabbit(int size) {//创建网格theField=new Field(size,size);//遍历网格for(int row=0;row<theField.getHeight();row++){for(int col=0;col<theField.getWidth();col++){double probability=Math.random();//随机放入狐狸if(probability<0.05){theField.place(row,col,new Fox());}//随机放入兔子else if(probability<0.15){theField.place(row, col,new Rabbit());}}}/*------把theField加入到显示框------*/theView=new View(theField);JFrame frame = new JFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setResizable(false);frame.setTitle("Cells");frame.add(theView);frame.pack();frame.setVisible(true);}/*------开始函数,传入的参数是程序要执行的次数------*/public void start(int steps){for (int i=0;i<steps;i++) {step();theView.repaint();//Java底层函数try {Thread.sleep(200);} catch (Exception e) {e.printStackTrace();}}}/*------step()函数,每次更新表格- - - - - -*/public void step() {for(int row=0;row<theField.getHeight();row++){for(int col=0;col<theField.getWidth();col++){//获取所有Cell的对象变量Cell cell=theField.get(row, col);if(cell!=null){//把管理的对象造型为Animal对象Animal animal=(Animal)cell;//年龄增长animal.grow();if(animal.isAlive()) {    //向周围移动Location loc=animal.move(theField.getFreeNeighbour(row, col));if(loc!=null) { theField.move(row,col,loc); }//获取周围的兔子,储存进容器里面Cell[] neighbour=theField.getNeighbour(row, col);ArrayList<Animal> listRabbit=new ArrayList<Animal>();for(Cell an:neighbour) {//instanceof关键字,判断是不是某个类的实例if(an instanceof Rabbit) { listRabbit.add((Rabbit)an); }                          }//吃掉兔子if(!listRabbit.isEmpty()) //isEmpty()是ArrayList的函数,没有元素则返回true{                         //这里涉及到了多态,这个animal实际上是Fox的对象,调用的是Fox的feed()//(animal本身是抽象类,自己不可能有对象的)Animal fed=animal.feed(listRabbit);//fed得到了兔子的对象之后,调用函数删除这个对象(被吃掉if(fed!=null) { theField.remove((Cell)fed); }}//动物繁殖Animal baby=animal.breed();if(baby!=null) { theField.placeRandomAdj(row,col,(Cell)baby); } }else { theField.remove(row ,col); }}}}}public static void main(String[] args) {FoxAndRabbit fr=new FoxAndRabbit(30);fr.start(50);     }}

包:field

数据处理(Field)

package field;import java.util.ArrayList;import cell.Cell;public class Field {private int width;private int height;private Cell[][] field;// 声明有这么个数组变量,但未承接任何对象private static final Location[] adjacent = { new Location(-1, -1), new Location(-1, 0), new Location(-1, 1),new Location(0, -1), new Location(0, 0), new Location(0, 1),new Location(1, -1), new Location(1, 0), new Location(1, 1),};public Field(int width, int height) {this.width = width;this.height = height;field = new Cell[height][width];}public int getWidth() {return width;}public int getHeight() {return height;}public Cell place(int row, int col, Cell cell) {// !这里的Cell o并非Cell类的对象,而是实现了Cell接口的对象field[row][col] = cell;Cell ret = field[row][col];return ret;}public Cell get(int row, int col) {return field[row][col];}public Cell[] getNeighbour(int row, int col) {ArrayList<Cell> list = new ArrayList<Cell>();for (int i = -1; i < 2; i++) {for (int j = -1; j < 2; j++) {int r = row + i;int c = col + j;if (r > -1 && r < height && c > -1 && c < width && !(r == row && c == col)) {list.add(field[r][c]);}}}return list.toArray(new Cell[list.size()]);}public Location[] getFreeNeighbour(int row, int col) {ArrayList<Location> list = new ArrayList<Location>();for (Location loc : adjacent) {int r = row + loc.getRow();int c = col + loc.getCol();if (r > -1 && r < height && c > -1 && c < width && field[r][c] == null) {list.add(new Location(r, c));}}// !学着点return list.toArray(new Location[list.size()]);}public boolean placeRandomAdj(int row, int col, Cell cell) {boolean ret = false;Location[] freeAdj = getFreeNeighbour(row, col);if (freeAdj.length > 0) {int idx = (int) (Math.random() * freeAdj.length);field[freeAdj[idx].getRow()][freeAdj[idx].getCol()] = cell;ret = true;}return ret;}public void clear() {for (int i = 0; i < height; i++) {for (int j = 0; j < width; j++) {field[i][j] = null;}}}public void remove(Cell fed) {for (int row = 0; row < height; row++) {for (int col = 0; col < width; col++) {if (field[row][col] == fed) {field[row][col] = null;break;}}}}public Cell remove(int row, int col) { // *函数重构field[row][col] = null;Cell ret = field[row][col];return ret;}public void move(int row, int col, Location loc) {field[loc.getRow()][loc.getCol()] = field[row][col];remove(row, col);}
}

图形绘制(View)

package field;import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;import javax.swing.JPanel;import cell.Cell;public class View extends JPanel {private static final long serialVersionUID = -2417015700213488315L;private static final int GRID_SIZE = 16;private Field theField;// *构造函数public View(Field field) {theField = field;}@Overridepublic void paint(Graphics g) {super.paint(g);g.setColor(Color.GRAY);for (int row = 0; row < theField.getHeight(); row++) g.drawLine(0, row * GRID_SIZE, theField.getWidth() * GRID_SIZE, row * GRID_SIZE);for ( int col = 0; col<theField.getWidth(); col++ )g.drawLine(col * GRID_SIZE, 0, col * GRID_SIZE, theField.getHeight() * GRID_SIZE);for (int row = 0; row < theField.getHeight(); row++) {for (int col = 0; col < theField.getWidth(); col++) {Cell cell = theField.get(row, col);if (cell != null) cell.draw(g, col * GRID_SIZE, row * GRID_SIZE, GRID_SIZE);}}}@Overridepublic Dimension getPreferredSize() {return new Dimension(theField.getWidth() * GRID_SIZE + 1, theField.getHeight() * GRID_SIZE + 1);}
}

存储移动位置(Location)

package field;public class Location {private int row;private int col;public Location(int row, int col) {this.row = row;this.col = col;}public int getRow() {return row;}public int getCol() {return col;}
}

包:Cell

接口(Cell)

package cell;import java.awt.Graphics;
public interface Cell {//注意这里不能写成interface class/** Cell是一个接口而非类(接口是一种完全抽象的抽象类)* !这个接口就是为了实现Fox和Rabbit类new的对象能够传递给Field类* Field类中指明需要的对象的类是Cell而Cell是作为中间承接者* Fox和Rabbit类需要有implements Cell语句来实现接口* !注意这里函数可以不用写函数前缀,只需要写返回值类型* ?抽象类无函数主体,只需声明函数原型,实现抽象类/接口的类都必须Override所有抽象方法,否则此子类仍为抽象类* ?abstract与final是冲突对立关系,抽象是用来被继承或重写的,final相反是不让继承/重写的*/void draw(Graphics g, int x, int y, int size);
}

包:animal

动物类[父类](Animal)

package animal;import java.util.ArrayList;import field.Location;public abstract class Animal {private int ageLimit;private int breedableAge;private int age;private boolean isAlive = true;public Animal(int ageLimit, int breedableAge) {this.ageLimit = ageLimit;this.breedableAge = breedableAge;}protected int getAge() {return age;}protected double getAgePercent() {return (double) age / (double) ageLimit;}public abstract Animal breed();public void grow() {age++;if (age >= ageLimit)die();}public void die() {isAlive = false;}public boolean isAlive() {return isAlive;}public boolean isBreedable() {return (age >= breedableAge);}//概率移动,移动位置public Location move(Location[] freeAdj) {Location ret = null;if (freeAdj.length > 0 && Math.random() < 0.02) {ret = freeAdj[(int) (Math.random() * freeAdj.length)];}return ret;}@Overridepublic String toString() {return "" + age + ":" + (isAlive ? "live" : "dead");}public Animal feed(ArrayList<Animal> neighbor) {return null;}protected void longerLife(int inc) {ageLimit += inc;}}

狐狸[子类](Fox)

package animal;import java.awt.Graphics;import java.awt.Color;
import java.util.ArrayList;import cell.Cell;/*** *Fox实现接口Cell,使Fox对象能间接传给Field*/
public class Fox extends Animal implements Cell {public Fox() {super(20, 4);}@Override // 实现接口Cell中的draw()public void draw(Graphics g, int x, int y, int size) {int alpha = (int) ((1 - getAgePercent()) * 255);g.setColor(new Color(0, 0, 0, alpha));g.fillRect(x, y, size, size);}@Overridepublic Animal breed() {Animal ret = null;if (isBreedable() && Math.random() < 0.05) {ret = new Fox();}return ret;}@Overridepublic String toString() {return ("Fox:" + super.toString());}@Overridepublic Animal feed(ArrayList<Animal> neighbor) {  //狐狸进食增加寿命Animal ret = null;if (Math.random() < 0.2) {ret = neighbor.get((int) (Math.random() * neighbor.size()));longerLife(2);}return ret;}
}

兔子[子类](Rabbit)

package animal;import java.awt.Color;
import java.awt.Graphics;import cell.Cell;public class Rabbit extends Animal implements Cell {public Rabbit() {super(10, 2); // *寿命&&生育年龄}@Overridepublic void draw(Graphics g, int x, int y, int size) {int alpha = (int) ((1 - getAgePercent()) * 255);g.setColor(new Color(255, 0, 0, alpha));g.fillRect(x, y, size, size);}@Overridepublic Animal breed() {Animal ret = null;if (isBreedable() && Math.random() < 0.12) {ret = new Rabbit();}return ret;}@Overridepublic String toString() {return "Rabbit" + super.toString();}
}

相关:
Java:Swing

Java:接口(狐狸和兔子)相关推荐

  1. java写 狐狸找兔子_狐狸找兔子(java 版)

    围绕着山顶有10个洞,一只狐狸和一只兔子住在各自的洞里.狐狸想吃掉兔子.一天,兔子对狐狸说:"你想吃我有一个条件,先把洞从1-10编上号,你从10号洞出发,先到1号洞找我:第二次隔1个洞找我 ...

  2. java写 狐狸找兔子_狐狸找兔 算法分析

    题目: 围绕着山顶有10个洞,一只兔子和一只狐狸住在各自的洞里,狐狸总想吃掉兔子,一天兔子对狐狸说,你想吃我有一个条件,你先把洞编号1到10,你从第10洞出发,先到第1号洞找我,第二次隔一个洞找我,第 ...

  3. 翁恺老师 狐狸和兔子练习

    习题描述 狐狸.兔子都有年龄: 到达一定年龄上限会自然死亡: 狐狸随机吃掉周围一只兔子: 狐狸.兔子可以随机生一只小的放在旁边格子: 如果不吃不生,狐狸.兔子可以随机向旁边格子移一步会随机吃掉 Ani ...

  4. Java 接口(interface)的用途和好处

    http://write.blog.csdn.net/postedit/41129935 首先不懂什么是interface的可以参考这里 http://blog.csdn.net/nvd11/arti ...

  5. 狐狸吃兔子模型元胞自动机

    下载地址 原博客地址 项目介绍 狐狸吃兔子模型元胞自动机 标签 Java.JavaGUI.元胞机 技术工具选型 Java.JavaGUI.元胞机 安装与使用 导入到IDEA或者Eclipse 配置JD ...

  6. Java接口对Hadoop集群的操作

    Java接口对Hadoop集群的操作 首先要有一个配置好的Hadoop集群 这里是我在SSM框架搭建的项目的测试类中实现的 一.windows下配置环境变量 下载文件并解压到C盘或者其他目录. 链接: ...

  7. 推荐一个 Java 接口快速开发框架

    欢迎关注方志朋的博客,回复"666"获面试宝典 今天给小伙伴们介绍一个Java接口快速开发框架-magic-api 简介 magic-api 是一个基于 Java 的接口快速开发框 ...

  8. java接口如何定义常量 c_在Java接口中怎样访问定义的常量呢?

    java接口是一系列方法的声明,是一些方法特征的集合,一个接口只有方法的特征没有方法的实现,因此这些方法可以在不同的地方被不同的类实现,而这些实现可以具有不同的行为(功能).那么我们在Java接口中怎 ...

  9. Java接口和Java抽象类

    Java接口和Java抽象类有太多相似的地方,又有太多特别的地方,究竟在什么地方,才是它们的最佳位置呢?把它们比较一下,你就可以发现了. 1.Java接口和Java抽象类最大的一个区别,就在于Java ...

最新文章

  1. 面向对象三大特征——继承
  2. 【工具】公网临时大文件传输工具
  3. Spring注解大全(示例详解)
  4. 从杂技表演到日剧BGM(r12笔记第23天)
  5. 10- vue django restful framework 打造生鲜超市 -用户登录和手机注册(中)
  6. Android之Android studio如何解决Multiple dex files define Landroid/support/a(文件重复引用错误)
  7. [初级]Java命令学习系列(六)——jinfo
  8. android custom toast,Android自定义Toast
  9. linux将视频导入到iphone,如何将 IPhone 的文件导入 Linux
  10. mysql souece 慢_Mysql InnoDB在linux下用source命令执行sql脚本速度慢的问题解决
  11. VC2008以资源形式实现多语言版本
  12. Windows8(2012) 如何改变登录界面上难看的头像,任意换!
  13. 【收山之作】用yourdiary为例 学习KRKR2 XP3加密静态分析
  14. 安卓学习之路-RecyclerView的简单用法
  15. 中兴f460光猫资料
  16. eyoucms使用入门 一
  17. SELECT list is not in GROUP BY clause and contains nonaggregated column 异常
  18. 计算机制图如何绘制太极图,太极图,如何用PS绘制太极图?
  19. crf graph matlab_如何评价 Vicarious 在 Science 上提出基于概率图模型(PGM)的 RCN 模型?...
  20. 别用老派交易员眼光看市场回调

热门文章

  1. access自动编号怎么解除_Access字段中“自动编号”类型不能再改回来的解决方法...
  2. 三分钟默哀,你想了什么?
  3. LightningChart出现闪电图全黑问题应该如何解决
  4. 聊聊我的成长--数据库初学过程--MySQL的安装与配置
  5. jquery设置video的宽度_jQ效果:jQuery和css自定义video播放控件
  6. 有什么计算机可以拆分数字,汇总:WPS表技能-在单元格中拆分文本和数字
  7. wince 蓝牙驱动(1) .
  8. 怎样在往犀牛里导入线框(矢量图线框)
  9. 设置PreferenceFragment主题
  10. MVC调用部分视图PartialView