这里提供一份简单的Java实现贪吃蛇游戏的代码,代码中使用了Java的Swing库实现图形界面。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class SnakeGame extends JFrame implements ActionListener{

    private static final long serialVersionUID = 1L;
    private JButton startButton;
    private JButton exitButton;
    private JPanel gamePanel;
    private JLabel scoreLabel;
    private int score = 0;
    private int[][] map = new int[20][20];
    private LinkedList<Point> snake = new LinkedList<Point>();
    private Point food;

    public SnakeGame() {
        setTitle("贪吃蛇");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        setSize(400, 400);
        setLocationRelativeTo(null);

        JPanel mainPanel = new JPanel(new BorderLayout());
        JPanel buttonPanel = new JPanel(new FlowLayout());
        startButton = new JButton("开始游戏");
        startButton.addActionListener(this);
        exitButton = new JButton("退出游戏");
        exitButton.addActionListener(this);
        buttonPanel.add(startButton);
        buttonPanel.add(exitButton);
        mainPanel.add(buttonPanel, BorderLayout.NORTH);

        gamePanel = new JPanel(new GridLayout(20, 20));
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                JLabel label = new JLabel();
                label.setBorder(BorderFactory.createLineBorder(Color.GRAY));
                gamePanel.add(label);
            }
        }
        mainPanel.add(gamePanel, BorderLayout.CENTER);

        scoreLabel = new JLabel("得分: 0");
        mainPanel.add(scoreLabel, BorderLayout.SOUTH);

        add(mainPanel);
        setVisible(true);
    }

    public void initGame() {
        score = 0;
        scoreLabel.setText("得分: " + score);
        snake.clear();
        snake.add(new Point(10, 10));
        map = new int[20][20];
        map[10][10] = 1;
        createFood();
        updateGamePanel();
    }

    public void createFood() {
        int x = (int)(Math.random() * 20);
        int y = (int)(Math.random() * 20);
        if (map[x][y] == 0) {
            food = new Point(x, y);
        } else {
            createFood();
        }
    }

    public void updateGamePanel() {
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                JLabel label = (JLabel)gamePanel.getComponent(i * 20 + j);
                if (map[i][j] == 1) {
                    label.setBackground(Color.GREEN);
                } else if (food != null && food.x == i && food.y == j) {
                    label.setBackground(Color.RED);
                } else {
                    label.setBackground(Color.WHITE);
                }
            }
        }
    }

    public void moveSnake(int dx, int dy) {
        Point head = snake.getFirst();
        int x = head.x + dx;
        int y = head.y + dy;
        if (x < 0 || x >= 20 || y < 0 || y >= 20 || map[x][y] == 1) {
            JOptionPane.showMessageDialog(this, "游戏结束");
            initGame();
            return;
        }
        snake.addFirst(new Point(x, y));
        map[x][y] = 1;
        if (food != null && food.x == x && food.y == y) {
            score++;
            scoreLabel.setText("得分: " + score);
            createFood();
        } else {
            Point tail = snake.removeLast();
            map[tail.x][tail.y] = 0;
        }
        updateGamePanel();
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == startButton) {
            initGame();
            Timer timer = new Timer(500, new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    moveSnake(0, -1);
                }
            });
            timer.start();
            addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent e) {
                    switch (e.getKeyCode()) {
                        case KeyEvent.VK_UP:
                            moveSnake(0, -1);
                            break;
                        case KeyEvent.VK_DOWN:
                            moveSnake(0, 1);
                            break;
                        case KeyEvent.VK_LEFT:
                            moveSnake(-1, 0);
                            break;
                        case KeyEvent.VK_RIGHT:
                            moveSnake(1, 0);
                            break;
                    }
                }
            });
            startButton.setEnabled(false);
        } else if (e.getSource() == exitButton) {
            System.exit(0);
        }
    }

    public static void main(String[] args) {
        new SnakeGame();
    }
}
``
Java实现贪吃蛇的代码

原文地址: https://www.cveoy.top/t/topic/eCtc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录