温馨提示×

Java怎么实现简单连连看游戏

小亿
103
2023-08-10 05:40:58
栏目: 编程语言

以下是一个简单的Java实现连连看游戏的示例代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LianLianKan extends JFrame implements ActionListener {
private JButton[][] buttons;
private int[][] board;
private int size;
private int selectedRow;
private int selectedColumn;
public LianLianKan(int size) {
super("连连看");
this.size = size;
board = new int[size][size];
buttons = new JButton[size][size];
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(size, size));
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
JButton button = new JButton();
button.addActionListener(this);
buttons[i][j] = button;
add(button);
}
}
generateBoard();
refreshBoard();
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void generateBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = (i * size + j) % (size * size / 2) + 1;
}
}
}
public void refreshBoard() {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
buttons[i][j].setText(String.valueOf(board[i][j]));
}
}
}
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
int row = -1;
int column = -1;
// Find the clicked button
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (buttons[i][j] == button) {
row = i;
column = j;
break;
}
}
}
if (selectedRow == -1 && selectedColumn == -1) {
// No previous selection
selectedRow = row;
selectedColumn = column;
button.setEnabled(false);
} else {
if (board[selectedRow][selectedColumn] == board[row][column]) {
// Match found, remove buttons
buttons[selectedRow][selectedColumn].setVisible(false);
buttons[row][column].setVisible(false);
board[selectedRow][selectedColumn] = 0;
board[row][column] = 0;
} else {
// No match, reset selection
buttons[selectedRow][selectedColumn].setEnabled(true);
}
selectedRow = -1;
selectedColumn = -1;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new LianLianKan(4); // Create a 4x4 game
}
});
}
}

在这个示例代码中,我们创建了一个JFrame窗口,其中包含了一个指定大小的网格,每个格子是一个JButton按钮。我们使用一个二维数组board来表示每个格子上的图案,初始时每个格子上的图案是随机生成的。

当玩家点击一个按钮时,我们通过ActionEvent来处理按钮点击事件。如果之前没有选中的格子,那么我们将当前格子设为选中,并禁用该按钮。如果之前已经选中了一个格子,我们将当前格子与之前选中的格子进行比较。如果两个格子上的图案相同,说明找到了一对匹配,我们将它们从界面上隐藏,并将board中对应位置的值设为0。如果两个格子上的图案不同,我们将之前选中的格子的按钮重新启用。

最后,在main方法中创建一个LianLianKan对象,传入指定的大小,即可运行连连看游戏。在这个示例中,我们创建了一个4x4的游戏,你可以根据需要调整大小。

0