0

您好,我正在设计一个基本的 Java“游戏”,您在其中输入数组的长度和大小的起点,然后程序将检查哪个值是真的,它必须遵循下一组规则

  1. 如果小区当前被占用,则仅当恰好一个邻居被占用时才保持被占用;
  2. 如果单元格当前为空,则仅当两个邻居都为空时它才保持为空

到目前为止我的代码有点工作,但它在开始时太快了,这导致规则 1 不起作用

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", " "));

    }
}
}
4

1 回答 1

0

您可以使用更简洁的代码来增加成功的机会。使用这样的额外方法:

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;
}

使用它可以帮助您更清楚地了解您真正想做的事情。

你可以大致这样称呼它:getLivingNeighbors(cellsCurrent[currentG],i)

于 2013-09-15T00:26:19.400 回答