我目前正在尝试编写记忆/配对游戏。我在尝试弄清楚如何检查是否单击了同一张卡并且用户找到匹配项时遇到问题。我了解我需要存储第一次点击的值并将其与第二次点击进行比较,但仍然不确定如何实际执行。
考虑以下代码,我重新创建了游戏的更简单版本,您可以在下面实际运行它:
class start {
JToggleButton DisplayCards[][] = new JToggleButton[4][4];
Shuffle shuffle = new Shuffle();
void main() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
int y = 20;
int x = 60;
for (int i = 0; i < DisplayCards.length; ++i) {
for (int j = 0; j < DisplayCards[i].length; ++j) {
DisplayCards[i][j] = new JToggleButton("Click Me!");
DisplayCards[i][j].setBounds(x, y, 90, 126);
y = y + 135;
if (y >= 540) {
y = 20;
x = x + 120;
}
frame.add(DisplayCards[i][j]);
DisplayCards[i][j].addActionListener(new Clicked(i, j, shuffle));
}
}
frame.setLayout(null);
frame.setVisible(true);
}
}
洗牌的课程:
class Shuffle {
String[][] cards = {
{"A", "B", "C", "D"},
{"E", "F", "G", "H"},
{"A", "B", "C", "D"},
{"E", "F", "G", "H"}
};
public void random() {
for (int i = 0; i < cards.length; i++) {
for (int j = 0; j < cards[i].length; j++) {
int i1 = (int) (Math.random() * cards.length);
int j1 = (int) (Math.random() * cards[i].length);
String temp = cards[i][j];
cards[i][j] = cards[i1][j1];
cards[i1][j1] = temp;
}
}
}
}
ActionListener的类:
class Clicked implements ActionListener {
Shuffle shuffle;
JToggleButton tBtn;
private int i;
private int j;
public Clicked(int i, int j, Shuffle shuffle) {
this.i = i;
this.j = j;
this.shuffle = shuffle;
}
public void actionPerformed(ActionEvent e) {
tBtn = (JToggleButton) e.getSource();
if (tBtn.isSelected()) {
tBtn.setText(shuffle.cards[i][j]);
} else {
tBtn.setText("Click Me!");
}
}
}
最佳答案
您需要存储所选的值并进行比较。这是一个粗略的例子。
我叫你的主班PuzzleGame
。
在主类中,我输入了两个静态值。
static String first;
static boolean state = false;
然后,我对您的操作侦听器进行了如下修改。
public void actionPerformed(ActionEvent e) {
tBtn = (JToggleButton) e.getSource();
if (tBtn.isSelected()) {
tBtn.setText(shuffle.cards[i][j]);
if (!PuzzleGame.state) {
PuzzleGame.first = shuffle.cards[i][j];
System.out.println(PuzzleGame.first);
PuzzleGame.state = true;
} else {
if (PuzzleGame.first.equals(shuffle.cards[i][j])) {
System.out.println("Correct!");
}
}
} else {
tBtn.setText("Click Me!");
}
}
第一次,
state
是false
,因此设置了first
。第二次,state
是true
,因此也可以与设置的first
进行比较。在这样的游戏中,您不应使用静态值。我这样做是因为它很容易演示该技术。
您还应该为错误的答案重置值和状态,并为正确的答案禁用按钮。
最后一点。
frame.setLocationRelativeTo(null); // centers the frame on screen.