java实现贪吃蛇游戏(附源码)

实现一个简单的贪吃蛇游戏需要使用Java的图形库,通常可以使用Swing或JavaFX。下面是一个使用Swing库来创建一个简单贪吃蛇游戏的示例代码:

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.LinkedList;
import java.util.Random;

public class SnakeGame extends JPanel implements ActionListener {
    private final int CELL_SIZE = 20;
    private final int GRID_WIDTH = 20;
    private final int GRID_HEIGHT = 20;
    private final int GAME_SPEED = 150;

    private LinkedList<Point> snake;
    private Point food;
    private int direction;
    private boolean isMoving;
    private boolean isGameOver;

    public SnakeGame() {
        setPreferredSize(new Dimension(CELL_SIZE * GRID_WIDTH, CELL_SIZE * GRID_HEIGHT));
        setBackground(Color.BLACK);
        setFocusable(true);

        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int key = e.getKeyCode();
                if ((key == KeyEvent.VK_LEFT) && (direction != 1)) direction = 0;
                if ((key == KeyEvent.VK_RIGHT) && (direction != 0)) direction = 1;
                if ((key == KeyEvent.VK_UP) && (direction != 3)) direction = 2;
                if ((key == KeyEvent.VK_DOWN) && (direction != 2)) direction = 3;
            }
        });

        snake = new LinkedList<>();
        generateFood();
        isMoving = true;
        isGameOver = false;

        Timer timer = new Timer(GAME_SPEED, this);
        timer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (isMoving && !isGameOver) {
            move();
            checkCollision();
            repaint();
        }
    }

    private void generateFood() {
        Random rand = new Random();
        int x, y;
        do {
            x = rand.nextInt(GRID_WIDTH);
            y = rand.nextInt(GRID_HEIGHT);
        } while (snake.contains(new Point(x, y));
        food = new Point(x, y);
    }

    private void move() {
        Point head = snake.peekFirst();
        Point newHead;
        switch (direction) {
            case 0:
                newHead = new Point(head.x - 1, head.y);
                break;
            case 1:
                newHead = new Point(head.x + 1, head.y);
                break;
            case 2:
                newHead = new Point(head.x, head.y - 1);
                break;
            case 3:
                newHead = new Point(head.x, head.y + 1);
                break;
            default:
                newHead = head;
        }

        snake.addFirst(newHead);

        if (newHead.equals(food)) {
            generateFood();
        } else {
            snake.removeLast();
        }
    }

    private void checkCollision() {
        if (snake.size() == GRID_WIDTH * GRID_HEIGHT) {
            isMoving = false;
            isGameOver = true;
        }

        Point head = snake.peekFirst();
        if (head.x < 0 || head.x >= GRID_WIDTH || head.y < 0 || head.y >= GRID_HEIGHT) {
            isMoving = false;
            isGameOver = true;
        }

        if (snake.size() > 1 && snake.contains(head)) {
            isMoving = false;
            isGameOver = true;
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (isGameOver) {
            g.setColor(Color.WHITE);
            g.setFont(new Font("SansSerif", Font.BOLD, 30));
            g.drawString("Game Over!", CELL_SIZE * 5, CELL_SIZE * 10);
        } else {
            // 绘制食物
            g.setColor(Color.RED);
            g.fillRect(food.x * CELL_SIZE, food.y * CELL_SIZE, CELL_SIZE, CELL_SIZE);

            // 绘制蛇
            g.setColor(Color.GREEN);
            for (Point p : snake) {
                g.fillRect(p.x * CELL_SIZE, p.y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
            }
        }
    }

    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.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

这个示例创建了一个简单的贪吃蛇游戏,使用了Swing库来构建图形用户界面。玩家可以使用方向键控制蛇的移动,目标是吃到食物,躲避碰撞和自身。游戏会在一定条件下结束,显示"Game Over"。你可以根据需要对游戏进行扩展和改进。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是Java实现扫雷游戏的完整源码: ```java import java.util.Random; import java.util.Scanner; public class MineSweeper { private int[][] board; // 扫雷游戏面板 private boolean[][] revealed; // 记录位置是否被揭示 private int mines; // 雷的个数 private int size; // 面板大小 private boolean gameOver; // 游戏是否结束 public MineSweeper(int size, int mines) { this.size = size; this.mines = mines; this.board = new int[size][size]; this.revealed = new boolean[size][size]; this.gameOver = false; initBoard(); } // 初始化面板,随机放置雷 private void initBoard() { Random random = new Random(); int count = 0; while (count < mines) { int x = random.nextInt(size); int y = random.nextInt(size); if (board[x][y] != -1) { // 如果该位置不是雷,就放置雷 board[x][y] = -1; count++; } } } // 显示游戏面板 private void displayBoard() { System.out.println(); System.out.print(" "); for (int i = 0; i < size; i++) { System.out.print(i + " "); } System.out.println(); for (int i = 0; i < size; i++) { System.out.print(i + " "); for (int j = 0; j < size; j++) { if (revealed[i][j]) { // 如果该位置已经被揭示 if (board[i][j] == -1) { // 如果该位置是雷 System.out.print("* "); } else { // 如果该位置不是雷 System.out.print(board[i][j] + " "); } } else { // 如果该位置还没有被揭示 System.out.print(". "); } } System.out.println(); } } // 获取某个位置周围雷的数量 private int getSurroundingMines(int x, int y) { int count = 0; for (int i = x - 1; i <= x + 1; i++) { for (int j = y - 1; j <= y + 1; j++) { if (i >= 0 && i < size && j >= 0 && j < size && board[i][j] == -1) { count++; } } } return count; } // 揭示某个位置 private void reveal(int x, int y) { if (!revealed[x][y]) { // 如果该位置还没有被揭示 revealed[x][y] = true; if (board[x][y] == -1) { // 如果该位置是雷,游戏结束 gameOver = true; return; } if (getSurroundingMines(x, y) == 0) { // 如果该位置周围没有雷,递归揭示周围的位置 for (int i = x - 1; i <= x + 1; i++) { for (int j = y - 1; j <= y + 1; j++) { if (i >= 0 && i < size && j >= 0 && j < size) { reveal(i, j); } } } } } } // 运行游戏 public void run() { Scanner scanner = new Scanner(System.in); while (!gameOver) { displayBoard(); System.out.print("请输入要揭示的位置(x y):"); int x = scanner.nextInt(); int y = scanner.nextInt(); if (x >= 0 && x < size && y >= 0 && y < size) { // 如果位置合法 reveal(x, y); } } displayBoard(); System.out.println("游戏结束!"); } public static void main(String[] args) { MineSweeper game = new MineSweeper(10, 10); // 创建一个大小为10x10,雷数为10的扫雷游戏 game.run(); } } ``` 这个程序实现了一个简单的扫雷游戏,可以自定义面板大小和雷的数量。玩家每次输入要揭示的位置,程序会判断该位置是否是雷,如果是雷则游戏结束,否则会递归揭示周围的位置直到所有不是雷的位置都被揭示出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值