Мне нужно сделать игру 2048 в Android.4x4 GridLayout программируется в Android
Для Правления нам необходимо использовать GridLayout и настроить его программно.
Это будет сетка 4x4, как оригинальная игра.
Для карты мы должны использовать FrameLayout с TextView и центрировать его.
Это то, что у меня уже есть:
public class Board extends GridLayout {
private final int BOARD_WIDTH = 4;
private final int BOARD_HEIGHT = 4;
private Card[][] cards;
public Board(Context context) {
super(context);
initBoard();
}
public Board(Context context, AttributeSet attrs) {
super(context, attrs);
initBoard();
}
public Board(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initBoard();
}
public void initBoard() {
this.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorBoard));
this.setRowCount(BOARD_HEIGHT);
this.setColumnCount(BOARD_WIDTH);
Random random = new Random();
cards = new Card[BOARD_WIDTH][BOARD_HEIGHT];
for (int x = 0; x < BOARD_WIDTH; x++) {
for (int y = 0; y < BOARD_HEIGHT; y++) {
int n = random.nextInt(2);
cards[x][y] = new Card(this.getContext(), (n * 2));
}
}
}
public void addCardsToBoard() {
for (int x = 0; x < BOARD_WIDTH; x++) {
for (int y = 0; y < BOARD_HEIGHT; y++) {
GridLayout.LayoutParams param = new LayoutParams();
param.height = LayoutParams.WRAP_CONTENT;
param.width = LayoutParams.WRAP_CONTENT;
param.setGravity(Gravity.CENTER);
param.columnSpec = GridLayout.spec(x);
param.rowSpec = GridLayout.spec(y);
param.topMargin = 50;
Card c = cards[x][y];
c.setLayoutParams(param);
this.addView(cards[x][y], 230, 230);
}
}
}
}
-
public class Card extends FrameLayout {
private int number = 0;
private TextView txtNumber;
public Card(Context context, int n) {
super(context);
LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
txtNumber = new TextView(context);
txtNumber.setTextSize(30);
txtNumber.setLayoutParams(params);
this.addView(txtNumber);
setNumber(n);
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
this.setBackgroundColor(ContextCompat.getColor(getContext(), number == 0 ? R.color.colorCard : R.color.colorCardActive));
txtNumber.setText(number == 0 ? "" : "" + number);
}
}
Все, что я могу сделать, чтобы выглядеть лучше (как оригинал игра).
Любые советы/советы приветствуются.
'Мне нужно сделать игру 2048' ... ** еще одну ** ?? И почему вы решили создавать GridLayout программно, вместо того, чтобы создавать GridView в макете xml? –
@ Rotwang Да, еще один, это хороший способ попрактиковаться? И это начальные инструкции. Хотелось бы сделать это в xml. – Matthiee