Hello guys. I gotta make this game called game of "Life".
I've tried but i'm kinda stuck because of a semantic mistake. I'll show you my code of the prototype!
CODE
/* Write an animation that lets the computer play the game of ``Life.''
The game goes as follows: the user specifies the size of game board,
a matrix, and also gives the starting positions of where some pebbles(``cells'') live.
Every second, the computer updates the board, creating and removing cells,
according to the following rules:
- an empty board position that is surrounded by exactly three cells gets
a cell placed on it. (The new cell ``comes to life.'')
- a board position occupied by a cell retains the cell if the position was surrounded
by exactly 2 other cells. (Otherwise the cell disappears---``dies''---due to
``loneliness'' or ``overcrowding.'')
Here is an example of two seconds of the animation on a 5-by-5 board, where an X denotes a cell and . denotes an empty space:
.X.XX ...XX ...XX
X...X ....X ....X
XXX.. => X.X.. => ...X.
..X.X X.X.. ..XX.
X...X ...X. .....
*/
import java.awt.*;
import javax.swing.*;
public class LifeFinal
{ char[][] c = new char[5][5];
char[][] m = new char[5][5];
public LifeFinal()
{ c[0][0] = '.'; c[0][1] = 'x'; c[0][2] = '.'; c[0][3] = 'x'; c[0][4] = 'x';
c[1][0] = 'x'; c[1][1] = '.'; c[1][2] = '.'; c[1][3] = '.'; c[1][4] = 'x';
c[2][0] = '.'; c[2][1] = '.'; c[2][2] = 'x'; c[2][3] = '.'; c[2][4] = '.';
c[3][0] = '.'; c[3][1] = '.'; c[3][2] = 'x'; c[3][3] = '.'; c[3][4] = 'x';
c[4][0] = 'x'; c[4][1] = '.'; c[4][2] = '.'; c[4][3] = '.'; c[4][4] = '.';
}
public void save()
{ m = c; }
public void print()
{ for(int i = 0; i < m.length; i++)
{ for(int j = 0; j < m[0].length; j++)
{ System.out.print(m[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
public void check_it()
{ c = m;
int three = 0;
int two = 0;
for(int i = 0; i < c.length; i++)
{ for(int j = 0; j < c[0].length; j++)
{ three = 0;
two = 0;
if(i>0 && j>0 && i<c.length-1 && j<c[0].length-1)
{ three = 0;
two = 0;
for(int p = i-1; p <= i+1; p++)
{ for(int q = j-1; q <= j+1; q++)
{ if(!((p == i) && (q == j)))
{
if(c[i][j] == '.' && c[p][q] == 'x') { three+=1; }
else if(c[i][j] == 'x' && c[p][q] == 'x') { two+=1; }
}
}
}
if(c[i][j] == '.' && three == 3) { m[i][j] = 'x'; }
else if(c[i][j] == 'x' && two != 2) { m[i][j] = '.'; }
}
}
}
}
public static void main(String[] args)
{ LifeFinal f = new LifeFinal();
f.save();
f.print();
f.check_it();
f.print();
}
}
I just checked the inside terms of the matrix, just to not get out of bounds cause I checked them by using algorithm i+1, i-1 etc... but it's not changing how it should the inner terms of the matrix(inner terms: from c[1][1] to c[3][3]).
The result after one check looks like this:
. x . x x
x . . . x
. . x . .
. . x . x
x . . . .
. x . x x
x x . . x
. . x . .
. x x x x
x . . . .
Maybe I'm not saving the matrix right. If anyone could analyze it i would appreciate! Thnx
** Edit **