21xrx.com
2024-11-05 20:28:47 Tuesday
登录
文章检索 我的文章 写文章
如何用Java编写简单的游戏
2023-06-18 01:01:17 深夜i     --     --
Java编程 2D游戏开发 Snake游戏

Java是一种强大的多用途编程语言,除了常见的应用开发,它还可以用于编写游戏。在这篇文章中,我们将介绍如何使用Java编写简单的2D游戏。我们将通过一个名为“Snake”的游戏来演示,该游戏需要玩家控制一条蛇通过屏幕上的障碍物,并吃掉尽可能多的食物。

在开始之前,你需要确保已经安装了Java开发环境(JDK)和一个称为Eclipse的Java集成开发环境(IDE)。 还需要学习一些Java编程,例如基本语法和OOP编程概念。

我们先创建游戏的主要类-“SnakeGame.java”。


import javax.swing.JFrame;

public class SnakeGame extends JFrame {

  public SnakeGame() {

    add(new Board());

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setSize(480, 420);

    setLocationRelativeTo(null);

    setTitle("Snake");

    setResizable(false);

    setVisible(true);

  }

  public static void main(String[] args) {

    new SnakeGame();

  }

}

在该类中,我们创建了一个名为“Board”的对象,用于呈现游戏地图。我们还通过setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)设置游戏窗口的关闭操作,setSize设置游戏窗口的大小, setTitle设置游戏窗口的标题,setResizable设置游戏窗口的大小是否可以调整,并通过setVisible(true)将游戏窗口设置为可见。

接下来,我们创建一个名为“Board”的类,它将作为游戏地图的主要组件。在此类中,我们设置了游戏地图的背景颜色,并记录蛇的位置和食物的位置。


import java.awt.Color;

import java.awt.Dimension;

import java.awt.Graphics;

import java.awt.Point;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.util.Random;

import javax.swing.JPanel;

import javax.swing.Timer;

public class Board extends JPanel implements KeyListener, ActionListener {

  private final int BOARD_WIDTH = 480;

  private final int BOARD_HEIGHT = 360;

  private final int PIXEL_SIZE = 10;

  private final int TOTAL_PIXELS = (BOARD_WIDTH * BOARD_HEIGHT)

      / (PIXEL_SIZE * PIXEL_SIZE);

  private boolean leftDirection = false;

  private boolean rightDirection = true;

  private boolean upDirection = false;

  private boolean downDirection = false;

  private boolean inGame = true;

  private Timer timer;

  private Point food;

  private Point[] snake = new Point[TOTAL_PIXELS];

  private int snakeSize = 3;

  public Board() {

    addKeyListener(this);

    setBackground(Color.gray);

    setFocusable(true);

    setPreferredSize(new Dimension(BOARD_WIDTH, BOARD_HEIGHT));

    initGame();

  }

  public void initGame() {

    snake[0] = new Point(100, 100);

    snake[1] = new Point(90, 100);

    snake[2] = new Point(80, 100);

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

      snake[i] = new Point(100 - (i * 10), 100);

    }

    generateFood();

    timer = new Timer(100, this);

    timer.start();

  }

  public void generateFood() {

    int x = (int) (Math.random() * ((BOARD_WIDTH - PIXEL_SIZE) / PIXEL_SIZE + 1))

        * PIXEL_SIZE;

    int y = (int) (Math.random() * ((BOARD_HEIGHT - PIXEL_SIZE) / PIXEL_SIZE + 1))

        * PIXEL_SIZE;

    food = new Point(x, y);

  }

  public void checkFood() {

    if (snake[0].equals(food)) {

      snakeSize++;

      generateFood();

    }

  }

  public void checkCollision() {

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

      if (snake[0].equals(snake[i]))

        inGame = false;

      

    }

    if (snake[0].x < 0 || snake[0].x > BOARD_WIDTH - PIXEL_SIZE

        || snake[0].y < 0 || snake[0].y > BOARD_HEIGHT - PIXEL_SIZE)

      inGame = false;

    

  }

  public void move() {

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

      snake[i] = snake[i - 1];

    }

    if (leftDirection) {

      snake[0] = new Point(snake[0].x - PIXEL_SIZE, snake[0].y);

    }

    if (rightDirection) {

      snake[0] = new Point(snake[0].x + PIXEL_SIZE, snake[0].y);

    }

    if (upDirection) {

      snake[0] = new Point(snake[0].x, snake[0].y - PIXEL_SIZE);

    }

    if (downDirection) {

      snake[0] = new Point(snake[0].x, snake[0].y + PIXEL_SIZE);

    }

  }

  public void actionPerformed(ActionEvent e) {

    if (inGame) {

      checkFood();

      checkCollision();

      move();

    }

    repaint();

  }

  public void paintComponent(Graphics g) {

    super.paintComponent(g);

    if (inGame) {

      g.setColor(Color.red);

      g.fillRect(food.x, food.y, PIXEL_SIZE, PIXEL_SIZE);

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

        if (i == 0) {

          g.setColor(Color.black);

          g.fillRect(snake[i].x, snake[i].y, PIXEL_SIZE, PIXEL_SIZE);

        } else {

          g.setColor(Color.gray);

          g.fillRect(snake[i].x, snake[i].y, PIXEL_SIZE, PIXEL_SIZE);

        }

      }

      g.setColor(Color.white);

      g.drawRect(0, 0, BOARD_WIDTH - 1, BOARD_HEIGHT - 1);

    } else {

      g.drawString("Game Over", BOARD_WIDTH / 2 - 30, BOARD_HEIGHT / 2);

    }

  }

  public void keyPressed(KeyEvent e) {

    int key = e.getKeyCode();

    if ((key == KeyEvent.VK_LEFT) && (!rightDirection))

      leftDirection = true;

      upDirection = false;

      downDirection = false;

    

    if ((key == KeyEvent.VK_RIGHT) && (!leftDirection))

      rightDirection = true;

      upDirection = false;

      downDirection = false;

    

    if ((key == KeyEvent.VK_UP) && (!downDirection))

      upDirection = true;

      rightDirection = false;

      leftDirection = false;

    

    if ((key == KeyEvent.VK_DOWN) && (!upDirection))

      downDirection = true;

      rightDirection = false;

      leftDirection = false;

    

  }

  public void keyReleased(KeyEvent e)

  

  public void keyTyped(KeyEvent e)

  

}

在“Board”类中,我们更新蛇的位置,检查是否吃到了食物,检查是否出现碰撞,并调用重新绘制方法(repaint)更新游戏地图。

最后,在主菜单中,我们实例化SnakeGame类并通过main方法启动游戏。

以上就是简单的Java游戏开发,希望它能够帮助你开始自己的Java游戏编程之旅。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章