Question

JAVA. Threading the Game of Life Write a Java program to implement the Game of Life,...

JAVA. Threading the Game of Life

Write a Java program to implement the Game of Life, as defined by John Conway:

Any live cell with fewer than two live neighbors dies, as if caused by under-population.

Any live cell with two or three live neighbors lives on to the next generation.

Any live cell with more than three live neighbors dies, as if by overpopulation.

Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

Your program should use a 20 x 20 grid, and accept the initial grid configuration from a text file named "startinggrid.txt", in a form similar to the following (this example would be for a 4 x 4 grid):

OOOO

OXXO

OXXO

OOOO

Where ‘X’ indicates and inhabited square and ‘O’ indicates an empty square. The last line of the text file (the 21st line) will contain a single integer, indicating the number of generations to compute, and show the final configuration in the same format as the input.

****THIS IS AN EXERCISE IN THREADING. USE A SEPARATE THREAD FOR EACH SQUARE IN YOUR GRID!****

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code:


import java.io.File;
import java.util.Scanner;

/**
*
* @author pc
*/
//Implement Runnable in this class MyThread to overwrite the run method from Runnable
class MyThread implements Runnable
{
private char grid[][],inter[][];
int x, y;
//initialize all the variables in the constructor like square index , grid,inter
public MyThread(int x,int y,char [][]grid,char [][]inter)
{
this.x=x;
this.y=y;
this.grid=grid;
this.inter=inter;
}
//find the status for x,y square for next generation
public boolean makeAlive()
{
int neigh=0;
for(int i=x-1;i<=x+1;i++)
{
for(int j=y-1;j<=y+1;j++)
{
if((i!=x || j!=y) && i>=0 && j>=0 && i<20 && j<20 && grid[i][j]=='X')
{
neigh++;
}
}
}
//if this sqare is dead and it has exact three neighbur then make it alive
if(grid[x][y]=='O' && neigh==3)
return true;
if(grid[x][y]=='X' && (neigh==2||neigh==3))//if it is alive and it has either 2 or 4 neighbours then keep it alive for next generation
return true;
return false;//otherwise make it dead
}
//every thread on calling start() willl call run() method and will update value in intermediate grid(inter) by extracting input from grid[][]
@Override
public void run() {
boolean alive=makeAlive();
if(alive)//if it is supposed to be alive for next generation then mak it alive in next generation
inter[x][y]='X';
else
inter[x][y]='O';
}
}

class GameofLife
{
//to store grid
private char grid[][]=new char[20][20];
//to store intermediate values for next generation
private char inter[][]=new char[20][20];
//read file into grid and generation value
public int readFile()
{
int index=0,gen=1;
try{
File file=new File("E:\\startinggrid.txt");
Scanner sc=new Scanner(file);
while(sc.hasNext())
{
String str=sc.next();
//if length is 20 then read it in array
if(str.length()==20)
{
for(int j=0;j<20;j++)
{
grid[index][j]=str.charAt(j);
  
}
index++;
}
else{
gen=Integer.parseInt(str);
break;
}
}
sc.close();
}catch(Exception e)
{
System.out.println(e);
}
return gen;//return gen
}
//copy inter into grid at end of each generation
public void copyInterIntoGrid()
{
for(int i=0;i<20;i++)
{
for(int j=0;j<20;j++)
{
grid[i][j]=inter[i][j];
}
}
}
//process data for generation one at a time
public void process()
{
//create 20*20 thread for each square
Thread t[]=new Thread[400];
int index=0;//index
//instantiate thread
for(int i=0;i<20;i++)
{
for(int j=0;j<20;j++){
t[index] = new Thread(new MyThread(i,j,grid,inter));
t[index].start();//start
index++;
}
}
try{
//keep this main thread on hold untill all the other threads finish their work
for(int i=0;i<400;i++)
t[i].join();
}catch(Exception e)
{
System.out.println(e);
}
copyInterIntoGrid();//copy inter into grid
}
public static void main(String[] args) {
GameofLife gof=new GameofLife();
int gen=gof.readFile();
//process for each generation
for(int i=0;i<gen;i++)
{
gof.process();
}
//printing process
System.out.println("Final output after at last generation");
for(int i=0;i<20;i++)
{
for(int j=0;j<20;j++)
{
System.out.print(String.valueOf(gof.grid[i][j]));
}
System.out.println("");
}
}
  
  
}

Input File (startinggrid.txt):

OOOOOOOOOXXXXXOOOXXO
OOOOOOOOOXXXXXOOOXXO
OOXXXXOOOXXXXXOOOXXO
OOOOOOOOOXXXXXOOOXXO
OOOOOOOOOXXXXXOOOXXO
OOOOXXXOOXXOOXOOOXXO
OOOOOOOOOXXXXXOOOXXO
OOOOOOOOOXXXXXOOOXXO
OOOOOOOOOXXOOXXOXXXO
OOOOOOOOOXXXXXOOOXXO
OOOOOOOOOXXXXXOOOXXO
OXXOOOOOOXXXXXOOOXXO
OOOOOOOOOXXXXXOOOXXO
OOOOOOOOOXXXXXOOOXXO
OOOOOOOOOXXXXXOOOXXO
OOOOOOOOOXXXXXOOOXXO
XOXOOOOOOXXXXXOOOXXO
OOOOOXXXOXXXXXOOOXXO
OOOOOOOOOXXXXXOOOXXO
XXXXXXXXXXXXXXOOOXXO
1

Add a comment
Know the answer?
Add Answer to:
JAVA. Threading the Game of Life Write a Java program to implement the Game of Life,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write this Game of Life program in Java. The Game of Life is a well-known mathematical...

    Write this Game of Life program in Java. The Game of Life is a well-known mathematical game that gives rise to amazingly complex behavior, although it can be specified by a few simple rules. Here are the rules. The game is played on a rectangular board. Each square can be either empty or occupied. At the beginning, you can specify empty and occupied cells using 1's and 0's; then the game runs automatically. In each generation, the next generation is...

  • Option 2: Conwav's Game of Life Your task is to write a program that plays Conway's...

    Option 2: Conwav's Game of Life Your task is to write a program that plays Conway's Game of Life (for details and ex amples, see https://en.vikipedia.org/wiki/Convay's.Game of Life). The basic gam ts played on each generation, each cell changes according to the following instructions: nal grid of square cells, each of which is either alive or dead. With 1. Any dead cell with exactly three live neighbors (out of its eight nearest neighbors) comes to life [reproduction]. 2. Any live...

  • Write this Game of Life program in Java. The Game of Life is a well-known mathematical...

    Write this Game of Life program in Java. The Game of Life is a well-known mathematical game that gives rise to amazingly complex behavior, although it can be specified by a few simple rules. Here are the rules. The game is played on a rectangular board. Each square can be either empty or occupied. At the beginning, you can specify empty and occupied cells using 1's and 0's; then the game runs automatically. In each generation, the next generation is...

  • I am really struggling with how to approach this program. Conway's Game of life, whereby, 1....

    I am really struggling with how to approach this program. Conway's Game of life, whereby, 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by over-population. 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. Submit...

  • Write a program that consists of a 10 by 10 game board, with 10 generations. Project...

    Write a program that consists of a 10 by 10 game board, with 10 generations. Project The Game of Life The life game consists of a board with size of NxN cells and cells are occupied by creatures. Each cell can have at most one creature. The surrounding cells are called the neighbors of this cell. Each game state is called "generation". The game progresses from one generation to the next according to the following rules: A creature that has...

  • Objective: Write a program that implements the Game of Life cellular automata system invented by John...

    Objective: Write a program that implements the Game of Life cellular automata system invented by John Conway. 1. Create two game grids of size at least 50x50. These grid cells can be either Boolean or integer. In the following, I’ll refer to these as gridOne and gridTwo. 2. Set all cells in both grids to false. 3. Start by initializing gridOne. Allow the user to specify two different ways of initializing the grid: 1) by specifying a pattern file to...

  • Please use C++, thank you! The life game consists of a board with size of NxN cells and cells are occupied by creatures. Each cell can have at most one creature. The surrounding cells are called the...

    Please use C++, thank you! The life game consists of a board with size of NxN cells and cells are occupied by creatures. Each cell can have at most one creature. The surrounding cells are called the neighbors of this cell Each game state is called "generation". The game progresses from one generation to the next according to the following rules: A creature that has more than 3 neighbors- dies of crowding. Its cell will be empty in the next...

  • Hi, PLEASE I need the code in C programming, (USING THE SAME INPUT AND OUTPUT FORMAT...

    Hi, PLEASE I need the code in C programming, (USING THE SAME INPUT AND OUTPUT FORMAT DESCRIBED BELOW). Title: Game of Life Description In this assignment, you will code a simulation called "Game of Life". It is a very famous 'game' and the formed the basis of an entire field of simulation models called "cellular automata". Before continuing reading this assignment, I suggest you read a bit more about Game of Life at: https://en.wikipedia.org/wiki/Conway's_Game_of_Life or http://www.math.com/students/wonders/life/life.html (the latter also has...

  • You will write a Java program that implements Conway’s Game of Life, a simple cellular automaton...

    You will write a Java program that implements Conway’s Game of Life, a simple cellular automaton discussed in class. See for example: http://www.bitstorm.org/gameoflife/ Our version has a 10 x 10 grid, numbered like this: 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 The grid is represented by a 10 x 10 2­dimensional integer array. If the grid point (i, j) is "populated", the array element [i][j] contains 1;...

  • I have a question about my assignment. Could you please make program and give me some...

    I have a question about my assignment. Could you please make program and give me some explanation of codes? I need c++ codes. Conway's Game of Life is a game invented by mathematician John Conway in 1970. The rules are as follows: Each cell lives in a cell in a square (make it 10x10) grid. A cell can either be dead or alive. Before you start the game, you need to provide an initial state. You can do this by...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT