简体   繁体   中英

Cell life Game java

Hello i am designing a basic java "game" where you put in a starting true point the length and size of array then the program will check which value is true and it has to follow the next set of rules

  1. if the cell is currently occupied, it remains occupied only if exactly one neighbour is occupied;
  2. it the cell is currently empty, it remains empty only if both neighbours are empty

the code that i have so far kinda works but it puts a true too soon in the beginning which causes rule 1 to not work

import java.util.*;

class Cell
{
public static void main (String[] args)
{int l;
  int g; //number of the generation
  String s, a;//stands for automata
  int p; //position of the true cells
  int currentG; //current generation

  Scanner scanner;
  scanner= new Scanner(System.in);
  a=scanner.next();
  l=scanner.nextInt();
  g=scanner.nextInt();
  s=scanner.next();
  boolean[][] cellsCurrent = new boolean[g][l+2]; 
  currentG=0;
  while(scanner.hasNextInt()){ //put the position values in an array
  p=scanner.nextInt();
  if(p<=l){
  cellsCurrent[currentG][p] = true;
  }
}
s=scanner.next();//ik weet niet echt wat ik anders met die *init_end* moet

 if(a.equals("A")){
   for(currentG=0; currentG<g-1; currentG++){ //for all generations
     for(int i=1; i<l+1; i++){ //for all cells
       if(cellsCurrent[currentG][i] == true && ((cellsCurrent[currentG][i+1] == true && cellsCurrent[currentG][i-1] == false)||(cellsCurrent[currentG][i+1] == false && cellsCurrent[currentG][i-1]  == true ))){ //dit werkt dus nog niet
        cellsCurrent[currentG+1][i] = true;

       }
       else {if (cellsCurrent[currentG][i] == true){
         cellsCurrent[currentG+1][i] = false;
       }}
       if(cellsCurrent[currentG][i] == false && cellsCurrent[currentG][i+1] == false && cellsCurrent[currentG][i-1] == false){
         cellsCurrent[currentG+1][i] = false;
       }
       else{
        cellsCurrent[currentG+1][i] = true; 
       }
     }
   }
}

    for (int i = 0; i < cellsCurrent.length; i++) {

System.out.println(Arrays.toString(cellsCurrent[i]).replace("true", "*")
        .replace("false", " "));

    }
}
}

You can increase your chances of success with cleaner code. Use an extra method like this:

static int getLivingNeighbors (boolean[] arr, int index) {
    int result = 0;
    if (index > 0 && arr[index-1])
        result++;
    if (index < arr.length-1 && arr[index+1])
        result++;
    return result;
}

Using this will help you to get a clearer view on what you really want to do.

You can call it roughly like this: getLivingNeighbors(cellsCurrent[currentG],i)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM