I'm making a simple game of life 10x10 board using dashes, and filling them in with x's when the user inputs the corresponding row and column. I have everything I need for this except option 3, which is to 'show the next generation' by these rules:
- A new cell is born on an empty square if it is surrounded by exactly three neighbors
- A cell dies of overcrowding if it is surrounded by four or more neighbors
- It dies of loneliness if it is surrounded by zero or one neighbor
- If a cell has two or three neighbors, it survives to the next generation
import java.util.Scanner; public class GameOfLife { public static void main (String[] args) { final int ROWS = 10; final int COLUMNS = 10; Scanner scan = new Scanner(System.in); String[][] board = new String[ROWS][COLUMNS]; for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = "-"; boolean done = false; while (!done) { System.out.println("1 - Add a being"); System.out.println("2 - Show current board"); System.out.println("3 - Show next generation"); System.out.println("4 - Clear board"); System.out.println("5 - Exit"); int option = scan.nextInt(); if (option == 1) { System.out.print("Enter row for being (1 through 9): "); int i = scan.nextInt(); System.out.print("Enter column for being: "); int j = scan.nextInt(); board[i][j] = "x"; } else if (option == 2) { for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLUMNS; j++) System.out.print(board[i][j]); System.out.println(); } } else if (option == 3) { int neighbors = 0; int x = ROWS, y = COLUMNS; if (x >= 1 && y >=1 && x < COLUMNS && y < ROWS) { if (board[x][y++].equals(1)) {neighbors++;} if (board[x][y--].equals(1)) {neighbors++;} if (board[x++][y].equals(1)) {neighbors++;} if (board[x++][y++].equals(1)) {neighbors++;} if (board[x++][y--].equals(1)) {neighbors++;} if (board[x--][y--].equals(1)) {neighbors++;} if (board[x--][y++].equals(1)) {neighbors++;} } } else if (option == 4) { for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = "-"; } else if (option == 5) { done = true; } else System.out.println("Invalid input."); } System.exit(0); } }
I have it so it finds the neighbors but I'm not sure how to go about deleting or keeping certain x's.
For example, how to go from this:
---------- ---------- ---------- ---xxx---- ---------- ---------- ---------- ---------- ---------- ----------
To this:
---------- ---------- ----x----- ----x----- ----x----- ---------- ---------- ---------- ---------- ----------