Конвей в игре Life Loop Logic

Когда я запускаю свою программу, мой вывод остается прежним после первого запуска цикла while. Почему testgrid не устанавливается на новое значение copygrid после каждого прохода?

Цикл находится прямо под комментарием // Выполнить снова для поколений х

package assignment2;
/**
 * @author jaw209
 * Date: 2/24/14
 * Purpose: Conway's Game of Life Program
 */
import java.io.*;
import java.util.*;
import javax.swing.*;

public class Assignment2 {

    private static int livecount;
    static char[][] copygrid = new char[30][30];


    public static void main(String[] args) throws FileNotFoundException {

        String inputfile;
        String output;
        String generations;
        char[][] testgrid = new char[30][30];
//Fills array copygrid with -        
        for(int i = 0; i < 30; i++){
            for(int x= 0; x < 30; x++){
                copygrid[i][x] = '-';
                }
            }

//Input file = L:\Java 2\Assignment2\Sample input.txt  

//Inputs from file to char array        
        inputfile = JOptionPane.showInputDialog ("Where is the input file?   Ex: C:\\users\\public\\desktop\\input.txt ");
        Scanner input = new Scanner (new FileReader(inputfile)); 
        char[] chararray = new char[904];
        String allvalues = null;
        do {
            String values = input.next();
            allvalues = allvalues + values;
        }
        while(input.hasNextLine());
        chararray = allvalues.toCharArray();

//Reads values in chararray into multidimensional array       
        char[][] grid1 =  new char[30][30]; 
        int i = 4;
        for(int row = 0; row < 30; row++){
            for(int col = 0; col < 30; col++){
                grid1 [row][col] = chararray[i]; 
                i++;
                    System.out.print(grid1[row][col]);
                        }
                    System.out.println();
                    }

//Finds how many generations should be calculated        
        generations = JOptionPane.showInputDialog ("How many generations should be calculated?");
        int gens = Integer.parseInt(generations);

//Prompts for output file
        output = JOptionPane.showInputDialog ("Where is the output file?");
        PrintWriter out = new PrintWriter(output); 

//Runs the cycle once      
        for (int row = 0; row < 30; row++){
            for (int col = 0; col < 30; col ++){
                if (status(grid1[row][col])){
                    liveSurrounding(grid1, row, col);
                    moves(row, col);
                }
                else if (!status(grid1[row][col])){
                    //run 3 checker
                  if (liveSurrounding(grid1, row, col) == 3){
                  copygrid[row][col] = 'X';
                  }     
                }

            }
        }
        System.out.println();
        System.out.print("Generation: 1");
        printCopy();

//Run again for x generations
        int count = 1;
        while (count <= gens){
        //copies old value of copygrid into new array    
            for(int e = 0; e < 30; e++){
                for(int f = 0; f < 30; f++){
                testgrid[e][f] = copygrid[e][f];
                }
            }  

       //Reset copy grid to blank
            for(int v = 0; v < 30; v++){
            for(int x= 0; x < 30; x++){
                copygrid[v][x] = '-';
                }
            }

       //Run through generation methods
            for (int row = 0; row < 30; row++){
            for (int col = 0; col < 30; col ++){
                if (status(testgrid[row][col])){
                    liveSurrounding(testgrid, row, col);
                    moves(row, col);
                }
                else if (!status(testgrid[row][col])){
                    //run 3 checker
                  if (liveSurrounding(testgrid, row, col) == 3){
                  copygrid[row][col] = 'X';
                  }     
                }
            }
        }

        System.out.println();
        int oneoff = count+1;
        System.out.print("Generation: " + oneoff);
        printCopy();
        count++;
        }

    }


//Check to see if cell is live or dead    
    public static boolean status(char value){  
            if (value == 'X'){
                return true;
            } else {
            return false;
            }
        }

//See if neighbor is alive or dead    
    public static int liveSurrounding(char [][] grid, int a, int b){

        livecount = 0;

        if (a > 0 && grid[a-1][b] == 'X'){
            livecount++;
        }
        if (a > 0 && b < grid.length - 1 && grid[a-1][b+1] == 'X'){
            livecount++;
        } 
        if (b < grid.length - 1 && grid[a][b+1] == 'X'){
            livecount++;
        }
        if (a < grid.length - 1 && b < grid.length - 1 && grid[a+1][b+1] == 'X'){
            livecount++;
        }
        if (a < grid.length - 1 && grid[a+1][b] == 'X'){
            livecount++;
        }
        if (a < grid.length - 1 && b > 0 && grid[a+1][b-1] == 'X'){
            livecount++;
        }
        if (b > 0 && grid[a][b-1] == 'X'){
            livecount++;
        }
        if (a > 0 && b > 0 && grid[a-1][b-1] == 'X'){
            livecount++;
        }
        else {
        grid[a][b] = '-';
        }
        return livecount;
    }   

//Adjust alive cells for each condition    
    public static char[][] moves(int a, int b){

        switch(livecount){
            case 0: copygrid[a][b] = 'X'; break;
            case 1: copygrid[a--][b] = 'X'; copygrid[a][b] = '-'; break;
            case 2: copygrid[a][b++] = 'X'; copygrid[a][b] = '-'; break;
            case 3: copygrid[a][b--] = 'X'; copygrid[a][b] = '-'; break;
            case 4: copygrid[a++][b] = 'X'; copygrid[a][b] = '-'; break;
            case 5: copygrid[a--][b++] = 'X'; copygrid[a][b] = '-'; break;
            case 6: copygrid[a++][b--] = 'X'; copygrid[a][b] = '-'; break; 
            case 7: copygrid[a--][b--] = 'X'; copygrid[a][b] = '-';  break;
            case 8: copygrid[a++][b++] = 'X';copygrid[a][b] = '-';  break;
            default:
        }

                    return copygrid;         
    }    

//method to print out formatted copygrid    
    public static void printCopy(){
for (int row = 0; row < 30; row++){
    System.out.println();
    for (int col = 0; col < 30; col++){
            System.out.print(copygrid[row][col]);
            }
        }
System.out.println();
    }

}

1 ответ

Вероятно, это не вся проблема, но я бы с большим подозрением отнесся к этому коду:

//Adjust alive cells for each condition
public static char[][] moves(int a, int b){

    switch(livecount){
        case 0: copygrid[a][b] = 'X'; break;
        case 1: copygrid[a--][b] = 'X'; copygrid[a][b] = '-'; break;
        case 2: copygrid[a][b++] = 'X'; copygrid[a][b] = '-'; break;
        case 3: copygrid[a][b--] = 'X'; copygrid[a][b] = '-'; break;
        case 4: copygrid[a++][b] = 'X'; copygrid[a][b] = '-'; break;
        case 5: copygrid[a--][b++] = 'X'; copygrid[a][b] = '-'; break;
        case 6: copygrid[a++][b--] = 'X'; copygrid[a][b] = '-'; break;
        case 7: copygrid[a--][b--] = 'X'; copygrid[a][b] = '-';  break;
        case 8: copygrid[a++][b++] = 'X';copygrid[a][b] = '-';  break;
        default:
    }

    return copygrid;
}

Я бы порекомендовал написать несколько тестов, чтобы убедиться, что он делает то, что вы думаете. Я подозреваю, что это не так.

Насколько я помню, следующее состояние ячейки зависит от ее текущего состояния и количества живых соседей. Этот код, похоже, влияет на состояние разных ячеек в зависимости от количества живых соседей для конкретной ячейки. Он также устанавливает большинство этих ячеек на "X", а затем немедленно устанавливает их снова на "-".

Также кажется, что существует некоторая путаница относительно того, используете ли вы поля или возвращаете значения здесь и в других местах вашего кода.

Другие вопросы по тегам