由于贪吃蛇的代码实现较长,本回答仅提供一个简单的贪吃蛇代码框架,供参考。

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

public class SnakeGame extends JFrame implements KeyListener {
    private JLabel[][] grid;
    private int[][] snake;
    private int snakeLength;
    private int[] food;
    private int score;
    private boolean gameOver;
    private int direction; // 1: up, 2: right, 3: down, 4: left

    public SnakeGame() {
        // Initialize the game board
        grid = new JLabel[20][20];
        for (int i = 0; i < 20; i++) {
            for (int j = 0; j < 20; j++) {
                grid[i][j] = new JLabel();
                grid[i][j].setPreferredSize(new Dimension(20, 20));
                grid[i][j].setOpaque(true);
                grid[i][j].setBackground(Color.WHITE);
                getContentPane().add(grid[i][j]);
            }
        }

        // Initialize the snake
        snake = new int[100][2];
        snakeLength = 3;
        snake[0][0] = 10;
        snake[0][1] = 10;
        snake[1][0] = 10;
        snake[1][1] = 11;
        snake[2][0] = 10;
        snake[2][1] = 12;
        direction = 2;

        // Generate the food
        food = new int[2];
        generateFood();

        // Initialize the game state
        score = 0;
        gameOver = false;

        // Set up the window
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(new GridLayout(20, 20));
        pack();
        setVisible(true);

        // Set up the key listener
        addKeyListener(this);
        setFocusable(true);
    }

    private void generateFood() {
        // Generate a random location for the food
        food[0] = (int) (Math.random() * 20);
        food[1] = (int) (Math.random() * 20);
        // Check that the food is not on the snake
        for (int i = 0; i < snakeLength; i++) {
            if (food[0] == snake[i][0] && food[1] == snake[i][1]) {
                generateFood();
                return;
            }
        }
        // Set the food location on the game board
        grid[food[0]][food[1]].setBackground(Color.RED);
    }

    private boolean moveSnake() {
        // Move the snake in the current direction
        int headRow = snake[0][0];
        int headCol = snake[0][1];
        switch (direction) {
            case 1: // up
                headRow--;
                break;
            case 2: // right
                headCol++;
                break;
            case 3: // down
                headRow++;
                break;
            case 4: // left
                headCol--;
                break;
        }
        // Check if the snake has hit a wall
        if (headRow < 0 || headRow >= 20 || headCol < 0 || headCol >= 20) {
            return false;
        }
        // Check if the snake has hit itself
        for (int i = 1; i < snakeLength; i++) {
            if (headRow == snake[i][0] && headCol == snake[i][1]) {
                return false;
            }
        }
        // Check if the snake has eaten the food
        if (headRow == food[0] && headCol == food[1]) {
            // Add a new segment to the snake
            snakeLength++;
            snake[snakeLength - 1][0] = snake[snakeLength - 2][0];
            snake[snakeLength - 1][1] = snake[snakeLength - 2][1];
            // Generate a new food
            generateFood();
            // Increment the score
            score += 10;
        }
        // Move the snake segments
        for (int i = snakeLength - 1; i > 0; i--) {
            snake[i][0] = snake[i - 1][0];
            snake[i][1] = snake[i - 1][1];
        }
        snake[0][0] = headRow;
        snake[0][1] = headCol;
        return true;
    }

    public void keyTyped(KeyEvent e) {}

    public void keyPressed(KeyEvent e) {
        // Change the direction of the snake based on the arrow keys
        if (e.getKeyCode() == KeyEvent.VK_UP && direction != 3) {
            direction = 1;
        } else if (e.getKeyCode() == KeyEvent.VK_RIGHT && direction != 4) {
            direction = 2;
        } else if (e.getKeyCode() == KeyEvent.VK_DOWN && direction != 1) {
            direction = 3;
        } else if (e.getKeyCode() == KeyEvent.VK_LEFT && direction != 2) {
            direction = 4;
        }
    }

    public void keyReleased(KeyEvent e) {}

    public void play() {
        // Move the snake every 200 milliseconds
        Timer timer = new Timer(200, new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if (!gameOver) {
                    // Clear the game board
                    for (int i = 0; i < 20; i++) {
                        for (int j = 0; j < 20; j++) {
                            grid[i][j].setBackground(Color.WHITE);
                        }
                    }
                    // Move the snake and update the game board
                    if (moveSnake()) {
                        for (int i = 0; i < snakeLength; i++) {
                            grid[snake[i][0]][snake[i][1]].setBackground(Color.GREEN);
                        }
                        grid[food[0]][food[1]].setBackground(Color.RED);
                        setTitle("Snake - Score: " + score);
                    } else {
                        // End the game if the snake has hit a wall or itself
                        gameOver = true;
                        setTitle("Game Over - Score: " + score);
                    }
                }
            }
        });
        timer.start();
    }

    public static void main(String[] args) {
        new SnakeGame().play();
    }
}
``
用java写个贪吃蛇代码

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

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