This repository was archived by the owner on Mar 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryGame.java
More file actions
107 lines (90 loc) · 2.77 KB
/
Copy pathMemoryGame.java
File metadata and controls
107 lines (90 loc) · 2.77 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.accessibility.*;
import java.util.*;
public class MemoryGame extends JFrame implements ActionListener {
private final int BOARD_SIZE = 4;
private final int MAX_CARD = BOARD_SIZE * BOARD_SIZE / 2;
private int[][] board = new int[BOARD_SIZE][BOARD_SIZE];
private JButton[][] button = new JButton[BOARD_SIZE][BOARD_SIZE];
private JButton lastButton = null;
private int pairFound = 0;
public MemoryGame() {
setTitle("Memory Game");
setSize(200, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
randomBoard();
drawBoard();
setVisible(true);
}
private void randomBoard() {
Random rand = new Random();
for (int i=0; i<BOARD_SIZE; i++) Arrays.fill(board[i], 0);
for (int i=1; i<=MAX_CARD; i++) {
for (int j=0; j<2; j++) {
int x, y;
do {
x = rand.nextInt(BOARD_SIZE);
y = rand.nextInt(BOARD_SIZE);
} while (board[x][y] != 0);
board[x][y] = i;
}
}
}
private void drawBoard() {
JPanel panel = new JPanel(new GridLayout(BOARD_SIZE, BOARD_SIZE));
for (int i=0; i<BOARD_SIZE; i++) {
for (int j=0; j<BOARD_SIZE; j++) {
button[i][j] = new JButton();
button[i][j].addActionListener(this);
panel.add(button[i][j]);
}
}
add(panel);
}
private int[] getButtonPressed(Object source) {
for (int i=0; i<BOARD_SIZE; i++)
for (int j=0; j<BOARD_SIZE; j++)
if (button[i][j] == source) {
int retval[] = {i, j};
return retval;
}
return null;
}
private void checkWinner() {
if (pairFound == MAX_CARD)
JOptionPane.showMessageDialog(this, "You win!");
}
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
int idx[] = getButtonPressed(src);
int x = idx[0], y = idx[1];
JButton pressed = button[x][y];
if (pressed.getText().length() == 0) {
if (lastButton == null) {
lastButton = pressed;
lastButton.setText("" + board[x][y]);
}
else {
if (Integer.parseInt(lastButton.getText()) == board[x][y]) {
pressed.setText("" + board[x][y]);
pairFound++;
checkWinner();
}
else {
lastButton.setText("");
}
lastButton = null;
}
}
}
public static void main(String[] args) {
MemoryGame frm = new MemoryGame();
}
private static void debug(String str) {
System.out.println(str);
}
}