JAVA贪吃蛇小游戏实现:
贪吃蛇曾经在我们的童年给我们带来了很多乐趣。贪吃蛇这款游戏现在基本上没人玩了,甚至在新一代人的印象中都已毫无记忆了。。。但是,这款游戏可以在一定程度上锻炼自己的编程能力。
目前这个版本只是一个测试版本,所以只有一些基本功能,实现了移动,吃食物身体增长,分数增长,判断撞墙和撞自己的身体。
代码展示
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Random;
/**
* 贪吃蛇实现类,
* 可运行main方法查看效果
*/
public class SnakeGame extends JFrame implements ActionListener, KeyListener {
private static final long serialVersionUID = 1L;
private JPanel mainPanel, scorePanel, gamePanel;
private JButton startButton, pauseButton, resumeButton;
private JLabel scoreLabel;
private Timer timer;
private int score, headX, headY, headDirection, foodX, foodY, speed;
private final int GAME_WIDTH = 400, GAME_HEIGHT = 400, GRID_SIZE = 10;
private ArrayList<Integer> bodyX, bodyY;
public SnakeGame() {
super("贪吃蛇");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setFocusable(true);
addKeyListener(this);
// 创建主面板
mainPanel = new JPanel(new BorderLayout());
getContentPane().add(mainPanel);
// 创建分数面板
scorePanel = new JPanel();
scoreLabel = new JLabel("分数: " + score);
startButton = new JButton("开始");
pauseButton = new JButton("暂停");
resumeButton = new JButton("继续");
startButton.addActionListener(this);
pauseButton.addActionListener(this);
resumeButton.addActionListener(this);
pauseButton.setEnabled(false);
resumeButton.setEnabled(false);
scorePanel.add(scoreLabel);
scorePanel.add(startButton);
scorePanel.add(pauseButton);
scorePanel.add(resumeButton);
mainPanel.add(scorePanel, BorderLayout.NORTH);
// 创建游戏面板
gamePanel = new GamePanel();
mainPanel.add(gamePanel, BorderLayout.CENTER);
// 初始化
headX = GAME_WIDTH / 2;
headY = GAME_HEIGHT / 2;
headDirection = KeyEvent.VK_DOWN;
bodyX = new ArrayList<Integer>();
bodyY = new ArrayList<Integer>();
bodyX.add(headX);
bodyY.add(headY - GRID_SIZE);
bodyX.add(headX);
bodyY.add(headY - 2 * GRID_SIZE);
speed = 200;//移动速度 值越小速度越快,值越大速度越慢
// 显示窗口
pack();
setLocationRelativeTo(null); // 居中
setResizable(false); // 禁止调整大小
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startButton) { // 开始游戏
startGame();
} else if (e.getSource() == pauseButton) { // 暂停游戏
pauseGame();
} else if (e.getSource() == resumeButton) { // 继续游戏
resumeGame();
}
}
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP && headDirection != KeyEvent.VK_DOWN) {
headDirection = KeyEvent.VK_UP;
} else if (keyCode == KeyEvent.VK_DOWN && headDirection != KeyEvent.VK_UP) {
headDirection = KeyEvent.VK_DOWN;
} else if (keyCode == KeyEvent.VK_LEFT && headDirection != KeyEvent.VK_RIGHT) {
headDirection = KeyEvent.VK_LEFT;
} else if (keyCode == KeyEvent.VK_RIGHT && headDirection != KeyEvent.VK_LEFT) {
headDirection = KeyEvent.VK_RIGHT;
}
}
@Override
public void keyReleased(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
private void startGame() {
startButton.setEnabled(false);
pauseButton.setEnabled(true);
timer = new Timer(speed, new TimerHandler());
timer.start();
newFood();
}
private void pauseGame() {
timer.stop();
pauseButton.setEnabled(false);
resumeButton.setEnabled(true);
}
private void resumeGame() {
timer.start();
pauseButton.setEnabled(true);
resumeButton.setEnabled(false);
}
private class GamePanel extends JPanel {
private static final long serialVersionUID = 1L;
public GamePanel() {
setBackground(Color.WHITE);
setPreferredSize(new Dimension(GAME_WIDTH, GAME_HEIGHT));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// 画食物
g.setColor(Color.BLUE);
g.fillOval(foodX, foodY, GRID_SIZE, GRID_SIZE);
// 画蛇头
g.setColor(Color.gray);
g.fillOval(headX, headY, GRID_SIZE, GRID_SIZE);
// 画蛇身体
g.setColor(Color.BLACK);
for (int i = 0; i < bodyX.size(); i++) {
g.fillOval(bodyX.get(i), bodyY.get(i), GRID_SIZE, GRID_SIZE);
}
}
}
private class TimerHandler implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// 移动蛇身体
for (int i = bodyX.size() - 1; i > 0; i--) {
bodyX.set(i, bodyX.get(i - 1));
bodyY.set(i, bodyY.get(i - 1));
}
bodyX.set(0, headX);
bodyY.set(0, headY);
// 移动蛇头
if (headDirection == KeyEvent.VK_UP) {
headY -= GRID_SIZE;
} else if (headDirection == KeyEvent.VK_DOWN) {
headY += GRID_SIZE;
} else if (headDirection == KeyEvent.VK_LEFT) {
headX -= GRID_SIZE;
} else if (headDirection == KeyEvent.VK_RIGHT) {
headX += GRID_SIZE;
}
// 碰到边界或自身,游戏结束
if (headX < 0 || headX + GRID_SIZE > GAME_WIDTH || headY < 0 || headY + GRID_SIZE > GAME_HEIGHT) {
gameOver();
return;
}
for (int i = 0; i < bodyX.size(); i++) {
if (headX == bodyX.get(i) && headY == bodyY.get(i)) {
gameOver();
return;
}
}
// 吃到食物,增加分数和身体长度
if (headX == foodX && headY == foodY) {
score += 10;
scoreLabel.setText("分数: " + score);
bodyX.add(bodyX.get(bodyX.size() - 1));
bodyY.add(bodyY.get(bodyY.size() - 1));
newFood();
}
// 重绘游戏面板
gamePanel.repaint();
}
}
private void newFood() {
Random rand = new Random();
foodX = rand.nextInt(GAME_WIDTH / GRID_SIZE) * GRID_SIZE;
foodY = rand.nextInt(GAME_HEIGHT / GRID_SIZE) * GRID_SIZE;
for (int i = 0; i < bodyX.size(); i++) {
if (foodX == bodyX.get(i) && foodY == bodyY.get(i)) {
newFood();
return;
}
}
}
private void gameOver() {
timer.stop();
JOptionPane.showMessageDialog(this, "游戏结束,分数:" + score);
startButton.setEnabled(true);
pauseButton.setEnabled(false);
resumeButton.setEnabled(false);
score = 0;
scoreLabel.setText("分数: " + score);
headX = GAME_WIDTH / 2;
headY = GAME_HEIGHT / 2;
headDirection = KeyEvent.VK_DOWN;
bodyX.clear();
bodyY.clear();
bodyX.add(headX);
bodyY.add(headY - GRID_SIZE);
bodyX.add(headX);
bodyY.add(headY - 2 * GRID_SIZE);
}
//运行游戏
public static void main(String[] args) {
new SnakeGame();
System.out.println("");
}
}
运行效果如图:
完整素材及全部代码
代码已上传csdn,0积分下载,觉得这片博文有用请留下你的点赞。
基于JAVA实现的贪吃蛇小游戏
感谢大家的阅读,希望对大家有所帮助!