21xrx.com
2024-05-19 18:14:45 Sunday
登录
文章检索 我的文章 写文章
Java实现简单贪吃蛇游戏-附PPT介绍
2023-06-16 22:55:11 深夜i     --     --
Java 贪吃蛇 游戏编程

贪吃蛇是一款经典的小游戏,它的玩法简单而有趣,能够带给人们愉悦的游戏体验。利用Java语言,我们可以轻松地实现一个简单的贪吃蛇游戏,下面来介绍一下实现的过程。

首先,我们需要创建一个窗体,作为我们游戏的界面。然后,我们需要定义一个蛇的类,包括蛇头、蛇身和蛇尾等部分。在蛇类中,我们还需要定义一些方法,如“移动”、“增加长度”、“判断是否吃到食物”等。

接着,我们需要定义一个食物类,表示游戏中需要吃的食物。该类主要包含食物的位置、食物被吃掉的方法等。

最后,我们需要定义一个控制类,该类主要负责控制游戏的运行和更新。在控制类中,我们需要实现键盘监听事件,接收玩家的方向控制,同时还需要不断检测蛇与食物的接触等。

下面是一些Java代码案例,实现了蛇的移动和食物的生成,记得另外导入必要的组件库。


import java.awt.*;

import javax.swing.*;

public class Snake extends JPanel {

  private static final long serialVersionUID = 1L;

  private static final int WIDTH = 500;

  private static final int HEIGHT = 500;

  private static final int DOT_SIZE = 10;

  private static final int ALL_DOTS = 900;

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

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

  private int dots;

  private int foodX;

  private int foodY;

  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 ball;

  private Image apple;

  private Image head;

  public Snake() {

    initGame();

  }

  private void initGame() {

    addKeyListener(new TAdapter());

    setBackground(Color.black);

    setPreferredSize(new Dimension(WIDTH, HEIGHT));

    setFocusable(true);

    loadImages();

    initDots();

    initFood();

    timer = new Timer(140, this);

    timer.start();

  }

  private void loadImages() {

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

    ball = 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 initDots() {

    dots = 3;

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

      snakeX[z] = 50 - z * 10;

      snakeY[z] = 50;

    }

  }

  private void initFood() {

    foodX = (int) (Math.random() * WIDTH / DOT_SIZE) * DOT_SIZE;

    foodY = (int) (Math.random() * HEIGHT / DOT_SIZE) * DOT_SIZE;

  }

  @Override

  protected void paintComponent(Graphics g) {

    super.paintComponent(g);

    doDrawing(g);

  }

  private void doDrawing(Graphics g) {

    if (inGame) {

      g.drawImage(apple, foodX, foodY, this);

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

        if (z == 0) {

          g.drawImage(head, snakeX[z], snakeY[z], this);

        } else {

          g.drawImage(ball, snakeX[z], snakeY[z], this);

        }

      }

      Toolkit.getDefaultToolkit().sync();

    } 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, (WIDTH - metr.stringWidth(msg)) / 2, HEIGHT / 2);

  }

  private void move() {

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

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

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

    }

    if (leftDirection) {

      snakeX[0] -= DOT_SIZE;

    }

    if (rightDirection) {

      snakeX[0] += DOT_SIZE;

    }

    if (upDirection) {

      snakeY[0] -= DOT_SIZE;

    }

    if (downDirection) {

      snakeY[0] += DOT_SIZE;

    }

  }

  private void checkFood() {

    if ((snakeX[0] == foodX) && (snakeY[0] == foodY)) {

      dots++;

      initFood();

    }

  }

  private void checkCollision() {

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

      if ((z > 4) && (snakeX[0] == snakeX[z]) && (snakeY[0] == snakeY[z]))

        inGame = false;

      

    }

    if (snakeY[0] >= HEIGHT)

      inGame = false;

    

    if (snakeY[0] < 0)

      inGame = false;

    

    if (snakeX[0] >= WIDTH)

      inGame = false;

    

    if (snakeX[0] < 0)

      inGame = false;

    

    if (!inGame) {

      timer.stop();

    }

  }

  private class TAdapter extends KeyAdapter {

    @Override

    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;

      

    }

  }

  @Override

  public void actionPerformed(ActionEvent e) {

    if (inGame) {

      checkFood();

      checkCollision();

      move();

    }

    repaint();

  }

  public static void main(String[] args) {

    JFrame frame = new JFrame("贪吃蛇");

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.getContentPane().add(new Snake());

    frame.pack();

    frame.setLocationRelativeTo(null);

    frame.setVisible(true);

  }

}

最后,附上Java简单贪吃蛇的PPT介绍,方便大家学习和使用。

  
  

评论区

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