Java编写一个带有背景音乐的贪吃蛇游戏
时间: 2024-03-11 08:48:00 浏览: 96
以下是一个Java编写的带有背景音乐的贪吃蛇游戏的示例代码。在此示例中,我们使用Java Swing库来创建游戏窗口,使用Java AWT库来处理用户输入,使用Java内置的javax.sound.sampled库来添加背景音乐。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.sound.sampled.*;
import java.io.*;
public class SnakeGame extends JPanel implements ActionListener, KeyListener {
// 游戏相关变量
private int width = 300;
private int height = 300;
private int tileSize = 10;
private int[][] tiles = new int[width/tileSize][height/tileSize];
private int snakeLength = 3;
private int[] snakeX = new int[snakeLength];
private int[] snakeY = new int[snakeLength];
private int foodX, foodY;
private boolean gameOver = false;
private Timer timer;
// 背景音乐相关变量
private Clip clip;
private boolean musicOn = true;
public SnakeGame() {
// 设置游戏窗口大小和背景色
setPreferredSize(new Dimension(width, height));
setBackground(Color.BLACK);
// 初始化蛇的位置和食物位置
for (int i = 0; i < snakeLength; i++) {
snakeX[i] = width/tileSize/2 + i;
snakeY[i] = height/tileSize/2;
}
spawnFood();
// 创建游戏主循环
timer = new Timer(100, this);
timer.start();
// 添加键盘事件监听器
addKeyListener(this);
setFocusable(true);
// 初始化背景音乐
initMusic();
}
// 初始化背景音乐
private void initMusic() {
try {
// 打开音频文件
File musicFile = new File("music.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(musicFile);
// 获取音频格式
AudioFormat format = audioIn.getFormat();
// 打开音频输出流
DataLine.Info info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(audioIn);
// 循环播放音乐
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
// 刷新游戏
private void update() {
// 更新蛇的位置
for (int i = snakeLength - 1; i > 0; i--) {
snakeX[i] = snakeX[i-1];
snakeY[i] = snakeY[i-1];
}
switch (tiles[snakeX[0]][snakeY[0]]) {
case 0:
snakeX[0]++;
break;
case 1:
snakeX[0]--;
break;
case 2:
snakeY[0]++;
break;
case 3:
snakeY[0]--;
break;
case 4:
snakeLength++;
snakeX[snakeLength-1] = snakeX[snakeLength-2];
snakeY[snakeLength-1] = snakeY[snakeLength-2];
spawnFood();
break;
}
// 检查游戏是否结束
if (snakeX[0] < 0 || snakeX[0] >= width/tileSize || snakeY[0] < 0 || snakeY[0] >= height/tileSize) {
gameOver = true;
}
for (int i = 1; i < snakeLength; i++) {
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
gameOver = true;
}
}
}
// 绘制游戏
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
// 绘制蛇
g2d.setColor(Color.GREEN);
for (int i = 0; i < snakeLength; i++) {
g2d.fillRect(snakeX[i]*tileSize, snakeY[i]*tileSize, tileSize, tileSize);
}
// 绘制食物
g2d.setColor(Color.RED);
g2d.fillRect(foodX*tileSize, foodY*tileSize, tileSize, tileSize);
// 绘制游戏结束文字
if (gameOver) {
g2d.setColor(Color.WHITE);
g2d.drawString("Game Over!", width/2-30, height/2);
}
}
// 生成食物
private void spawnFood() {
do {
foodX = (int) (Math.random() * (width/tileSize));
foodY = (int) (Math.random() * (height/tileSize));
} while (tiles[foodX][foodY] != 0);
tiles[foodX][foodY] = 4;
}
// 处理定时器事件
public void actionPerformed(ActionEvent e) {
if (gameOver) {
timer.stop();
} else {
update();
repaint();
}
}
// 处理键盘事件
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
if (tiles[snakeX[0]][snakeY[0]-1] != 3) {
tiles[snakeX[0]][snakeY[0]] = 2;
snakeX[0] = snakeX[0];
snakeY[0] = snakeY[0]-1;
}
break;
case KeyEvent.VK_DOWN:
if (tiles[snakeX[0]][snakeY[0]+1] != 2) {
tiles[snakeX[0]][snakeY[0]] = 3;
snakeX[0] = snakeX[0];
snakeY[0] = snakeY[0]+1;
}
break;
case KeyEvent.VK_LEFT:
if (tiles[snakeX[0]-1][snakeY[0]] != 1) {
tiles[snakeX[0]][snakeY[0]] = 0;
snakeX[0] = snakeX[0]-1;
snakeY[0] = snakeY[0];
}
break;
case KeyEvent.VK_RIGHT:
if (tiles[snakeX[0]+1][snakeY[0]] != 0) {
tiles[snakeX[0]][snakeY[0]] = 1;
snakeX[0] = snakeX[0]+1;
snakeY[0] = snakeY[0];
}
break;
case KeyEvent.VK_M:
if (musicOn) {
clip.stop();
musicOn = false;
} else {
clip.loop(Clip.LOOP_CONTINUOUSLY);
musicOn = true;
}
break;
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
// 启动游戏
public static void main(String[] args) {
JFrame frame = new JFrame("Snake Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SnakeGame game = new SnakeGame();
frame.add(game);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```
在上述代码中,我们使用Java Swing库创建游戏窗口,并使用Java AWT库处理用户输入。我们还使用Java内置的javax.sound.sampled库添加背景音乐。在游戏主循环中,我们更新蛇的位置并检查游戏是否结束。在键盘事件处理方法中,我们处理用户输入,包括控制蛇的移动和开关背景音乐。最后,我们在main方法中启动游戏。
你可以将上述代码保存为SnakeGame.java文件并编译运行,以在Java编写的贪吃蛇游戏中添加背景音乐。如果需要,你可以根据需要修改代码以满足你的具体需求。
阅读全文