Conway game of life, Next generation not printing well - java

I am working on Conway game of college problem. I have been able to print the first generation and the second but when it comes to the following ones they all copy the second generation. I was wondering if y'all can help me out.
public void computeNextGeneration(int generation)
{
char[][] newBoard = new char[board.length][board[0].length];
for(int i = 0; i < board.length; i++)
{
for(int j = 0; j < board[0].length; j++)
{
if(board[i][j] == '0' && numOfNeighbors(i,j) == 3)
{
newBoard[i][j] = 'X';
}
else if(board[i][j] == 'X' && numOfNeighbors(i,j) < 2)
{
newBoard[i][j] = '0';
}
else if(board[i][j] == 'X' && numOfNeighbors(i,j) >3)
{
newBoard[i][j] = '0';
}
else if(board[i][j] == 'X' && numOfNeighbors(i,j) == 2 || numOfNeighbors(i,j) == 3)
{
newBoard[i][j] = 'X'; //change x to 0
}
else{
newBoard[i][j] +=board[i][j];
}
}
}
for (int i = 0; i < newBoard.length; i++)
{
for(int j = 0; j < newBoard[0].length; j++)
{
System.out.print(newBoard[i][j]);
}
System.out.println();
}
}

After you calculate the new board you have to assign it back to the class field board. Add as the last line of computeNextGeneration board = newboard.

You start counting your generations from 2 for(int i = 2; i <= gen; i++) as the constructor doesnt generate a starting generation this should be a 0.

Related

How do I check if a position in my vector of vectors is out of bounds?

I have a vector of vectors filled with characters from a text file. It is essentially a simple outbreak simulator, with 'i' characters being infected, and 's' characters being susceptible to infection. The point is to run through the matrix and if it comes across an 'i', it then changes all 's' around it into an 'i'. I run into a problem when checking the elements around it due to checking positions out of the bounds on the edges of the matrix. Is there a way to check these bounds in my if statements?
Here is the code:
for (int i = 0; i < population.size(); i++) {
for(int j = 0; j < population[i].size(); j++) {
if(population[i][j] == 'i') {
if(population[i-1][j] == 's') {
population[i-1][j] = 'i';
}
if(population[i-1][j+1] == 's') {
population[i-1][j+1] = 'i';
}
if(population[i][j+1] == 's') {
population[i][j+1] = 'i';
}
if(population[i+1][j+1] == 's') {
population[i+1][j+1] = 'i';
}
if(population[i+1][j] == 's') {
population[i+1][j] = 'i';
}
if(population[i+1][j-1] == 's') {
population[i+1][j-1] = 'i';
}
if(population[i][j-1] == 's') {
population[i][j-1] = 'i';
}
}
}
}
Instead of directly referencing a particular array entry, you could do something like the following:
void checkForInfectionAndInfectIfNeeded(int i, int j) {
for (int row = -1; row <= 1; row++) {
for (int column = -1; column <=1; column++) {
infect(i + row, j + column);
}
}
}
void infect(int i, int j) {
if (i < 0 || i >= population.size() || j < 0 || j >= population[j].size()) {
return;
} else {
population[i][j] = 'i';
}
}
This way, the infect method is the only that checks the boundaries, and you replace your long list of manually checking the surrounding locations with two loops.

How do I use a variable that is declared inside of a for loop outside the loop?

I'm creating ATARI BREAKOUT, using the acm.graphics library and I'm trying to access a "brick" outside of my for loop to delete it. I can't figure out any other way to create the bricks without the for loop. Help?
GRect brick = new GRect(brickwidth, brickheight);
for(j = 1; j <= nrows; j++) {
for(i = 0; i < bricksperrow; i++) {
brick.setLocation(i*(brickwidth + brickSep) + 1, brickoffset + j*(brickheight + brickSep));
if(j == 1 || j == 2) {
brick.setColor(Color.RED);
brick.setFilled(true);
}
else if(j == 3 || j == 4) {
brick.setColor(Color.ORANGE);
brick.setFilled(true);
}
else if(j == 5 || j == 6) {
brick.setColor(Color.YELLOW);
brick.setFilled(true);
}
else if(j == 7 || j == 8) {
brick.setColor(Color.GREEN);
brick.setFilled(true);
}
else if(j == 9 || j == 10) {
brick.setColor(Color.CYAN);
brick.setFilled(true);
}
add(brick);
}
}
I guess you want to create many bricks in for loop.
You are doing it wrong, per iteration you are just changing a position of one brick.
You need to create a new brick per iteration and save its reference into some structure preferably a matrix of [nrows, bricksperrow] dimensions.
Here's how:
GRect[][] bricks = new GRect[nrows][bricksperrow];
for(j = 1; j <= nrows; j++) {
for(i = 0; i < bricksperrow; i++) {
bricks[j - 1][i].setLocation(
i*(brickwidth + brickSep) + 1,
brickoffset + j*(brickheight + brickSep));
if(j == 1 || j == 2) {
brick.setColor(Color.RED);
brick.setFilled(true);
}
else if(j == 3 || j == 4) {
brick.setColor(Color.ORANGE);
brick.setFilled(true);
}
else if(j == 5 || j == 6) {
brick.setColor(Color.YELLOW);
brick.setFilled(true);
}
else if(j == 7 || j == 8) {
brick.setColor(Color.GREEN);
brick.setFilled(true);
}
else if(j == 9 || j == 10) {
brick.setColor(Color.CYAN);
brick.setFilled(true);
}
add(bricks[j - 1][i]);
}
}
This way you can have global matrix of bricks from where you can delete any entry.

Connect four multithread design - Homework

I'm trying to make a connect four game sumulation.
The program should have three threads - player 1, player 2 and game controller.The game controller thread has the responsibility of transfering control from one player to the other, has to monitor if a thread takes more than 5 second to execute, check if there is a winner and so on.
The interface the player classes must implement is:
public interface Player extends Runnable {
public int nextMove(int otherPlayerLastMove);
public void gameOver();
}
The method nextMove return the number of the column the player puts his next token in, and takes as a paramether the number of the column the oposing player put his last token.
The method gameOver must be called from the game controller thread to indicate end of the game and releasing of all resources from the player.
I don't have a problem with implementing the logic of the game it self, but I'm faceing a problem design wise. I just can't put my mind on what classes do I need and how they should interact. The obvious classes are PlayerImpl and GameController - which I think should keep the table for the game ( a 2D char array) and implement the checking logic. Or do I need a third class which contains only the table and to which the other two have access?
The basic code is here:
public class GameController implements Runnable{
private static char [][] table;
private void initTable(){
table = new char[6][7];
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
table[i][j] = '*';
}
}
}
public void printTable(){
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
System.out.print(table[i][j] + " ");
}
System.out.println();
}
}
private char checkWinner(){
//check for horizontal line
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < 4; j++) {
if ( table[i][j] != '*' && table[i][j+1] != '*' && table[i][j+2] != '*' && table[i][j+3] != '*' &&
table[i][j] == table [i][j+1] && table[i][j+1] == table[i][j+2] && table[i][j+2] == table[i][j+3])
return table[i][j];
}
}
//check for vertical line
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 7; j++) {
if ( table[i][j] != '*' && table[i+1][j] != '*' && table[i+2][j] != '*' && table[i+3][j] != '*' &&
table[i][j] == table [i+1][j] && table[i+1][j] == table[i+2][j] && table[i+2][j] == table[i+3][j])
return table[i][j];
}
}
// left to right diagonals
for (int i = 0; i < 3; i++) {
for (int j = 3; j < 7; j++) {
if ( table[i][j] != '*' && table[i+1][j-1] != '*' && table[i+2][j-2] != '*' && table[i+3][j-3] != '*' &&
table[i][j] == table [i+1][j-1] && table[i+1][j-1] == table[i+2][j-2] && table[i+2][j-2] == table[i+3][j-3])
return table[i][j];
}
}
// right to left diagonals
for (int i = 0; i < 2; i++) {
for (int j = 3; j >=0; j--) {
if ( table[i][j] != '*' && table[i+1][j+1] != '*' && table[i+2][j+2] != '*' && table[i+3][j+3] != '*' &&
table[i][j] == table [i+1][j+1] && table[i+1][j+1] == table[i+2][j+2] && table[i+2][j+2] == table[i+3][j+3])
return table[i][j];
}
}
return 0;
}
public void addToken(int column, char token){
for (int i = table.length ; i >= 0 ; i--) {
if(table[i][column] == '*'){
table[i][column] = token;
break;
}
}
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
So how would you make the design of such a problem? An explanation or just a UML diagram would be great. Thanks in advance :)
The fact that you have methods on your Runnable tells me you are kinda going for an actor model.
This just means conceptually, you have the players and a controller, all having their own thread (they are all "actors"), and communicate through sending messages. In your case, you are doing that by accepting method calls (nextMove, gameOver).
Here is something that gets your code closer to an actor pattern.
class User extends Runnable {
int userId;
Controller controller;
Queue<Message> msgQueue;
void nextMove(int whoMoved, int whatMove){
msgQueue.offer(new NextMove(whoMoved, whatMove));
}
void gameOver(){
msgQueue.offer(new GameOver());
}
run(){
while(true){
Message msg = msgQueue.poll();
if(msg != null){
// deal with it
// Maybe send message to controller
controller.nextMove(new NextMove(userId, 4));
} else {
// Do something else, like talking to user
// sleep to avoid hogging CPU
Thread.sleep(10);
}
}
}
}
The code has many problems (like that fact that it will scale terribly, abstraction not being great etc. etc.), but I hope it illustrates the approach. Typical real actor model implementation use green threads to tackle scalability and provide standardised way to send and receive messages (e.g. see Akka, Erlang).

(ADDED) Noughts and Crosses game. While loop

for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
visBoard[i][j] = "[ ]";
board[i][j] = 0;
check[i][j] = false;
}
}for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
System.out.print(visBoard[i][j]);
}System.out.print("\n");
}
//Getting Names
System.out.println("Player 1 - Enter your name");
play1 = sc.nextLine();
System.out.println("Player 2 - Enter your name");
play2 = sc.nextLine();
//
moves = 0;
symbol = " X ";
do{
do{
//Get Coords
System.out.println("X Coordinate");
xcoord = sc.nextInt() -1;
System.out.println("Y Coordinate");
ycoord = sc.nextInt() -1;
if(check[xcoord][ycoord] == true){
System.out.println("Not a valid move!");
}
}while(check[xcoord][ycoord] == true);
//Making move
check[xcoord][ycoord] = true;
visBoard[xcoord][ycoord] = symbol;
if(symbol.equals(" X ")){
board[xcoord][ycoord] = 1;
}else if(symbol.equals(" O ")){
board[xcoord][ycoord] = 5;
}else{
System.out.println("You've messed up James");
}
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
System.out.print(visBoard[i][j]);
}System.out.print("\n");
}
//Check if game has won
//columns
total = 0;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
total = total + board[j][i];
}if(total == 15 || total == 3){
gamewon = true;
}
}total = 0;
//rows
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
total = total + board[i][j];
}if(total == 15 || total == 3){
gamewon = true;
}
}total = 0;
//diagonals
for(int i = 0; i < 3; i++){
total = total + board[i][i];
}if(total == 15 || total == 3){
gamewon = true;
}total = 0;
diag = 2;
for(int i = 0; i < 3; i++){
total = total + board[i][diag];
diag--;
}if(total == 15 || total == 3){
gamewon = true;
}
moves++;
if(gamewon == false){
if(moves == 9){
System.out.println("Game has been drawn! No one wins!");
}else{
mod = moves % 2;
if(mod == 0){
symbol = " X ";
}else{
symbol = " O ";
}
}
}
}while(gamewon == false || moves != 9);
if(gamewon == true){
if(symbol.equals(" X ")){
System.out.println("Winner is "+play1);
}else{
System.out.println("Winner is "+play2);
}
}else{
System.out.println("Game is drawn");
}
}
}
This is a further question from a previous question I had. This game won't end until moves reaches 9 even though the while loop should stop once someone has won. The boolean will turn true, but it will continue to loop.
How do I fix this issue with keeping the while condition, and possibly without using breaks?
You need an and not an or
while(gamewon == false && moves != 9);
Reading that to yourself it says while there is no winner and we are not at move 9. However it's usually better form to code your loops to check that you haven't exceeded a bound rather than you have hit the bound exactly, and it is also nicer to simply test the boolean directly so the following is more stylish:
while(!gamewon && moves < 9);
while(gamewon == false || moves != 9)....
This tells the loop to execute while game isnt won, or moves are not 9. For it to end, BOTH conditions need to change, the game needs to be ended AND moves needs to be 9.
Change your || operator to &&. This way the game will keep going while the game is not won AND the moves is not 9. It seems a bit strange but if you can follow the logic, you'll see that you need the AND operator.
Therefore, you're looking for:
while(gamewon == false && moves != 9)

Messed up recursion code for a board game

What I have to do here is to count the number of adjacent white blocks (in 2's) on a square board which is made up of random black(0's) and white(1's) blocks. The white blocks have to be at i+1,j || i-1,j || i,j+1 || i,j-1. Technically diagonals are not counted. I have provided an example below:
[1 0 1]
[1 1 0]
[0 1 0]
Here count == 3 (0,0)(1,0) and (1,0)(1,1) and (1,1)(2,1)
Here is my code:
public int count = 0;
boolean count(int x, int y, int[][] mat)
{
if(x<0 || y<0)
return false;
if(mat[x][y] == 0)
return false;
for(int i = x; i<mat.length; i++)
{
for(int j = y; j<mat[0].length; j++)
{
if(mat[i][j] == 1)
{
mat[i][j] = 0;
if(count(i-1,j,mat))
count++;
if(count(i,j-1,mat))
count++;
if(count(i+1,j,mat))
count++;
if(count(i,j+1,mat))
count++;
}
}
}
return true;
}
Short explanation of what I am trying to do here: I am going about finding 1's on the board and when I find one I change it to a 0 and check its up,down,left,right for a 1. This goes on till I find no adjacent 1's. What is the thing I am missing here? I kind of have a feeling I am looping unnecessarily.
here's a solution without recursion
for(int i = 0; i < mat.length; i++) {
for(int j = 0; j < mat[i].length; j++) {
if(mat[i][j] == 1) {
if(i < mat.length - 1 && mat[i+1][j] == 1) {
count++;
}
if(j < mat[i].length - 1 && mat[i][j+1] == 1) {
count++;
}
}
}
I don't think recursion is the right answer as you should only being going one step deep (to find the adjacent value). Instead just loop through the elements looking to the right and down. Don't look up or left as twain mentioned so that you don't double count matches. Then is it simply:
for (i=0; i<max; i++)
for (j=0; j<max; j++)
if (array[i][j] == 1){
if (i<max-1 && array[i+1][j] == 1) count++;
if (j<max-1 && array[i][j+1] == 1) count++;
}

Categories