首先,感谢您的到来,并花时间帮助解决问题。
我是一个完整的菜鸟(第3天编程),这解释了为什么我花费了无数时间来试图解决这个问题,但仍然没有想到它:
如何迭代网格(例如使用for循环或while循环),以便新网格替换旧网格,最新网格成为新网格不停?我不熟悉' show()'方法,但我有点工作。
额外问题:如何使用thread.sleep(1000)方法使2个网格在迭代前暂停一秒或其他什么?我想我也应该实现一代计数器,以便用户可以跟踪增长情况。
这是我不完整的代码,可以让您了解问题:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class LifeGrid {
public static boolean[][] gen() throws IOException {
Scanner scanner = new Scanner(new File("seed.txt"));
int rows = 0, columns = 0;
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
if (s.length() > columns) {
columns = s.length();
}
rows++;
}
boolean[][] cells = new boolean[rows][columns + 1];
Scanner scanner1 = new Scanner(new File("seed.txt"));
System.out.println("Original seed pattern:");
for (int r = 0; r < rows; r++) {
String line = scanner1.nextLine();
System.out.println(line);
for (int c = 0; c <= line.length(); c++) {
if (line.charAt(r) == '*') {
cells[r][c] = true;
}
}
}
System.out.println();
return cells;
}
public static boolean[][] nextGen(boolean[][] cells) {
boolean[][] newCells = new boolean[cells.length][cells[0].length];
for (int r = 0; r < cells.length; r++) {
for (int c = 0; c < cells[0].length; c++) {
int num = numNeighbours(cells, r, c);
if (occupiedNext(num, cells[r][c]))
newCells[r][c] = true;
}
}
return newCells;
}
public static void main(String[] args) throws IOException {
boolean[][] cells = gen();
System.out.println("Generation:");
show(cells);
System.out.println("Next Generation:");
cells = nextGen(cells);
show(cells);
System.out.println("Next Next Generation");
cells = nextGen(cells);
show(cells);
System.out.println("Next Next Next Generation");
cells = nextGen(cells);
show(cells);
}
private static boolean inbounds(boolean[][] cells, int r, int c) {
return r >= 0 && r < cells.length && c >= 0 && c < cells[0].length;
}
private static int numNeighbours(boolean[][] cells, int row, int col) {
int num = cells[row][col] ? -1 : 0;
for (int r = row - 1; r <= row + 1; r++)
for (int c = col - 1; c <= col + 1; c++)
if (inbounds(cells, r, c) && cells[r][c])
num++;
return num;
}
public static void show(boolean[][] grid) {
String s = "";
for (boolean[] row : grid) {
for (boolean val : row)
if (val)
s += "*";
else
s += "_";
s += "\n";
}
System.out.println(s);
}
public static boolean occupiedNext(int numNeighbours, boolean occupied) {
if (occupied && (numNeighbours == 2 || numNeighbours == 3))
return true;
else if (!occupied && numNeighbours == 3)
return true;
else
return false;
}
}