|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
在ruby里才是一切皆对象。当然我不并不是很了解ruby,但是ruby确实是将语法简化得很好。
上面要先容的程序的前身是由LarryOBrien原创的一些代码,并以由CraigReynolds于1986年体例的“Boids”程序为基本,事先是为了演示庞大性实际的一个特别成绩,名为“凸显”(Emergence)。
这儿要到达的方针是经由过程为每种植物都划定少量复杂的划定规矩,从而传神地再现植物的群聚举动。每一个植物都能看到看到全部情况和情况中的其他植物,但它只与一系列四周的“群聚同伴”打交道。植物的挪动基于三个复杂的引诱举动:
(1)分开:制止当地群聚同伴过于拥堵。
(2)偏向:服从当地群聚同伴的广泛偏向。
(3)聚合:朝当地群聚同伴组的中央挪动。
更庞大的模子乃至能够包含停滞物的要素,植物能预知和制止与停滞抵触的才能,以是它们能环绕情况中的流动物体自在举动。除此之外,植物也大概有本人的特别方针,这大概会形成群体按特定的路径行进。为简化会商,制止停滞和方针征采的要素并未包含到这里创建的模子中。
只管盘算机自己对照大略,并且接纳的划定规矩也相称复杂,但了局看起来是实在的。也就是说,相称传神的举动从这个复杂的模子中“凸显”出来了。
程序以分解到一同的使用程序/程序片的情势供应:
- //:FieldOBeasts.java
- //Demonstrationofcomplexitytheory;simulates
- //herdingbehaviorinanimals.Adaptedfrom
- //aprogrambyLarryOBrienlobrien@msn.com
- importjava.awt.*;
- importjava.awt.event.*;
- importjava.applet.*;
- importjava.util.*;
- classBeast{
- int
- x,y,//Screenposition
- currentSpeed;//Pixelspersecond
- floatcurrentDirection;//Radians
- Colorcolor;//Fillcolor
- FieldOBeastsfield;//WheretheBeastroams
- staticfinalintGSIZE=10;//Graphicsize
- publicBeast(FieldOBeastsf,intx,inty,
- floatcD,intcS,Colorc){
- field=f;
- this.x=x;
- this.y=y;
- currentDirection=cD;
- currentSpeed=cS;
- color=c;
- }
- publicvoidstep(){
- //Youmovebasedonthosewithinyoursight:
- Vectorseen=field.beastListInSector(this);
- //Ifyourenotoutinfront
- if(seen.size()>0){
- //Gatherdataonthoseyousee
- inttotalSpeed=0;
- floattotalBearing=0.0f;
- floatdistanceToNearest=100000.0f;
- BeastnearestBeast=
- (Beast)seen.elementAt(0);
- Enumeratione=seen.elements();
- while(e.hasMoreElements()){
- BeastaBeast=(Beast)e.nextElement();
- totalSpeed+=aBeast.currentSpeed;
- floatbearing=
- aBeast.bearingFromPointAlongAxis(
- x,y,currentDirection);
- totalBearing+=bearing;
- floatdistanceToBeast=
- aBeast.distanceFromPoint(x,y);
- if(distanceToBeast<distanceToNearest){
- nearestBeast=aBeast;
- distanceToNearest=distanceToBeast;
- }
- }
- //Rule1:Matchaveragespeedofthose
- //inthelist:
- currentSpeed=totalSpeed/seen.size();
- //Rule2:Movetowardstheperceived
- //centerofgravityoftheherd:
- currentDirection=
- totalBearing/seen.size();
- //Rule3:Maintainaminimumdistance
- //fromthosearoundyou:
- if(distanceToNearest<=
- field.minimumDistance){
- currentDirection=
- nearestBeast.currentDirection;
- currentSpeed=nearestBeast.currentSpeed;
- if(currentSpeed>field.maxSpeed){
- currentSpeed=field.maxSpeed;
- }
- }
- }
- else{//Youareinfront,soslowdown
- currentSpeed=
- (int)(currentSpeed*field.decayRate);
- }
- //Makethebeastmove:
- x+=(int)(Math.cos(currentDirection)
- *currentSpeed);
- y+=(int)(Math.sin(currentDirection)
- *currentSpeed);
- x%=field.xExtent;
- y%=field.yExtent;
- if(x<0)
- x+=field.xExtent;
- if(y<0)
- y+=field.yExtent;
- }
- publicfloatbearingFromPointAlongAxis(
- intoriginX,intoriginY,floataxis){
- //ReturnsbearingangleofthecurrentBeast
- //intheworldcoordiantesystem
- try{
- doublebearingInRadians=
- Math.atan(
- (this.y-originY)/
- (this.x-originX));
- //Inversetanhastwosolutions,soyou
- //havetocorrectforotherquarters:
- if(x<originX){
- if(y<originY){
- bearingInRadians+=-(float)Math.PI;
- }
- else{
- bearingInRadians=
- (float)Math.PI-bearingInRadians;
- }
- }
- //Justsubtracttheaxis(inradians):
- return(float)(axis-bearingInRadians);
- }catch(ArithmeticExceptionaE){
- //Divideby0errorpossibleonthis
- if(x>originX){
- return0;
- }
- else
- return(float)Math.PI;
- }
- }
- publicfloatdistanceFromPoint(intx1,inty1){
- return(float)Math.sqrt(
- Math.pow(x1-x,2)+
- Math.pow(y1-y,2));
- }
- publicPointposition(){
- returnnewPoint(x,y);
- }
- //Beastsknowhowtodrawthemselves:
- publicvoiddraw(Graphicsg){
- g.setColor(color);
- intdirectionInDegrees=(int)(
- (currentDirection*360)/(2*Math.PI));
- intstartAngle=directionInDegrees-
- FieldOBeasts.halfFieldOfView;
- intendAngle=90;
- g.fillArc(x,y,GSIZE,GSIZE,
- startAngle,endAngle);
- }
- }
- publicclassFieldOBeastsextendsApplet
- implementsRunnable{
- privateVectorbeasts;
- staticfloat
- fieldOfView=
- (float)(Math.PI/4),//Inradians
- //Deceleration%persecond:
- decayRate=1.0f,
- minimumDistance=10f;//Inpixels
- staticint
- halfFieldOfView=(int)(
- (fieldOfView*360)/(2*Math.PI)),
- xExtent=0,
- yExtent=0,
- numBeasts=50,
- maxSpeed=20;//Pixels/second
- booleanuniqueColors=true;
- ThreadthisThread;
- intdelay=25;
- publicvoidinit(){
- if(xExtent==0&&yExtent==0){
- xExtent=Integer.parseInt(
- getParameter("xExtent"));
- yExtent=Integer.parseInt(
- getParameter("yExtent"));
- }
- beasts=
- makeBeastVector(numBeasts,uniqueColors);
- //Nowstartthebeastsa-rovin:
- thisThread=newThread(this);
- thisThread.start();
- }
- publicvoidrun(){
- while(true){
- for(inti=0;i<beasts.size();i++){
- Beastb=(Beast)beasts.elementAt(i);
- b.step();
- }
- try{
- thisThread.sleep(delay);
- }catch(InterruptedExceptionex){}
- repaint();//Otherwiseitwontupdate
- }
- }
- VectormakeBeastVector(
- intquantity,booleanuniqueColors){
- VectornewBeasts=newVector();
- Randomgenerator=newRandom();
- //UsedonlyifuniqueColorsison:
- doublecubeRootOfBeastNumber=
- Math.pow((double)numBeasts,1.0/3.0);
- floatcolorCubeStepSize=
- (float)(1.0/cubeRootOfBeastNumber);
- floatr=0.0f;
- floatg=0.0f;
- floatb=0.0f;
- for(inti=0;i<quantity;i++){
- intx=
- (int)(generator.nextFloat()*xExtent);
- if(x>xExtent-Beast.GSIZE)
- x-=Beast.GSIZE;
- inty=
- (int)(generator.nextFloat()*yExtent);
- if(y>yExtent-Beast.GSIZE)
- y-=Beast.GSIZE;
- floatdirection=(float)(
- generator.nextFloat()*2*Math.PI);
- intspeed=(int)(
- generator.nextFloat()*(float)maxSpeed);
- if(uniqueColors){
- r+=colorCubeStepSize;
- if(r>1.0){
- r-=1.0f;
- g+=colorCubeStepSize;
- if(g>1.0){
- g-=1.0f;
- b+=colorCubeStepSize;
- if(b>1.0)
- b-=1.0f;
- }
- }
- }
- newBeasts.addElement(
- newBeast(this,x,y,direction,speed,
- newColor(r,g,b)));
- }
- returnnewBeasts;
- }
- publicVectorbeastListInSector(Beastviewer){
- Vectoroutput=newVector();
- Enumeratione=beasts.elements();
- BeastaBeast=(Beast)beasts.elementAt(0);
- intcounter=0;
- while(e.hasMoreElements()){
- aBeast=(Beast)e.nextElement();
- if(aBeast!=viewer){
- Pointp=aBeast.position();
- Pointv=viewer.position();
- floatbearing=
- aBeast.bearingFromPointAlongAxis(
- v.x,v.y,viewer.currentDirection);
- if(Math.abs(bearing)<fieldOfView/2)
- output.addElement(aBeast);
- }
- }
- returnoutput;
- }
- publicvoidpaint(Graphicsg){
- Enumeratione=beasts.elements();
- while(e.hasMoreElements()){
- ((Beast)e.nextElement()).draw(g);
- }
- }
- publicstaticvoidmain(String[]args){
- FieldOBeastsfield=newFieldOBeasts();
- field.xExtent=640;
- field.yExtent=480;
- Frameframe=newFrame("FieldOBeasts");
- //Optionallyuseacommand-lineargument
- //forthesleeptime:
- if(args.length>=1)
- field.delay=Integer.parseInt(args[0]);
- frame.addWindowListener(
- newWindowAdapter(){
- publicvoidwindowClosing(WindowEvente){
- System.exit(0);
- }
- });
- frame.add(field,BorderLayout.CENTER);
- frame.setSize(640,480);
- field.init();
- field.start();
- frame.setVisible(true);
- }
- }///:~
复制代码
只管这并不是对CraigReynold的“Boids”例子中的举动完善重现,但它却展示出了本人独占的诱人以外。经由过程对数字举行调剂,便可举行周全的修正。至于与这类群聚举动有关的更多的情形,人人能够会见CraigReynold的主页——在谁人中央,乃至还供应了Boids一个公然的3D展现版本:
http://www.hmt.com/cwr/boids.html
为了将这个程序作为一个程序片运转,请在HTML文件中设置下述程序片标记:
- <applet
- code=FieldOBeasts
- width=640
- height=480>
- <paramname=xExtentvalue="640">
- <paramname=yExtentvalue="480">
- </applet>
复制代码
你通过从书的数量和开发周期及运行速度来证明:net网页编程和ruby要比java简单。 |
|