android - 康威的生命游戏应用生命规则问题 Android

标签 android

我正在尝试为我正在参加的编程类(class)创建适用于 Android 的康威生命游戏。我能够毫无问题地在板上绘制初始图案。当我想创造下一代时,我遇到了问题。

这是我创造下一代的方法。

public void createNextGen(){
    int neighbors;
    int[][] nextGen = new int[HEIGHT][WIDTH];

    for(int h = 0; h < HEIGHT; h++){
        for(int w = 0; w < WIDTH; w++){
            neighbors = calcNeighbors(h, w);
                if(currentLife[h][w] == 1){
                    if(neighbors < 2){
                        nextGen[h][w] = 0;
                    } else if (neighbors > 3){
                        nextGen[h][w] = 0;
                    } else {
                        nextGen[h][w] = 1;
                    }
                } else if (currentLife[h][w] == 0){
                    if(neighbors == 3){
                        nextGen[h][w] = 1;
                    } else {
                        nextGen[h][w] = 0;
                    }
                }
        }
    }

    copyGrid(nextGen, currentLife);
}

这是我计算邻居的方法。

private int calcNeighbors(int x, int y){
    int total = 0;

    for (int h = -1; h <= +1; h++) {
        for (int w = -1; w <= +1; w++) {
            if (currentLife[(HEIGHT + (y + h)) % HEIGHT][(WIDTH + (x + w)) % WIDTH] != 0) {
                total++;
            }
        }
    }
    return total;
}

这是从网格开始的初始模式。

public void initGrid() {
    resetGrid(currentLife);

    currentLife[8][(WIDTH / 2) - 1] = 1;
    currentLife[8][(WIDTH / 2) + 1] = 1;
    currentLife[9][(WIDTH / 2) - 1] = 1;
    currentLife[9][(WIDTH / 2) + 1] = 1;
    currentLife[10][(WIDTH / 2) - 1] = 1;
    currentLife[10][(WIDTH / 2)] = 1;
    currentLife[10][(WIDTH / 2) + 1] = 1;

}

我认为问题不在于我的 onDraw 方法,因为这个初始模式按预期显示。它的后代到处都是跳跃,我想我一定是在 createNextGeneration 方法中做错了什么。

我使用整数 1 表示一个 ALIVE 细胞,用整数 0 表示一个 DEAD 细胞。

非常感谢任何帮助或指导。

最佳答案

只是参数顺序的一个简单错误 - 您将 y,x 发送到 calcNeighbors 方法,该方法需要 x,y.

calcNeighbors(h, w);
...

private int calcNeighbors(int x, int y)
...

我建议您将方法更改为:

private int calcNeighbors(int y, int x)

因为您在其余代码中使用了 h, w (y, x) 顺序。

关于android - 康威的生命游戏应用生命规则问题 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29881687/

相关文章:

php - 布伦特里付款 : Merchant is not set up to accept PayPal

android - 在 DrawerLayout 中添加 RecyclerView

android - 我的应用程序中显示的空 map

android - 如何在 Facebook Android SDK 中支持较早的 API 版本?

android - 手电筒需要哪些权限?

android - Spotify 安卓 SDK : Play offline tracks

android - Jetpack Compose - 修饰符参数是否应该仅应用于最外层/最顶层 View ?

java - 我可以通过 Android Java 解析 Apple pList 形式的 XML 吗?

android - 如何在特定时间内锁定 Android 设备?

Android Retrofit api链接介绍