Hi All,
I've tried testing my solution and it seems to work, but it doesn't pass the last requirment. When I test it, it accuratelt gives me false or true based on wheter or not the array has changedd Maybe if you could help me figure out what I'm doing wrong. I would really appreciate it.
package com.codegym.games.game2048;
import com.codegym.engine.cell.*;
import java.util.*;
public class Game2048 extends Game {
private static final int SIDE = 4;
private int[][] gameField = new int[SIDE][SIDE];
@Override
public void initialize() {
setScreenSize(SIDE, SIDE);
createGame();
drawScene();
}
private void createGame() {
createNewNumber();
createNewNumber();
/* gameField[0][0] = 1024;
gameField[1][0] = 64;
gameField[0][1] = 2048;
*/
}
private void drawScene() {
/* for(int x = 0; x < gameField.length; x++) {
for(int y = 0; y <gameField.length; y++) {
setCellColor(x, y, Color.LIGHTBLUE);
}
}*/
for(int x= 0; x < gameField.length; x++) {
for(int y = 0; y < gameField.length; y++) {
setCellColoredNumber(x, y, gameField[y][x]);
}
}
}
private void createNewNumber() {
boolean numberAssigned = false;
while(!numberAssigned) {
int cordX = getRandomNumber(SIDE); //generate X coordinates
int cordY = getRandomNumber(SIDE); //generate Y coordiates
if (gameField[cordX][cordY] == 0) { //check if cell is empty
int number = getRandomNumber(10); //generate number 2 or 4
int twoOrFour = 2;
if (number == 9) {
twoOrFour = 4;
}
gameField[cordX][cordY] = twoOrFour;
numberAssigned = true;
}
}
}
private void setCellColoredNumber(int x, int y, int value) {
Color cellColor = getColorByValue(value);
if(cellColor == Color.LIGHTBLUE) {
setCellValueEx(x, y, Color.LIGHTBLUE, "");
} else {
setCellValueEx(x, y, cellColor, Integer.toString(value));
}
}
private Color getColorByValue(int value) {
switch (value) {
case 0:
return Color.LIGHTBLUE;
case 2:
return Color.BLUE;
case 4:
return Color.YELLOW;
case 8:
return Color.GREEN;
case 16:
return Color.DARKBLUE;
case 32:
return Color.PURPLE;
case 64:
return Color.PINK;
case 128:
return Color.LIGHTGREEN;
case 256:
return Color.DARKGREEN;
case 512:
return Color.ORANGE;
case 1024:
return Color.VIOLET;
case 2048:
return Color.GOLD;
default:
return Color.NONE;
}
}
private boolean compressRow(int[] row) {
int[] oldRow = new int[row.length];
System.arraycopy(row, 0, oldRow, 0, row.length - 1);
// int[] oldRow = row.clone();
boolean changed = false;
for(int i = 0; i < row.length; i++) {
if(row[i] == 0) { // is it 0?
int j = i + 1;
while(j < row.length) { //is next number 0?
if(row[j] != 0){ //if not then switch numberAssigned
int switchNumbers = row[i];
row[i] = row[j];
row[j] = switchNumbers;
break;
}
j++; // if yes then check next number
// if no more numbers are not zero finish
}
}
}
// for(int k = 0; k < row.length; k++) {
// if(row[k] != oldRow[k]) {
if(!Arrays.equals(row, oldRow)) {
changed = true;
// break;
}
// }
return changed;
}
}