J'ai besoin de faire un jeu 2048 dans Android.4x4 GridLayout peupler par programmation
Pour le conseil d'administration, nous devons utiliser un GridLayout et le configurer par programme.
Ce sera une grille 4x4 comme le jeu original.
Pour la carte, nous devons utiliser un FrameLayout avec un TextView et le centrer.
C'est ce que je l'ai déjà:
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);
}
}
Tout ce que je peux faire pour le faire paraître mieux (plus comme l'original Jeu).
Tout conseil/conseil est apprécié.
'Je dois faire un jeu 2048 ... ** un autre **? Et pourquoi avez-vous choisi de créer un GridLayout par programme, au lieu de créer un GridView dans une mise en page XML? –
@Rotwang Oui un autre, c'est un bon moyen de pratiquer à droite? Et ce sont les instructions de départ. J'aurais préféré le faire en XML. – Matthiee