您好我正在设计一个基本的Java“游戏”,您可以在其中输入数组的长度和大小 然后程序将检查哪个值为真,并且必须遵循下一组规则
我到目前为止所使用的代码有点起作用,但它在开始时太快就会导致规则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", " "));
}
}
}
答案 0 :(得分: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)