java - 康威的生命游戏

标签 java

我的问题是 boolean isLive = false; 为什么将其指定为 false?我见过非常相似的例子,但我从来没有想过要理解它。谁能解释一下这条线在做什么?

/**
 * Method that counts the number of live cells around a specified cell

 * @param board 2D array of booleans representing the live and dead cells

 * @param row The specific row of the cell in question

 * @param col The specific col of the cell in question

 * @returns The number of live cells around the cell in question

 */

public static int countNeighbours(boolean[][] board, int row, int col)
{
    int count = 0;

    for (int i = row-1; i <= row+1; i++) {
        for (int j = col-1; j <= col+1; j++) {

            // Check all cells around (not including) row and col
            if (i != row || j != col) {
                if (checkIfLive(board, i, j) == LIVE) {
                    count++;
                }
            }
        }
    }

    return count;
}

/**
 * Returns if a given cell is live or dead and checks whether it is on the board
 * 
 * @param board 2D array of booleans representing the live and dead cells
 * @param row The specific row of the cell in question
 * @param col The specific col of the cell in question
 * 
 * @returns Returns true if the specified cell is true and on the board, otherwise false
 */
private static boolean checkIfLive (boolean[][] board, int row, int col) {
    boolean isLive = false;

    int lastRow = board.length-1;
    int lastCol = board[0].length-1;

    if ((row >= 0 && row <= lastRow) && (col >= 0 && col <= lastCol)) {             
        isLive = board[row][col];
    }

    return isLive;
}

最佳答案

这只是默认值,如果测试(if 子句)得到验证,则可能会更改。

它定义了板外的单元格不活动的约定。

这可以写成:

private static boolean checkIfLive (boolean[][] board, int row, int col) {

    int lastRow = board.length-1;
    int lastCol = board[0].length-1;

    if ((row >= 0 && row <= lastRow) && (col >= 0 && col <= lastCol)) {             
        return board[row][col];
    } else {
        return false;
    }
}

关于java - 康威的生命游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12856811/

相关文章:

java - Selenium WebDriver 基本 java 项目出错

java - Java 中的 OrientDB 并发图形操作

java - 连续监听 AWS SQS 消息的模式

java - 如何在没有终端的情况下在其他linux计算机上打开java程序?

java - Jetty VS Tomcat Maven 插件 - 我应该使用哪一个?

java - "Spring transaction"和 "Hibernate transaction"有什么区别

java - 通过 processbuilder 进行多进程通信,卡住在 BufferedReader() 的 readline() 处

java - 在 Java 中获取声明类

java - ESAPI - 获取具有禁止依赖项的 NoClassDefFoundError (LoggerFactory)

java - 如何使用带有多个搜索词的 appengine 搜索 api 进行搜索?