import java.util.Random;
import java.awt.*;
import java.awt.image.BufferedImage;
public class Level
{
private boolean[][] map;
private int width, height;
private Random rnd;
private boolean drawn;
private BufferedImage bImage;
private boolean built;
public Level(int x, int y)
{
map = new boolean[x][y];
width = x;
height = y;
rnd = new Random();
if (Game.RANDOMIZED)
{
for(int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
map[i][j] = rnd.nextBoolean();
}
}
}
}
private int getAmountOfNeighbors(int x, int y)
{
int n = 0;
if ((x < width) && (y < height) && (y >= 0) && (x >= 0))
{
for(int i = x-1; i <= x+1; i++)
{
for(int j = y-1; j <= y+1; j++)
{
if(getState(i, j))
{
n++;
}
}
}
}
return n;
}
private boolean getState(int x, int y)
{
if ((x < width) && (y < height) && (y >= 0) && (x >= 0))
{
return map[x][y];
}
else if (Game.RANDOMIZED)
{
return false;
}
else
{
return true;
}
}
private boolean getNextState(int x, int y)
{
if ((x < width) && (y < height) && (y >= 0) && (x >= 0))
{
if(getState(x, y))
{
switch(getAmountOfNeighbors(x, y) - 1)
{
case 2: case 3: {return true;}
default: {return false;}
}
}
else
{
if(getAmountOfNeighbors(x, y) == 3)
{
return true;
}
return false;
}
}
return false;
}
private boolean[][] nextStep()
{
boolean[][] mapN = new boolean[width][height];
for(int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
mapN[i][j] = getNextState(i, j);
}
}
return mapN;
}
public synchronized void tick()
{
while(built)
{
try
{
wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
int a = Game.SCALE;
int b = Game.BORDER;
bImage = new BufferedImage(a*width, a*height, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2 = bImage.createGraphics();
g2.setColor(Color.RED);
g2.fillRect(0 , 0, width*a, height*a);
boolean[][] mapN = nextStep();
for(int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
if(map[i][j] != mapN[i][j])
{
map[i][j] = mapN[i][j];
}
if(map[i][j])
{
//g2.setColor(Color.BLACK);
//g2.fillRect(i*a, j*a, a, a);
for(int k = 0; k < a; k++)
{
for(int n = 0; n < a; n++)
{
bImage.setRGB(i*a + k, j*a + n, 0xff000000); //black
}
}
}
}
}
built = true;
notify();
}
public static void black()
{
System.out.println(Integer.toHexString(Color.BLACK.getRGB()));
}
public synchronized void paint(Graphics g)
{
while(!built)
{
try
{
wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
int b = Game.BORDER;
g.drawImage(bImage, b, 3*b, null);
built = false;
notify();
}
}