基于java的吃豆子小游戏

游戏规则

  1. 目标:控制角色收集所有豆子,避免与敌人碰撞。
  2. 玩家控制:使用箭头键移动。
  3. 迷宫:19x19 网格,0 为通路,1 为墙壁。
  4. 敌人:3 个从右下角开始,随机移动,追踪玩家。
  5. 豆子:3 个豆子随机出现在迷宫空白处,玩家需要收集。
  6. 胜利条件:收集所有豆子。
  7. 失败条件:与敌人碰撞。
  8. 界面
    玩家:蓝色方块
    敌人:红色方块
    豆子:绿色圆形
    在这里插入图片描述

代码

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List; // 确保使用的是 java.util.List
import java.util.ArrayList; // 使用 java.util.ArrayList
import java.util.Arrays; // 使用 java.util.Arrays
import java.util.Collections; // 使用 java.util.Collections

public class MazeGame extends JFrame implements KeyListener {
    private static final int ROWS = 19;
    private static final int COLS = 19;
    private static final int CELL_SIZE = 30;
    private int[][] maze;
    private int playerX = 0, playerY = 0;
    private List<int[]> enemies;
    private List<int[]> beans;
    private int collectedBeans = 0;
    private boolean gameOver = false;
    private MazePanel mazePanel;
    private Random random = new Random();

    // 每个敌人的方向 {dx, dy}
    private final int[][] DIRECTIONS = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; // 上, 左, 下, 右

    public MazeGame() {
        setTitle("Maze Game");
        setSize(COLS * CELL_SIZE + 16, ROWS * CELL_SIZE + 39); // Adjust for window borders
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);
        addKeyListener(this);

        mazePanel = new MazePanel();
        add(mazePanel);

        createMaze(); // 手动创建迷宫
        initializeEnemies();
        initializeBeans();

        javax.swing.Timer timer = new javax.swing.Timer(400, e -> moveEnemies());
        timer.start();
    }

    private void createMaze() {
        // 手动定义迷宫,0 表示通路,1 表示墙壁
        maze = new int[][]{
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        };
        if (maze.length != ROWS || maze[0].length != COLS) {
            throw new IllegalArgumentException("迷宫数组的尺寸必须为 " + ROWS + " x " + COLS);
        }
    }

    private void initializeEnemies() {
        enemies = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            enemies.add(new int[]{ROWS - 1, COLS - 1});
        }
    }

    private void initializeBeans() {
        beans = new ArrayList<>();
        List<int[]> emptySpaces = new ArrayList<>();

        // 找到所有空白位置
        for (int i = 0; i < ROWS; i++) {
            for (int j = 0; j < COLS; j++) {
                if (maze[i][j] == 0 && !isOccupied(i, j) && (i != playerX || j != playerY)) {
                    emptySpaces.add(new int[]{i, j});
                }
            }
        }

        // 随机选择位置放置豆子
        Collections.shuffle(emptySpaces); // 打乱空白位置的顺序
        for (int i = 0; i < 3 && i < emptySpaces.size(); i++) {
            beans.add(emptySpaces.get(i));
        }
    }

    private void moveEnemies() {
        if (gameOver) return;
        for (int[] enemy : enemies) {
            int[] direction = getDirectionTowardsPlayer(enemy[0], enemy[1]);
            int newX = enemy[0] + direction[0];
            int newY = enemy[1] + direction[1];

            if (isValidMove(newX, newY) && !isOccupied(newX, newY)) {
                enemy[0] = newX;
                enemy[1] = newY;
            } else {
                moveEnemyRandomly(enemy);
            }
        }
        checkGameStatus();
        mazePanel.repaint();
    }

    private void moveEnemyRandomly(int[] enemy) {
        Collections.shuffle(Arrays.asList(DIRECTIONS)); // Shuffle directions
        for (int[] direction : DIRECTIONS) {
            int newX = enemy[0] + direction[0];
            int newY = enemy[1] + direction[1];
            if (isValidMove(newX, newY) && !isOccupied(newX, newY)) {
                enemy[0] = newX;
                enemy[1] = newY;
                return;
            }
        }
    }

    private int[] getDirectionTowardsPlayer(int x, int y) {
        int dx = playerX - x;
        int dy = playerY - y;
        if (Math.abs(dx) > Math.abs(dy)) {
            return new int[]{Integer.compare(dx, 0), 0};
        } else {
            return new int[]{0, Integer.compare(dy, 0)};
        }
    }

    private boolean isOccupied(int x, int y) {
        return enemies.stream().anyMatch(e -> e[0] == x && e[1] == y);
    }

    private boolean isValidMove(int x, int y) {
        return x >= 0 && x < ROWS && y >= 0 && y < COLS && maze[x][y] == 0;
    }

    private void checkGameStatus() {
        for (int[] enemy : enemies) {
            if (playerX == enemy[0] && playerY == enemy[1]) {
                gameOver("游戏失败");
                return;
            }
        }
        for (Iterator<int[]> iterator = beans.iterator(); iterator.hasNext(); ) {
            int[] bean = iterator.next();
            if (playerX == bean[0] && playerY == bean[1]) {
                iterator.remove();
                collectedBeans++;
                if (beans.isEmpty()) {
                    gameOver("游戏胜利");
                }
                break;
            }
        }
    }

    private void gameOver(String message) {
        gameOver = true;
        JOptionPane.showMessageDialog(this, message);
        System.exit(0);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (gameOver) return;

        int newX = playerX, newY = playerY;
        switch (e.getKeyCode()) {
            case KeyEvent.VK_UP -> newX--;
            case KeyEvent.VK_DOWN -> newX++;
            case KeyEvent.VK_LEFT -> newY--;
            case KeyEvent.VK_RIGHT -> newY++;
        }

        if (isValidMove(newX, newY)) {
            playerX = newX;
            playerY = newY;
            checkGameStatus();
            mazePanel.repaint();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    private class MazePanel extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (int i = 0; i < ROWS; i++) {
                for (int j = 0; j < COLS; j++) {
                    if (maze[i][j] == 1) {
                        g.setColor(Color.BLACK);
                        g.fillRect(j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE);
                    }
                }
            }

            // 绘制玩家
            g.setColor(Color.BLUE);
            g.fillRect(playerY * CELL_SIZE, playerX * CELL_SIZE, CELL_SIZE, CELL_SIZE);

            // 绘制敌人
            g.setColor(Color.RED);
            for (int[] enemy : enemies) {
                g.fillRect(enemy[1] * CELL_SIZE, enemy[0] * CELL_SIZE, CELL_SIZE, CELL_SIZE);
            }

            // 绘制豆子
            g.setColor(Color.GREEN);
            for (int[] bean : beans) {
                g.fillOval(bean[1] * CELL_SIZE, bean[0] * CELL_SIZE, CELL_SIZE, CELL_SIZE);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            MazeGame game = new MazeGame();
            game.setVisible(true);
        });
    }
}

  • 12
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值