aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/model/LineAlgorithm.java
blob: 0d0364b7b04dddcf73ba4a0f956c5c17c8abfc4a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package model;

/**
 * Created by loic on 21/09/16.
 */
public class LineAlgorithm {



    private int score=0;

    public int[] mergeRight(int[] line){

        line=gravityRight(line);

        for(int i=(line.length-1);i>=0;i--){
            if(i>0){
                int a=line[i];
                int b=line[i-1];
                if(a==b && a!=-1){
                    line[i]=a+b;
                    line[i-1]=-1;
                    i--;
                    this.score+=(a+b);
                }
            }
        }

        line=gravityRight(line);

        return line;
    }


    private static int[] gravityRight(int[] line){
        for(int i=0;i<line.length;i++) {
            for (int j = (line.length - 1); j >= 0; j--) {
                int a = line[j];
                if (j > 0) {
                    int b = line[j - 1];
                    if (a == -1) {
                        line[j] = b;
                        line[j - 1] = -1;
                    }
                }
            }
        }
        return line;
    }


    public static int[] clearLine(int[] line){
        for(int i=0;i<line.length;i++){
            line[i]=-1;
        }
        return line;
    }

    public static int[] reverseLine(int[] line){
        int[] reversedLine=new int[line.length];

        int j=0;
        for(int i=(line.length-1);i>=0;i--){
            reversedLine[j]=line[i];
            j++;
        }

        return reversedLine;
    }

    public static boolean linesIsEquals(int[] line1, int[] line2){
        if(line1.length!=line2.length){
            return false;
        }
        else {
            for (int i=0;i<line1.length;i++){
                if(line1[i]!=line2[i]){
                    return false;
                }
            }
        }
        return true;

    }

    public static void printLine(int[] line){
        System.out.println("----------");
        for(int i=0;i<line.length;i++){
            System.out.print(line[i]);
        }
        System.out.println("\n----------");

    }

    public int getScore() {
        return score;
    }

}