使用Java实现贪吃蛇游戏。

代码如下:

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyAdapter;

import java.awt.event.KeyEvent;

import java.util.ArrayList;

import java.util.List;

import java.util.Random;

 

public class SnakeGame extends JPanel implements ActionListener {

    private final int width = 30;

    private final int height = 30;

    private final int cellSize = 20;

    private final int gridWidth = width * cellSize;

    private final int gridHeight = height * cellSize;

    private final int delay = 100; // 游戏循环的延迟

    private int snakeSize = 3; // 初始蛇的长度

    private int x = 15, y = 15; // 蛇头的初始位置

    private int[] snakeX = new int[width], snakeY = new int[height]; // 存储蛇的每个部分

    private int appleX, appleY; // 苹果的位置

    private int score = 0;

    private Timer timer;

 

    public SnakeGame() {

        setPreferredSize(new Dimension(gridWidth, gridHeight));

        setBackground(Color.BLACK);

        setFocusable(true);

        addKeyListener(new TKeyListener());

        generateApple();

        startGame();

    }

 

    private void generateApple() {

        Random random = new Random();

        appleX = random.nextInt(width);

        appleY = random.nextInt(height);

    }

 

    private void startGame() {

        timer = new Timer(delay, this);

        timer.start();

    }

 

    private void stopGame() {

        if (timer != null) {

            timer.stop();

        }

    }

 

    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        draw(g);

    }

 

    private void draw(Graphics g) {

        g.setColor(Color.RED);

        g.fillRect(appleX * cellSize, appleY * cellSize, cellSize, cellSize); // 绘制苹果

 

        g.setColor(Color.GREEN);

        for (int i = 0; i < snakeSize; i++) {

            g.fillRect(snakeX[i] * cellSize, snakeY[i] * cellSize, cellSize, cellSize);

        }

 

        g.setColor(Color.WHITE);

        g.drawString("Score: " + score, 10, 20);

    }

 

    @Override

    public void actionPerformed(ActionEvent e) {

        if (e.getSource() == timer) {

            moveSnake();

            repaint();

        }

    }

 

    private void moveSnake() {

        for (int i = snakeSize - 1; i > 0; i--) {

            snakeX[i] = snakeX[i - 1];

            snakeY[i] = snakeY[i - 1];

        }

 

        switch (direction) {

            case "UP":

                y--;

                break;

            case "DOWN":

                y++;

                break;

            case "LEFT":

                x--;

                break;

            case "RIGHT":

                x++;

                break;

        }

 

        if (x >= width) x = 0;

        if (x < 0) x = width - 1;

        if (y >= height) y = 0;

        if (y < 0) y = height - 1;

 

        snakeX[0] = x;

        snakeY[0] = y;

 

        if (x == appleX && y == appleY) {

            score += 10;

            snakeSize++;

            generateApple();

        }

 

        checkGameOver();

    }

 

    private void checkGameOver() {

        for (int i = snakeSize - 1; i > 0; i--) {

            if (snakeX[i] == snakeX[0] && snakeY[i] == snakeY[0]) {

                stopGame();

                JOptionPane.showMessageDialog(this, "Game Over! Your score: " + score, "Game Over", JOptionPane.PLAIN_MESSAGE);

            }

        }

    }

 

    class TKeyListener extends KeyAdapter {

        @Override

        public void keyPressed(KeyEvent e) {

            switch (e.getKeyCode()) {

                case KeyEvent.VK_UP:

                    direction = "UP";

                    break;

                case KeyEvent.VK_DOWN:

                    direction = "DOWN";

                    break;

                case KeyEvent.VK_LEFT:

                    direction = "LEFT";

                    break;

                case KeyEvent.VK_RIGHT:

                    direction = "RIGHT";

                    break;

            }

        }

    }

 

    private String direction;

 

    public static void main(String[] args) {

        JFrame frame = new JFrame("贪吃蛇游戏");

        SnakeGame game = new SnakeGame();

        frame.add(game);

        frame.pack();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.setResizable(false);

        frame.setLocationRelativeTo(null);

        frame.setVisible(true);

    }

}

代码制作不易,请勿抄袭。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值