用Java开发简单的贪吃蛇游戏 - 详细教程和代码
用Java开发简单的贪吃蛇游戏 - 详细教程和代码
想要学习用Java开发一款经典的贪吃蛇游戏吗?本教程将带您从零开始,一步步实现这款简单又有趣的休闲游戏。
游戏规则
贪吃蛇游戏的规则很简单:
- 玩家控制一条蛇在一个有限的区域内移动,吃掉食物以增加长度。
- 如果蛇头碰到边界或者自己的身体,游戏结束。
- 食物会随机出现在游戏区域内的某个位置。
- 每次吃掉食物后,蛇的长度会增加,并且游戏难度会增加。
- 游戏结束后,可以记录玩家的得分,并提供重新开始游戏的选项。
代码实现
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private final int WIDTH = 300;
private final int HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
private final int x[] = new int[ALL_DOTS];
private final int y[] = new int[ALL_DOTS];
private int dots;
private int food_x;
private int food_y;
private boolean leftDirection = false;
private boolean rightDirection = true;
private boolean upDirection = false;
private boolean downDirection = false;
private boolean inGame = true;
private Timer timer;
private Image ball;
private Image food;
private Image head;
public SnakeGame() {
initGame();
}
private void initGame() {
addKeyListener(new TAdapter());
setBackground(Color.white);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
ImageIcon iid = new ImageIcon(this.getClass().getResource("dot.png"));
ball = iid.getImage();
ImageIcon iia = new ImageIcon(this.getClass().getResource("apple.png"));
food = iia.getImage();
ImageIcon iih = new ImageIcon(this.getClass().getResource("head.png"));
head = iih.getImage();
dots = 3;
for (int z = 0; z < dots; z++) {
x[z] = 50 - z * 10;
y[z] = 50;
}
locateFood();
timer = new Timer(DELAY, this);
timer.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g) {
if (inGame) {
g.drawImage(food, food_x, food_y, this);
for (int z = 0; z < dots; z++) {
if (z == 0) {
g.drawImage(head, x[z], y[z], this);
} else {
g.drawImage(ball, x[z], y[z], this);
}
}
Toolkit.getDefaultToolkit().sync();
} else {
gameOver(g);
}
}
private void gameOver(Graphics g) {
String msg = "Game Over";
Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metr = getFontMetrics(small);
g.setColor(Color.black);
g.setFont(small);
g.drawString(msg, (WIDTH - metr.stringWidth(msg)) / 2, HEIGHT / 2);
}
private void checkFood() {
if ((x[0] == food_x) && (y[0] == food_y)) {
dots++;
locateFood();
}
}
private void move() {
for (int z = dots; z > 0; z--) {
x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}
if (leftDirection) {
x[0] -= DOT_SIZE;
}
if (rightDirection) {
x[0] += DOT_SIZE;
}
if (upDirection) {
y[0] -= DOT_SIZE;
}
if (downDirection) {
y[0] += DOT_SIZE;
}
}
private void checkCollision() {
for (int z = dots; z > 0; z--) {
if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
inGame = false;
}
}
if (y[0] >= HEIGHT) {
inGame = false;
}
if (y[0] < 0) {
inGame = false;
}
if (x[0] >= WIDTH) {
inGame = false;
}
if (x[0] < 0) {
inGame = false;
}
if (!inGame) {
timer.stop();
}
}
private void locateFood() {
int r = (int) (Math.random() * RAND_POS);
food_x = ((r * DOT_SIZE));
r = (int) (Math.random() * RAND_POS);
food_y = ((r * DOT_SIZE));
}
@Override
public void actionPerformed(ActionEvent e) {
if (inGame) {
checkFood();
checkCollision();
move();
}
repaint();
}
private class TAdapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
leftDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
rightDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_UP) && (!downDirection)) {
upDirection = true;
rightDirection = false;
leftDirection = false;
}
if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
downDirection = true;
rightDirection = false;
leftDirection = false;
}
}
}
public static void main(String[] args) {
JFrame frame = new SnakeGame();
frame.setTitle("Snake");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
代码说明
代码中包含以下关键部分:
- 游戏初始化: 在
initGame()方法中,设置游戏窗口尺寸、背景颜色、键盘监听器等。 - 绘制游戏:
paintComponent()方法负责绘制游戏界面,包括蛇身、食物和游戏结束信息。 - 移动蛇:
move()方法根据方向控制蛇的移动。 - 碰撞检测:
checkCollision()方法检测蛇是否撞到边界或自身。 - 吃食物:
checkFood()方法检测蛇是否吃到食物,并增加长度。 - 游戏循环:
actionPerformed()方法作为游戏循环,不断更新游戏状态并重绘界面。
运行游戏
- 将以上代码保存为
SnakeGame.java文件。 - 确保您的系统中已经安装了 Java 开发环境 (JDK)。
- 在命令行中运行
javac SnakeGame.java编译代码。 - 运行
java SnakeGame即可启动游戏。
扩展游戏
您可以根据自己的创意扩展游戏功能,例如:
- 增加不同难度的游戏模式。
- 添加背景音乐和音效。
- 实现多人游戏模式。
- 添加计分系统和排行榜。
结语
希望本教程能帮助您学习使用Java开发简单的游戏。 通过不断尝试和练习,您将能够创造出更多有趣的游戏。
原文地址: https://www.cveoy.top/t/topic/jMg9 著作权归作者所有。请勿转载和采集!