packagegra;importjava.io.BufferedReader;importjava.io.File;importjava.io.FileReader;importjava.io.IOException;publicclassLife{privatechar[][]gameBoard=newchar[12][20];privateintnumberOfRounds=0;publicbooleanreadDataFromFile(Filefile){try(BufferedReaderbr=newBufferedReader(newFileReader(file))){Stringline;intarrayIndex=0;while((line=br.readLine())!=null){for(inti=0;i<20;i++){gameBoard[arrayIndex][i]=line.charAt(i);}arrayIndex++;}}catch(IOExceptione){e.printStackTrace();returnfalse;}returntrue;}publicvoidprintGameBoard(){for(inti=0;i<gameBoard.length;i++){for(intj=0;j<gameBoard[i].length;j++){System.out.print(gameBoard[i][j]);}System.out.println();}}publicintgetNumberOfNeighbours(introw,intcolumn){intneighboursCount=0;for(inti=-1;i<2;i++){for(intj=-1;j<2;j++){if(gameBoard[row+i][column+j]=='X')neighboursCount++;}}returnneighboursCount;}publicbooleanhasTwoOrThreeNeighbours(introw,intcolumn){intnumberOfNeighbours=getNumberOfNeighbours(row,column);returnnumberOfNeighbours==2||numberOfNeighbours==3;}publicbooleanhasThreeNeighbours(introw,intcolumn){returngetNumberOfNeighbours(row,column)==3;}publicvoidnextRound(){// Starts from 1 because number of neighbours add -1// to row and to column in the first placefor(inti=1;i<gameBoard.length-1;i++){for(intj=1;j<gameBoard[i].length-1;j++){if(gameBoard[i][j]=='X'&&hasTwoOrThreeNeighbours(i,j)){gameBoard[i][j]='X';}elseif(gameBoard[i][j]=='.'&&hasThreeNeighbours(i,j)){gameBoard[i][j]='X';}else{gameBoard[i][j]='.';}}}numberOfRounds++;}publicintgetNumberOfRounds(){returnnumberOfRounds;}}
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.