java 细胞繁殖问题_模拟一下细胞的繁殖

usingSystem;usingSystem.Drawing;usingSystem.Drawing.Imaging;usingSystem.Windows.Forms;namespaceArtificialLife

{publicpartialclassFormMain : Form

{int[,] Cells;//状态(1生,0死)int[,] CellCounts;//周边细胞数量(最大8个)int[,] Temp;//缓冲(切换生死状态)Bitmap memBitmap;//画布Random rand=newRandom((int)DateTime.Now.Ticks);

System.Windows.Forms.Timer updateTimer;publicFormMain()

{

InitializeComponent();//宽高Width=320;

Height=240;

memBitmap=newBitmap(Width, Height);

Cells=newint[memBitmap.Width, memBitmap.Height];

CellCounts=newint[memBitmap.Width, memBitmap.Height];//初始化,随机决定for(var x=0; x

Cells[x, y]=rand.Next(memBitmap.Width)%3==0?1:0;

Temp=(int[,])Cells.Clone();

updateTimer=newTimer();

updateTimer.Tick+=newEventHandler(updateTimer_Tick);

updateTimer.Interval=1000;

updateTimer.Start();

}voidupdateTimer_Tick(objectsender, EventArgs e)

{

DoCalc();

DoDraw();

}privatevoidDoCalc()

{/*1. 如果一个细胞只有0或1个邻居,它将因为孤独而死;

2. 如果一个细胞有4到8个邻居,它将因为拥挤而死;

3. 如果一个细胞恰有2或者3个邻居,它将继续生存下去;

4. 如果一个空格子恰有3个邻居,将“生”出一个新细胞;*/intnCount=0;//用以统计每个细胞周围的细胞个数for(var x=0; x

{//每个细胞的前后左右八个方向的nCount=0;if(x>0) nCount+=Cells[x-1, y];if(x>0&&y>0) nCount+=Cells[x-1, y-1];if(x0) nCount+=Cells[x, y-1];if(y>0&&x0&&y

CellCounts[x, y]=nCount;//放入计数器if(nCount<2||nCount>3)//决定生死Temp[x, y]=0;if(nCount==3)

Temp[x, y]=1;

}for(var x=0; x

Cells[x, y]=Temp[x, y];

}protectedoverridevoidOnPaint(PaintEventArgs e)

{

DoDraw();

}privatevoidDoDraw()

{//开启编译选项 unsafe+BitmapData bmData=memBitmap.LockBits(newRectangle(0,0, memBitmap.Width, memBitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);intstride=bmData.Stride;

IntPtr Scan0=bmData.Scan0;unsafe{byte*p=(byte*)(void*)Scan0;intnOffset=stride-memBitmap.Width*3;for(inty=0; y

{for(intx=0; x

{//blue = p[0];//green = p[1];//red = p[2];//当周边细胞数越多则颜色越亮p[0]=p[1]=p[2]=(byte)Math.Max(Math.Min(CellCounts[x, y]*30,255),0);if(Cells[x, y]==1) p[0]=255;//生存的细胞p+=3;

}

p+=nOffset;

}

}

memBitmap.UnlockBits(bmData);

Graphics g=this.CreateGraphics();

g.DrawImage(memBitmap, ClientRectangle);

g.Dispose();

}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值