狐狸和兔子围绕山洞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);
}
}
總結
以上是生活随笔為你收集整理的狐狸和兔子围绕山洞c语言,弎问笔录30 之 狐狸和兔子(二)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android自定义View的多点触控
- 下一篇: 基于spring boot + Myba