用Java语言编写一个含背景音乐和排行榜以及有速度选择的贪吃蛇游戏,需要具体代码
时间: 2024-03-16 09:44:59 浏览: 206
好的,下面是一个基本的Java贪吃蛇游戏,包含背景音乐、排行榜和速度选择功能。其中,背景音乐使用Java自带的音乐播放器库,排行榜使用文件读写操作,速度选择使用JOptionPane弹出选择框。代码中有详细的注释,希望能帮到你。
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SnakeGame extends JPanel implements Runnable, KeyListener {
// 游戏窗口的宽度和高度
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
// 蛇的初始长度和初始方向
private static final int SNAKE_LENGTH = 10;
private static final int SNAKE_DIRECTION_RIGHT = 0;
private static final int SNAKE_DIRECTION_LEFT = 1;
private static final int SNAKE_DIRECTION_UP = 2;
private static final int SNAKE_DIRECTION_DOWN = 3;
// 游戏速度和分值
private static int speed = 5;
private static int score = 0;
// 蛇的身体和食物的坐标
private ArrayList<Point> snake = new ArrayList<Point>();
private Point food;
// 蛇的当前方向
private int direction;
// 游戏是否结束和是否暂停
private boolean gameOver;
private boolean pause;
// 排行榜文件路径
private static final String SCORE_FILE = "score.txt";
// 音乐文件路径
private static final String MUSIC_FILE = "music.wav";
public SnakeGame() {
// 设置游戏窗口的基本信息
setPreferredSize(new java.awt.Dimension(WIDTH, HEIGHT));
setBackground(Color.BLACK);
setFocusable(true);
// 添加键盘事件监听器
addKeyListener(this);
// 初始化蛇的身体和方向
direction = SNAKE_DIRECTION_RIGHT;
for (int i = 0; i < SNAKE_LENGTH; i++) {
snake.add(new Point(WIDTH / 2 - i * 10, HEIGHT / 2));
}
// 随机生成食物的坐标
generateFood();
// 加载背景音乐
playMusic();
// 开始游戏循环
new Thread(this).start();
}
// 绘制游戏界面
public void paint(Graphics g) {
super.paint(g);
// 绘制蛇的身体和食物
g.setColor(Color.WHITE);
for (Point p : snake) {
g.fillRect(p.x, p.y, 10, 10);
}
g.setColor(Color.RED);
g.fillRect(food.x, food.y, 10, 10);
// 绘制分数和速度
g.setColor(Color.WHITE);
g.drawString("Score: " + score, 10, 20);
g.drawString("Speed: " + speed, 10, 35);
// 绘制游戏结束提示
if (gameOver) {
g.drawString("Game Over!", WIDTH / 2 - 30, HEIGHT / 2);
}
// 绘制暂停提示
if (pause) {
g.drawString("Paused", WIDTH / 2 - 20, HEIGHT / 2);
}
}
// 游戏循环
public void run() {
while (true) {
if (!gameOver && !pause) {
// 移动蛇的身体
for (int i = snake.size() - 1; i > 0; i--) {
snake.set(i, snake.get(i - 1));
}
// 根据方向移动蛇头
switch (direction) {
case SNAKE_DIRECTION_RIGHT:
snake.set(0, new Point(snake.get(0).x + 10, snake.get(0).y));
break;
case SNAKE_DIRECTION_LEFT:
snake.set(0, new Point(snake.get(0).x - 10, snake.get(0).y));
break;
case SNAKE_DIRECTION_UP:
snake.set(0, new Point(snake.get(0).x, snake.get(0).y - 10));
break;
case SNAKE_DIRECTION_DOWN:
snake.set(0, new Point(snake.get(0).x, snake.get(0).y + 10));
break;
}
// 判断游戏是否结束
if (snake.get(0).x < 0 || snake.get(0).x >= WIDTH || snake.get(0).y < 0 || snake.get(0).y >= HEIGHT) {
gameOver = true;
}
for (int i = 1; i < snake.size(); i++) {
if (snake.get(0).equals(snake.get(i))) {
gameOver = true;
}
}
// 判断是否吃到食物
if (snake.get(0).equals(food)) {
// 增加蛇的长度
snake.add(new Point(snake.get(snake.size() - 1)));
// 增加分数
score += 10;
// 生成新的食物
generateFood();
}
}
// 重绘游戏界面
repaint();
// 控制游戏速度
try {
Thread.sleep(1000 / speed);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 生成随机食物的坐标
private void generateFood() {
Random random = new Random();
int x = random.nextInt(WIDTH / 10) * 10;
int y = random.nextInt(HEIGHT / 10) * 10;
food = new Point(x, y);
}
// 加载背景音乐
private void playMusic() {
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(getClass().getResource(MUSIC_FILE)));
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch (Exception e) {
e.printStackTrace();
}
}
// 保存分数到文件
private void saveScore() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(SCORE_FILE, true));
writer.write(score + "\n");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 从文件中读取分数并排序
private ArrayList<Integer> loadScore() {
ArrayList<Integer> scores = new ArrayList<Integer>();
try {
BufferedReader reader = new BufferedReader(new FileReader(SCORE_FILE));
String line;
while ((line = reader.readLine()) != null) {
scores.add(Integer.parseInt(line));
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
scores.sort((a, b) -> b - a);
return scores;
}
// 弹出排行榜对话框
private void showScore() {
ArrayList<Integer> scores = loadScore();
String message = "";
for (int i = 0; i < scores.size(); i++) {
message += (i + 1) + ". " + scores.get(i) + "\n";
}
JOptionPane.showMessageDialog(this, message, "Score Board", JOptionPane.PLAIN_MESSAGE);
}
// 处理键盘事件
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_RIGHT:
if (direction != SNAKE_DIRECTION_LEFT) {
direction = SNAKE_DIRECTION_RIGHT;
}
break;
case KeyEvent.VK_LEFT:
if (direction != SNAKE_DIRECTION_RIGHT) {
direction = SNAKE_DIRECTION_LEFT;
}
break;
case KeyEvent.VK_UP:
if (direction != SNAKE_DIRECTION_DOWN) {
direction = SNAKE_DIRECTION_UP;
}
break;
case KeyEvent.VK_DOWN:
if (direction != SNAKE_DIRECTION_UP) {
direction = SNAKE_DIRECTION_DOWN;
}
break;
case KeyEvent.VK_SPACE:
pause = !pause;
break;
case KeyEvent.VK_ENTER:
if (gameOver) {
saveScore();
gameOver = false;
score = 0;
direction = SNAKE_DIRECTION_RIGHT;
snake.clear();
for (int i = 0; i < SNAKE_LENGTH; i++) {
snake.add(new Point(WIDTH / 2 - i * 10, HEIGHT / 2));
}
generateFood();
}
break;
case KeyEvent.VK_S:
showScore();
break;
case KeyEvent.VK_1:
speed = 1;
break;
case KeyEvent.VK_2:
speed = 2;
break;
case KeyEvent.VK_3:
speed = 3;
break;
case KeyEvent.VK_4:
speed = 4;
break;
case KeyEvent.VK_5:
speed = 5;
break;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public static void main(String[] args) {
// 创建游戏窗口
JFrame frame = new JFrame("Snake Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(new SnakeGame());
frame.pack();
frame.setVisible(true);
// 弹出速度选择框
String[] options = { "1", "2", "3", "4", "5" };
int choice = JOptionPane.showOptionDialog(frame, "Select game speed:", "Speed", JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[2]);
speed = choice + 1;
}
}
```
阅读全文