狐狸和兔子围绕山洞c语言,弎问笔录30 之 狐狸和兔子(二)

现在把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 

for(int col = 0; col 

double probability = Math.random();

if(probability 

field.place(row, col, new Fox());

}else if(probability 

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 

step();

view.repaint();

try {

Thread.sleep(200);

} catch (Exception e) {

e.printStackTrace();

}

}

}

public void step() {

for(int row = 0; row 

for(int col = 0; 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);

List listofRabbit = 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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值