我在Java中编写了一个类似于2048游戏的小项目,它几乎完全基于数组操作。我为我遇到的问题编写了一个解决方案,它运行得很好,但是代码非常混乱。如果有人可以帮忙清理它,可能是通过使用不同的技术或其他东西,它只是很多if语句。
// This bit gets rid of the empty tiles between numbers.
// Eg {2,2,0,4} becomes {2,2,4,0}.
for(int i =1; i<row.length; i++) {
if(row[i-1] == 0)
{
row[i-1] = row[i];
row[i] = 0;
}
}
for(int j=row.length-1; j>=1; j--) {
if(row[j-1] == 0 ) {
row[j-1] = row[j];
row[j] = 0;
}
}
int nonEmpty = 0; // Count the number of non empty tiles
for(int i=0; i<row.length; i++) {
if(row[i] != 0)
nonEmpty++;
}
if(nonEmpty == 2) {
if(row[1] == row[0]) {
row[0] *= 2;
row[1] = 0;
}
}
else if(nonEmpty == 3) {
if(row[1] == row[0]) {
row[0] *= 2;
row[1] = row[2];
row[2] = 0;
}
else if(row[2] == row[1]) {
row[1] *= 2;
row[2] = 0;
}
}
else if(nonEmpty==4) {
if(row[1] == row[0]) {
row[0] *= 2;
row[1] = 0;
if(row[2] == row[3]) {
row[2] *= 2;
row[3] = 0;
}
}
else if(row[2] == row[1]) {
row[1] *= 2;
row[2] = row[3];
row[3] = 0;
}
else if(row[3] == row[2]) {
row[2] *= 2;
row[3] = 0;
}
}
// Get rid of 0s between numbers again.
for(int i =1; i<row.length; i++) {
if(row[i-1] == 0)
{
row[i-1] = row[i];
row[i] = 0;
}
}
for(int j=row.length-1; j>=1; j--) {
if(row[j-1] == 0 ) {
row[j-1] = row[j];
row[j] = 0;
}
}
此处的每个if / else if语句都是至关重要的,因为它可以处理所有情况。我并没有要求有人通过并清理它,但如果我能提供一些指示或示例,那就太棒了。
谢谢你们
答案 0 :(得分:1)
试试这个
void set(int indexFrom, int... values) {
for (int v : values)
row[indexFrom++] = v;
}
并重写
if(row[1] == row[0]) {
row[0] *= 2;
row[1] = row[2];
row[2] = 0;
}
else if(row[2] == row[1]) {
row[1] *= 2;
row[2] = 0;
}
到
if (row[1] == row[0])
set(0, row[0] * 2, row[2], 0);
else if (row[2] == row[1])
set(1, row[1] * 2, 0);