我们有这样的情况
class Pole extends Thread
{
JButton pole;
Plansza p;
Pole neighbours[] = new Pole[4];
public Pole(Plansza p)
{
this.p = p;
pole = new JButton();
int r,g,b;
r=p.rndColor();
g=p.rndColor();
b=p.rndColor();
pole.setBackground(new Color(r,g,b));
}
public Pole()
{
;
}
public void run()
{
while(true)
{
Thread.yield();
try
{
Thread.sleep((int)p.rndTime());
}
catch(InterruptedException e)
{
;
}
if(p.rnd.nextDouble()<=1-p.p)
setNeighboursColor();
if(p.rnd.nextDouble()<=p.p)
setRandomColor();
}
}
public void setRandomColor()
{
synchronized(this)
{
int r,g,b;
r = p.rndColor();
g = p.rndColor();
b = p.rndColor();
pole.setBackground(new Color(r,g,b));
}
}
public void setNeighboursColor()
{
synchronized(this)
{
int r,g,b;
Color c0 = neighbours[0].pole.getBackground();
Color c1 = neighbours[1].pole.getBackground();
Color c2 = neighbours[2].pole.getBackground();
Color c3 = neighbours[3].pole.getBackground();
r = (int)(c0.getRed() + c1.getRed() + c2.getRed() + c3.getRed())/4;
g = (int)(c0.getGreen() + c1.getGreen() + c2.getGreen() + c3.getGreen())/4;
b = (int)(c0.getBlue() + c1.getBlue() + c2.getBlue() + c3.getBlue())/4;
Color nc = new Color(r,g,b);
pole.setBackground(nc);
}
}
}
我已经编辑了问题并粘贴了我的代码,所以现在每个 Pole(Field) 与其他 4 个 Pole 对象的邻居关系可能更清楚一点,所以我们有很多这样的对象,每个都是不同的线程,它们可以从他们的邻居并将其自身颜色更改为邻居颜色的算术平均值。