lundi 30 mai 2016

Java - Cleaning up lots of if statements

I'm writing a little project in Java which is similar to the 2048 game, which is pretty much solely based on array manipulation. I wrote a solution to a problem I had, and it works perfectly, however the code is incredibly messy. If anybody could please help with cleaning it up, maybe by using a different technique or something, it is just lots of if statements.

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

Every if/else if statement here is crucial as it takes care of all situations. I'm not asking for somebody to go through and clean it all up, but if I could just have some pointers or examples that'd be great.

Thanks guys

Aucun commentaire:

Enregistrer un commentaire