I recently coded a very basic version of Conway's Game of Life using arrays of 1's and 0's. Now, I am trying to create a grid of rectangles using java.awt that will fill in the rectangles according to which cells are "alive" (as represented by a 1) in the array. Basically, I want the filled rectangles to correspond with the 1s in the array my program prints. I am pretty unfamiliar with graphics and haven't even been able to add a rectangle to a frame or panel. If you guys could even just explain the basics of Java graphics, or offer any information that would be amazing.
Here is my code so far:
import java.awt.*;
import java.awt.geom.*;
public class GameofLife {
public static void main(String[] args){
int [][] array = new int [17][17];
Frame main = new Frame("Conway's Game of Life");
main.setSize(400,400);
Panel panel = new Panel();
array[2][4]=1;
array[2][5]=1;
array[2][6]=1;
array[2][10]=1;
array[2][11]=1;
array[2][12]=1;
array[7][4]=1;
array[7][5]=1;
array[7][6]=1;
array[7][10]=1;
array[7][11]=1;
array[7][12]=1;
array[9][4]=1;
array[9][5]=1;
array[9][6]=1;
array[9][10]=1;
array[9][11]=1;
array[9][12]=1;
array[14][4]=1;
array[14][5]=1;
array[14][6]=1;
array[14][10]=1;
array[14][11]=1;
array[14][12]=1;
array[4][2]=1;
array[5][2]=1;
array[6][2]=1;
array[10][2]=1;
array[11][2]=1;
array[12][2]=1;
array[4][7]=1;
array[5][7]=1;
array[6][7]=1;
array[4][9]=1;
array[5][9]=1;
array[6][9]=1;
array[4][14]=1;
array[5][14]=1;
array[6][14]=1;
array[10][7]=1;
array[11][7]=1;
array[12][7]=1;
array[10][9]=1;
array[11][9]=1;
array[12][9]=1;
array[10][14]=1;
array[11][14]=1;
array[12][14]=1;
int [][] end = new int [array.length][array[0].length];
printArray(array);
System.out.println("");
System.out.println("");
int a=0;
while(a<4){
for(int i=1; i<=array.length-2; i++)
{
for(int j=1; j<=array[0].length-2; j++)
{
int counter = surround(array,i,j);
if(array[i][j]==1 && counter<=2)
{
end[i][j]=0;
}
if(array[i][j]==1 && counter==3)
{
end[i][j]=1;
}
if(array[i][j]==1 && counter>4)
{
end[i][j]=0;
}
if(array[i][j]==0 && counter==3)
{
end[i][j]=1;
}
if(array[i][j]==1 && counter==4)
{
end[i][j]=1;
}
}
}
printArray(end);
System.out.println("");
System.out.println("");
a++;
for(int i=0; i<array.length; i++)
{
for(int j=0; j<array[0].length; j++)
{
array[i][j]=end[i][j];
end[i][j]=0;
}
}
}
}
public static int surround(int[][] initial, int i, int j){
int[][] surrounding = {{initial[i-1][j-1],initial[i-1][j],initial[i-1][j+1]},
{initial[i][j-1],initial[i][j],initial[i][j+1]},
{initial[i+1][j-1],initial[i+1][j],initial[i+1][j+1]}};
int counter = 0;
for(int a=0; a<=2; a++)
{
for(int b=0; b<=2; b++)
{
if(surrounding[a][b]==1)
{
counter ++;
}
}
}
return counter;
}
public static void printArray(int[][] input)
{
for(int x =0; x<input.length; x++)
{
for(int y=0; y< input[0].length; y++)
{
System.out.print(input[x][y]);
}
System.out.println("");
}
}
}
Thank you so much for any help and sorry to code dump :/.
Aucun commentaire:
Enregistrer un commentaire