import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.sound.sampled.*;public class Don'tStepOnWhiteTile extends JFrame implements ActionListener {
private static final int ROWS = 4;
private static final int COLS = 4;
private static final int TILE_SIZE = 100;private JButton[][] tiles;
private int score;
private Clip backgroundMusic;public Don'tStepOnWhiteTile() {
setTitle("别踩白块");
setSize(COLS * TILE_SIZE, ROWS * TILE_SIZE);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);tiles = new JButton[ROWS][COLS];
setLayout(new GridLayout(ROWS, COLS));for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
tiles[row][col] = new JButton();
tiles[row][col].setBackground(Color.WHITE);
tiles[row][col].addActionListener(this);
add(tiles[row][col]);
}
}score = 0;
loadBackgroundMusic();
setVisible(true);
}private void loadBackgroundMusic() {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(getClass().getResource("background_music.wav"));
backgroundMusic = AudioSystem.getClip();
backgroundMusic.open(audioInputStream);
backgroundMusic.loop(Clip.LOOP_CONTINUOUSLY);
} catch (Exception e) {
e.printStackTrace();
}
}public void actionPerformed(ActionEvent e) {
JButton tile = (JButton) e.getSource();
if (tile.getBackground() == Color.WHITE) {
tile.setBackground(Color.BLACK);
score++;
} else {
tile.setBackground(Color.WHITE);
score--;
}if (score < 0) {
score = 0;
}if (isGameOver()) {
backgroundMusic.stop();
JOptionPane.showMessageDialog(this, "游戏结束!得分:" + score, "游戏结束", JOptionPane.INFORMATION_MESSAGE);
resetGame();
}
}private boolean isGameOver() {
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
if (tiles[row][col].getBackground() == Color.WHITE) {
return false;
}
}
}
return true;
}private void resetGame() {
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLS; col++) {
tiles[row][col].setBackground(Color.WHITE);
}
}
score = 0;
backgroundMusic.loop(Clip.LOOP_CONTINUOUSLY);
}public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Don'tStepOnWhiteTile();
}
});
}
}
注意:我们添加了一个`loadBackgroundMusic`方法,该方法使用`AudioSystem`和`Clip`类从资源文件中加载背景音乐。你需要将音乐文件(例如`background_music.wav`)放置在与Java源文件相同的目录下
本文介绍了使用JavaSwing开发的一个名为别踩白块的游戏,游戏中融入了背景音乐播放功能,当玩家踩到白块时,游戏得分变化并检测游戏是否结束。
2675

被折叠的 条评论
为什么被折叠?



