ITPub博客

首页 > 应用开发 > Java > 使用Java编写简单游戏指南

使用Java编写简单游戏指南

投稿 Java 作者:bhluo 时间:2025-11-05 16:25:42 0 删除 编辑

下面我将介绍如何使用Java编写几个不同类型的简单游戏,从控制台游戏到图形界面游戏。

1. 控制台猜数字游戏

这是一个简单的文本基础游戏,适合初学者理解Java基础语法。

java1import java.util.Scanner;2import java.util.Random;34public class GuessNumberGame {5    public static void main(String[] args) {6        Scanner scanner = new Scanner(System.in);7        Random random = new Random();8        9        int numberToGuess = random.nextInt(100) + 1; // 1-100的随机数10        int numberOfTries = 0;11        boolean hasWon = false;12        13        System.out.println("欢迎来到猜数字游戏!");14        System.out.println("我已经想好了一个1到100之间的数字,请猜猜是多少?");15        16        while (!hasWon) {17            System.out.print("请输入你的猜测: ");18            int guess = scanner.nextInt();19            numberOfTries++;20            21            if (guess == numberToGuess) {22                hasWon = true;23                System.out.println("恭喜你!你猜对了!");24                System.out.println("你一共猜了 " + numberOfTries + " 次。");25            } else if (guess < numberToGuess) {26                System.out.println("太小了,再大一点!");27            } else {28                System.out.println("太大了,再小一点!");29            }30        }31        32        scanner.close();33    }34}

2. 简单的文字冒险游戏

java1import java.util.Scanner;23public class TextAdventureGame {4    public static void main(String[] args) {5        Scanner scanner = new Scanner(System.in);6        7        System.out.println("欢迎来到神秘岛冒险!");8        System.out.println("你醒来发现自己在一个陌生的海滩上。");9        10        boolean gameOver = false;11        int health = 100;12        boolean hasKey = false;13        14        while (!gameOver) {15            System.out.println("\n你可以做以下事情:");16            System.out.println("1. 探索海滩");17            System.out.println("2. 进入丛林");18            System.out.println("3. 检查背包");19            System.out.println("4. 休息");20            System.out.println("5. 退出游戏");21      <"tzwcz.com"> <"ynazc.com"> <"fjtiyu.com">        System.out.print("选择你的行动: ");22            23            int choice = scanner.nextInt();24            25            switch (choice) {26                case 1:27                    System.out.println("你在海滩上发现了一个旧瓶子,里面有一张地图!");28                    break;29                case 2:30                    if (hasKey) {31                        System.out.println("你使用钥匙打开了丛林中的古老宝箱,找到了回家的路!");32                        System.out.println("恭喜你赢得了游戏!");33                        gameOver = true;34                    } else {35                        System.out.println("你在丛林中遇到了一只野兽!");36                        health -= 20;37                        System.out.println("你失去了20点生命值。当前生命值: " + health);38                        if (health <= 0) {39                            System.out.println("游戏结束!你被野兽击败了。");40                            gameOver = true;41                        }42                    }43                    break;44                case 3:45                    if (!hasKey) {46                        System.out.println("你在沙滩上发现了一把钥匙!");47                        hasKey = true;48                    } else {49                        System.out.println("你的背包里有一把钥匙。");50                    }51                    break;52                case 4:53                    health = Math.min(100, health + 10);54                    System.out.println("你休息了一会儿。生命值恢复到 " + health);55                    break;56                case 5:57                    System.out.println("感谢游玩,再见!");58                    gameOver = true;59                    break;60                default:61                    System.out.println("无效的选择,请重新输入。");62            }63        }64        65        scanner.close();66    }67}

3. 使用Swing的图形界面游戏 - 贪吃蛇

这是一个更复杂的例子,使用Java Swing创建图形界面。

java1import javax.swing.*;2import java.awt.*;3import java.awt.event.*;4import java.util.Random;56public class SnakeGame extends JFrame {7    8    private static final int TILE_SIZE = 25;9    private static final int WIDTH = 20;10    private static final int HEIGHT = 20;11    private static final int ALL_TILES = WIDTH * HEIGHT;12    13    private final int[] x = new int[ALL_TILES];14    private final int[] y = new int[ALL_TILES];15  <"iqiyitiyu.com"> <"tiyuzhib.com"> <"zuagi.com">    16    private int bodyParts = 3;17    private int applesEaten;18    private int appleX;19    private int appleY;20    21    private char direction = 'R';22    private boolean running = false;23    private Timer timer;24    private Random random;25    26    public SnakeGame() {27        random = new Random();28        this.setTitle("贪吃蛇游戏");29        this.setSize(WIDTH * TILE_SIZE, HEIGHT * TILE_SIZE);30        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);31        this.setResizable(false);32        this.add(new GamePanel());33        this.pack();34        this.setVisible(true);35        36        startGame();37    }38    39    public void startGame() {40        newApple();41        running = true;42        timer = new Timer(100, new GameLoop());43        timer.start();44    }45    46    public void newApple() {47        appleX = random.nextInt(WIDTH) * TILE_SIZE;48        appleY = random.nextInt(HEIGHT) * TILE_SIZE;49    }50    51    public void move() {52        for (int i = bodyParts; i > 0; i--) {53            x[i] = x[i - 1];54            y[i] = y[i - 1];55        }56        57        switch (direction) {58            case 'U':59                y[0] -= TILE_SIZE;60                break;61            case 'D':62                y[0] += TILE_SIZE;63                break;64            case 'L':65                x[0] -= TILE_SIZE;66                break;67            case 'R':68                x[0] += TILE_SIZE;69                break;70        }71    }72    73    public void checkApple() {74        if ((x[0] == appleX) && (y[0] == appleY)) {75            bodyParts++;76            applesEaten++;77            newApple();78        }79    }80    81    public void checkCollisions() {82        // 检查是否撞到自己83        for (int i = bodyParts; i > 0; i--) {84            if ((x[0] == x[i]) && (y[0] == y[i])) {85                running = false;86            }87        }88        89        // 检查是否撞到边界90        if (x[0] < 0 || x[0] >= WIDTH * TILE_SIZE || y[0] < 0 || y[0] >= HEIGHT * TILE_SIZE) {91            running = false;92        }93        94        if (!running) {95            timer.stop();96        }97    }98    99    private class GamePanel extends JPanel implements KeyListener {100        101        public GamePanel() {102            this.setPreferredSize(new Dimension(WIDTH * TILE_SIZE, HEIGHT * TILE_SIZE));103            this.setBackground(Color.BLACK);104            this.setFocusable(true);105            this.addKeyListener(this);106        }107        108        @Override109        public void paintComponent(Graphics g) {110            super.paintComponent(g);111            112            if (running) {113                // 绘制苹果114                g.setColor(Color.RED);115                g.fillOval(appleX, appleY, TILE_SIZE, TILE_SIZE);116                117                // 绘制蛇118                for (int i = 0; i < bodyParts; i++) {119                    if (i == 0) {120                        g.setColor(Color.GREEN);121                    } else {122                        g.setColor(new Color(45, 180, 0));123                    }124                    g.fillRect(x[i], y[i], TILE_SIZE, TILE_SIZE);125                }126                127                // 显示分数128                g.setColor(Color.WHITE);129                g.setFont(new Font("Arial", Font.BOLD, 20));130                g.drawString("分数: " + applesEaten, 10, 20);131            } else {132                gameOver(g);133            }134        }135        136        public void gameOver(Graphics g) {137            // 游戏结束文字138            g.setColor(Color.RED);139            g.setFont(new Font("Arial", Font.BOLD, 50));140            FontMetrics metrics = getFontMetrics(g.getFont());141            g.drawString("游戏结束", 142                (getWidth() - metrics.stringWidth("游戏结束")) / 2, 143                getHeight() / 2);144            145            // 显示最终分数146            g.setColor(Color.WHITE);147            g.setFont(new Font("Arial", Font.BOLD, 20));148            g.drawString("最终分数: " + applesEaten, 149                (getWidth() - metrics.stringWidth("最终分数: " + applesEaten)) / 2, 150                getHeight() / 2 + 50);151        }152        153        @Override154        public void keyPressed(KeyEvent e) {155            switch (e.getKeyCode()) {156                case KeyEvent.VK_LEFT:157                    if (direction != 'R') {158                        direction = 'L';159                    }160                    break;161                case KeyEvent.VK_RIGHT:162                    if (direction != 'L') {163                        direction = 'R';164                    }165                    break;166                case KeyEvent.VK_UP:167                    if (direction != 'D') {168                        direction = 'U';169                    }170                    break;171                case KeyEvent.VK_DOWN:172                    if (direction != 'U') {173                        direction = 'D';174                    }175                    break;176            }177        }178        179        @Override180        public void keyTyped(KeyEvent e) {}181        182        @Override183        public void keyReleased(KeyEvent e) {}184    }185    186    private class GameLoop implements ActionListener {187        @Override188        public void actionPerformed(ActionEvent e) {189            if (running) {190                move();191                checkApple();192                checkCollisions();193            }194            repaint();195        }196    }197    198    public static void main(String[] args) {199        new SnakeGame();200    }201}

4. 使用JavaFX的简单游戏 - 打砖块

java1import javafx.application.Application;2import javafx.scene.Scene;3import javafx.scene.input.KeyCode;4import javafx.scene.layout.Pane;5import javafx.scene.paint.Color;6import javafx.scene.shape.Circle;7import javafx.scene.shape.Rectangle;8import javafx.stage.Stage;910public class BreakoutGame extends Application {11    12    private static final int WIDTH = 800;13    private static final int HEIGHT = 600;14    private static final int PADDLE_WIDTH = 100;15    private static final int PADDLE_HEIGHT = 20;16    private static final int BALL_SIZE = 15;17    private static final int BRICK_WIDTH = 75;18    private static final int BRICK_HEIGHT = 20;19   <"tzjp888.com"> <"bjxjwhcb.com"> <"liangshiyajigd.com">   20    private Pane root;21    private Rectangle paddle;22    private Circle ball;23    private double ballDx = 2, ballDy = -3;24    private boolean gameStarted = false;25    26    @Override27    public void start(Stage primaryStage) {28        root = new Pane();29        root.setPrefSize(WIDTH, HEIGHT);30        31        // 创建挡板32        paddle = new Rectangle((WIDTH - PADDLE_WIDTH) / 2, HEIGHT - 50, PADDLE_WIDTH, PADDLE_HEIGHT);33        paddle.setFill(Color.BLUE);34        root.getChildren().add(paddle);35        36        // 创建球37        ball = new Circle(WIDTH / 2, HEIGHT / 2, BALL_SIZE, Color.RED);38        root.getChildren().add(ball);39        40        // 创建砖块41        createBricks();42        43        // 设置键盘控制44        root.setOnKeyPressed(event -> {45            if (event.getCode() == KeyCode.LEFT) {46                paddle.setX(Math.max(0, paddle.getX() - 20));47            } else if (event.getCode() == KeyCode.RIGHT) {48                paddle.setX(Math.min(WIDTH - PADDLE_WIDTH, paddle.getX() + 20));49            } else if (event.getCode() == KeyCode.SPACE) {50                gameStarted = true;51            }52        });53        54        // 游戏循环55        new javafx.animation.AnimationTimer() {56            @Override57            public void handle(long now) {58                if (gameStarted) {59                    moveBall();60                    checkCollisions();61                }62            }63        }.start();64        65        Scene scene = new Scene(root);66        scene.setFill(Color.BLACK);67        primaryStage.setTitle("打砖块游戏");68        primaryStage.setScene(scene);69        primaryStage.setResizable(false);70        primaryStage.show();71        72        root.requestFocus();73    }74    75    private void createBricks() {76        int brickCount = 0;77        for (int i = 0; i < 5; i++) {78            for (int j = 0; j < WIDTH / BRICK_WIDTH; j++) {79                Rectangle brick = new Rectangle(j * BRICK_WIDTH, i * (BRICK_HEIGHT + 10) + 50, 80                                               BRICK_WIDTH - 2, BRICK_HEIGHT);81                brick.setFill(Color.hsb(brickCount * 10, 1.0, 1.0));82                root.getChildren().add(brick);83                brickCount++;84            }85        }86    }87    88    private void moveBall() {89        ball.setCenterX(ball.getCenterX() + ballDx);90        ball.setCenterY(ball.getCenterY() + ballDy);91        92        // 边界检查93        if (ball.getCenterX() <= BALL_SIZE || ball.getCenterX() >= WIDTH - BALL_SIZE) {94            ballDx *= -1;95        }96        if (ball.getCenterY() <= BALL_SIZE) {97            ballDy *= -1;98        }99        100        // 游戏结束检查101        if (ball.getCenterY() > HEIGHT) {102            gameStarted = false;103            ball.setCenterX(WIDTH / 2);104            ball.setCenterY(HEIGHT / 2);105        }106    }107    108    private void checkCollisions() {109        // 检查与挡板的碰撞110        if (ball.getBoundsInParent().intersects(paddle.getBoundsInParent())) {111            ballDy = -Math.abs(ballDy);112            ball.setCenterY(paddle.getY() - BALL_SIZE);113        }114        115        // 检查与砖块的碰撞116        for (javafx.scene.Node node : root.getChildren()) {117            if (node instanceof Rectangle && !(node == paddle)) {118                Rectangle brick = (Rectangle) node;119                if (ball.getBoundsInParent().intersects(brick.getBoundsInParent())) {120                    root.getChildren().remove(brick);121                    ballDy *= -1;122                    break;123                }124            }125        }126    }127    128    public static void main(String[] args) {129        launch(args);130    }131}

游戏开发建议

  1. 从简单开始:先从小游戏开始,如猜数字或井字棋,逐步增加复杂性
  2. 使用游戏引擎:对于更复杂的游戏,考虑使用游戏引擎如libGDX或jMonkeyEngine
  3. 面向对象设计:将游戏元素封装为类(如Player、Enemy、GameWorld等)
  4. 游戏循环:理解并实现游戏循环(处理输入、更新游戏状态、渲染)
  5. 碰撞检测:这是游戏开发的关键部分
  6. 资源管理:学习如何加载和管理图像、声音等资源


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/19545/viewspace-3099842/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2015-11-01

  • 博文量
    895
  • 访问量
    933246