Реализация метода:
private void setCellColoredNumber(int x, int y, int value) {
if (value == 0) {
setCellValueEx(y, x, getColorByValue(value), "");
} else{
setCellValueEx(y, x, getColorByValue(value), String.valueOf(value));
}
}package com.javarush.task.jdk13.task53.task5301;
import com.javarush.engine.cell.*;
public class Game2048 extends Game {
private static final int SIDE = 4;
private int[][] gameField = new int[SIDE][SIDE];//{{2,4,8,16},{32,64,128,256},{512,1024,2048,0},{2,4,8,16}};
//{{2,4,8,16},{32,64,128,256},{512,1024,2048,0},{2,4,8,16}}
public void initialize() {
setScreenSize(SIDE, SIDE);
createGame();
drawScene();
//print();
}
private void createGame() {
createNewNumber();
createNewNumber();
}
private void drawScene() {
for (int i = 0; i < gameField.length; i++) {
for (int j = 0; j < gameField[i].length; j++) {
setCellColoredNumber(i, j, gameField[i][j]);
}
}
}
private void createNewNumber() {
int x = getRandomNumber(SIDE);
int y = getRandomNumber(SIDE);
if (gameField[x][y] != 0) {
while (gameField[x][y] != 0) {
x = getRandomNumber(SIDE);
y = getRandomNumber(SIDE);
}
}
if (getRandomNumber(10) == 9) {
gameField[x][y] = 4;
} else {
gameField[x][y] = 2;
}
}
private Color getColorByValue(int value) {
switch (value) {
case 2:
return Color.LIGHTYELLOW;
case 4:
return Color.YELLOW;
case 8:
return Color.PINK;
case 16:
return Color.ORANGE;
case 32:
return Color.DARKORANGE;
case 64:
return Color.ORANGERED;
case 128:
return Color.RED;
case 256:
return Color.DARKRED;
case 512:
return Color.BROWN;
case 1024:
return Color.PURPLE;
case 2048:
return Color.DARKVIOLET;
default:
return Color.WHITE;
}
}
private void setCellColoredNumber(int x, int y, int value) {
if (value == 0) {
setCellValueEx(y, x, getColorByValue(value), "");
} else{
setCellValueEx(y, x, getColorByValue(value), String.valueOf(value));
}
}
// private void print() {
// for (int i = 0; i < gameField.length; i++) {
// for (int j = 0; j < gameField[i].length; j++) {
// System.out.print(gameField[i][j] + " ");
// }
// System.out.println();
// }
// }
}
