Repository navigation
Expand file tree
/
Copy pathMemoryMatchActivity.java
More file actions
67 lines (57 loc) · 2.16 KB
/
Copy pathMemoryMatchActivity.java
File metadata and controls
67 lines (57 loc) · 2.16 KB
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
package com.example.games;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MemoryMatchActivity extends AppCompatActivity {
private List<Button> buttons;
private List<Integer> buttonValues;
private int lastButtonIndex = -1;
private boolean isFlipping = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memory_match);
GridLayout gridLayout = findViewById(R.id.gridLayout);
buttons = new ArrayList<>();
buttonValues = new ArrayList<>();
for (int i = 0; i < 16; i++) {
buttonValues.add(i / 2); // Two buttons for each value (0-7)
Button button = new Button(this);
button.setId(i);
button.setOnClickListener(this::onButtonClick);
buttons.add(button);
gridLayout.addView(button);
}
Collections.shuffle(buttonValues);
}
private void onButtonClick(View view) {
if (isFlipping) return;
Button button = (Button) view;
int index = button.getId();
button.setText(String.valueOf(buttonValues.get(index)));
if (lastButtonIndex == -1) {
lastButtonIndex = index;
} else {
if (buttonValues.get(lastButtonIndex).equals(buttonValues.get(index))) {
button.setEnabled(false);
buttons.get(lastButtonIndex).setEnabled(false);
lastButtonIndex = -1;
} else {
isFlipping = true;
Handler handler = new Handler();
handler.postDelayed(() -> {
button.setText("");
buttons.get(lastButtonIndex).setText("");
lastButtonIndex = -1;
isFlipping = false;
}, 1000);
}
}
}
}