21xrx.com
2024-12-23 02:11:18 Monday
登录
文章检索 我的文章 写文章
《Java游戏开发入门教程》:一份简单的Java游戏代码大全
2023-06-15 15:17:08 深夜i     --     --
Java游戏开发 贪吃蛇游戏 程序代码

《Java游戏开发入门教程》:一份简单的Java游戏代码大全

Java语言的高性能和可靠性为游戏开发提供了一个稳定的平台。无论是开发基于控制台的文字游戏,还是基于Java图形用户界面(GUI)的三维游戏,Java的资源库和插件库都为游戏开发人员提供了广泛的资源。

在这份入门教程中,我们将介绍Java游戏开发的基础知识,并提供一些简单的游戏代码示例。以下是一个基于Java的贪吃蛇游戏,以及它的完整代码:


import javax.swing.*;

import java.awt.*;

public class SnakeGame extends JFrame {

  public SnakeGame() {

    setTitle("贪吃蛇游戏");

    setSize(320, 340);

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    setLocationRelativeTo(null);

    setResizable(false);

    SnakeBoard board = new SnakeBoard();

    add(board);

  }

  public static void main(String[] args) {

    EventQueue.invokeLater(() -> {

      JFrame ex = new SnakeGame();

      ex.setVisible(true);

    });

  }

}

class SnakeBoard extends JPanel {

  private final int BOARD_WIDTH = 300;

  private final int BOARD_HEIGHT = 300;

  private final int OFF_SET = 10;

  private final int DOT_SIZE = 10;

  private final int ALL_DOTS = 900;

  private final int RANDOM_POS = 29;

  private final int[] x = new int[ALL_DOTS];

  private final int[] y = new int[ALL_DOTS];

  private int dots;

  private int apple_x;

  private int apple_y;

  private boolean leftDirection = false;

  private boolean rightDirection = true;

  private boolean upDirection = false;

  private boolean downDirection = false;

  private boolean inGame = true;

  private Timer timer;

  private Image dot;

  private Image apple;

  private Image head;

  public SnakeBoard() {

    addKeyListener(new KeyAdapter());

    setBackground(Color.black);

    setFocusable(true);

    setPreferredSize(new Dimension(BOARD_WIDTH, BOARD_HEIGHT));

    loadImages();

    initGame();

  }

  private void loadImages() {

    ImageIcon iid = new ImageIcon("src/resources/dot.png");

    dot = iid.getImage();

    ImageIcon iia = new ImageIcon("src/resources/apple.png");

    apple = iia.getImage();

    ImageIcon iih = new ImageIcon("src/resources/head.png");

    head = iih.getImage();

  }

  private void initGame() {

    dots = 3;

    for (int z = 0; z < dots; z++) {

      x[z] = 50 - z * 10;

      y[z] = 50;

    }

    locateApple();

    timer = new Timer(140, e -> {

      if (inGame) {

        checkApple();

        checkCollision();

        move();

      }

      repaint();

    });

    timer.start();

  }

  @Override

  protected void paintComponent(Graphics g) {

    super.paintComponent(g);

    doDrawing(g);

  }

  private void doDrawing(Graphics g) {

    if (inGame) {

      g.drawImage(apple, apple_x, apple_y, this);

      for (int z = 0; z < dots; z++) {

        if (z == 0) {

          g.drawImage(head, x[z], y[z], this);

        } else {

          g.drawImage(dot, x[z], y[z], this);

        }

      }

    } else {

      gameOver(g);

    }

  }

  private void gameOver(Graphics g) {

    String msg = "Game Over";

    Font small = new Font("Helvetica", Font.BOLD, 14);

    FontMetrics metr = getFontMetrics(small);

    g.setColor(Color.white);

    g.setFont(small);

    g.drawString(msg, (BOARD_WIDTH - metr.stringWidth(msg)) / 2, BOARD_HEIGHT / 2);

  }

  private void checkApple() {

    if ((x[0] == apple_x) && (y[0] == apple_y)) {

      dots++;

      locateApple();

    }

  }

  private void move() {

    for (int z = dots; z > 0; z--) {

      x[z] = x[(z - 1)];

      y[z] = y[(z - 1)];

    }

    if (leftDirection) {

      x[0] -= DOT_SIZE;

    }

    if (rightDirection) {

      x[0] += DOT_SIZE;

    }

    if (upDirection) {

      y[0] -= DOT_SIZE;

    }

    if (downDirection) {

      y[0] += DOT_SIZE;

    }

  }

  private void checkCollision() {

    for (int z = dots; z > 0; z--) {

      if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z]))

        inGame = false;

      

    }

    if (y[0] >= BOARD_HEIGHT)

      inGame = false;

    

    if (y[0] < 0)

      inGame = false;

    

    if (x[0] >= BOARD_WIDTH)

      inGame = false;

    

    if (x[0] < 0)

      inGame = false;

    

    if (!inGame) {

      timer.stop();

    }

  }

  private void locateApple() {

    int r = (int) (Math.random() * RANDOM_POS);

    apple_x = ((r * DOT_SIZE));

    r = (int) (Math.random() * RANDOM_POS);

    apple_y = ((r * DOT_SIZE));

  }

  public class KeyAdapter extends java.awt.event.KeyAdapter {

    @Override

    public void keyPressed(java.awt.event.KeyEvent e) {

      int key = e.getKeyCode();

      if ((key == java.awt.event.KeyEvent.VK_LEFT) && (!rightDirection))

        leftDirection = true;

        upDirection = false;

        downDirection = false;

      

      if ((key == java.awt.event.KeyEvent.VK_RIGHT) && (!leftDirection))

        rightDirection = true;

        upDirection = false;

        downDirection = false;

      

      if ((key == java.awt.event.KeyEvent.VK_UP) && (!downDirection))

        upDirection = true;

        rightDirection = false;

        leftDirection = false;

      

      if ((key == java.awt.event.KeyEvent.VK_DOWN) && (!upDirection))

        downDirection = true;

        rightDirection = false;

        leftDirection = false;

      

    }

  }

}

这是一个简单的贪吃蛇游戏,用Java语言编写。游戏界面是一个300像素乘以300像素的面板,里面包含了一些小圆点组成的蛇,还有一个红色的苹果。

玩家可以通过按下键盘上的箭头键来控制蛇的移动方向,吃掉苹果可以增加蛇的长度。如果蛇的头部与它的身体相撞,或者蛇撞到了屏幕边缘,游戏就会结束。

这个小游戏代码虽短,但是包含了许多Java游戏开发的基础知识,比如使用图像、坐标计算、游戏逻辑等等。开发者可以在此基础上进行扩展和优化,创作出更加有趣的游戏作品。

代码示例、文档、插件库和其他资源,可以在GitHub等开源社区中找到。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复