21xrx.com
2025-04-22 21:31:43 Tuesday
文章检索 我的文章 写文章
Java实现贪吃蛇游戏
2023-06-16 09:34:20 深夜i     18     0
Java 贪吃蛇 游戏

贪吃蛇游戏是一种非常经典的游戏,也是很多初学者使用的练手项目。在Java语言中,我们可以很轻松地实现这个游戏。接下来我们就来看一下如何用Java实现贪吃蛇游戏。

首先,我们需要明确一下贪吃蛇游戏的规则。游戏中,蛇头会不停地前进,在屏幕上放置一些食物。当蛇头吃到食物时,便会变得更长。如果蛇头碰到了自己的身体或屏幕边界,则游戏结束。具体实现流程如下:

1. 定义一个Snake类,用来表示蛇。该类中需要包含一些状态,如蛇头、蛇身等。

2. 定义一个Food类,用来表示食物。该类包含一个坐标。

3. 定义一个Game类,用来作为游戏的入口。在该类中,需要维护一个Snake对象、一个Food对象和游戏界面。

4. 在游戏界面中,需要监听玩家的操作,如上下左右键,用来控制蛇的移动。

5. 在Snake类中,需要定义蛇的移动方法、碰撞检测方法等。

6. 在Game类中,需要根据玩家的操作来触发蛇的移动,当蛇碰到食物时,需要重新生成一个食物,并更新蛇的状态。

下面是Java实现贪吃蛇游戏的代码案例:

// Snake.java
import java.util.LinkedList;
public class Snake {
 private LinkedList
  body;
 
 private Point head;
 private int direction;
 public Snake(int x, int y) {
  body = new LinkedList<>();
  body.add(new Point(x, y));
  body.add(new Point(x, y + 1));
  body.add(new Point(x, y + 2));
  head = body.getLast();
  direction = 0;
 }
 public LinkedList
  getBody() return body;
 
 public Point getHead() return head;
 public int getDirection() return direction;
 
 public void move() {
  Point newHead = new Point(head.getX(), head.getY());
  switch (direction) {
   case 0: newHead.setX(newHead.getX() + 1); break;
   case 1: newHead.setY(newHead.getY() + 1); break;
   case 2: newHead.setX(newHead.getX() - 1); break;
   case 3: newHead.setY(newHead.getY() - 1); break;
  }
  body.removeFirst();
  body.addLast(newHead);
  head = newHead;
 }
 public boolean checkCollision() {
  int x = head.getX(), y = head.getY();
  if (x < 0 || y < 0 || x >= Game.WIDTH || y >= Game.HEIGHT) return true;
  for (int i = 0; i < body.size() - 1; i++) {
   if (x == body.get(i).getX() && y == body.get(i).getY()) return true;
  }
  return false;
 }
 public void setDirection(int direction) {
  int newDirection = this.direction + direction;
  if (newDirection < 0) newDirection += 4;
  else if (newDirection >= 4) newDirection -= 4;
  if (newDirection != this.direction) this.direction = newDirection;
 }
 public void grow() {
  Point newTail = new Point(body.getFirst().getX(), body.getFirst().getY());
  int dx = body.get(1).getX() - newTail.getX();
  int dy = body.get(1).getY() - newTail.getY();
  newTail.setX(newTail.getX() - dx);
  newTail.setY(newTail.getY() - dy);
  body.addFirst(newTail);
 }
}
// Food.java
public class Food {
 private Point pos;
 public Food(Point pos) this.pos = pos;
 public Point getPos() return pos;
 public void setPos(Point pos) this.pos = pos;
}
// Game.java
import javax.swing.JFrame;
import java.awt.Point;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
public class Game extends JFrame implements KeyListener {
 public static final int WIDTH = 20;
 public static final int HEIGHT = 20;
 public static final int CELL_SIZE = 20;
 public static final int FPS = 10;
 private Snake snake;
 private Food food;
 private boolean gameOver;
 private int score;
 public Game() {
  setTitle("贪吃蛇");
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setSize(WIDTH * CELL_SIZE, HEIGHT * CELL_SIZE);
  setLocationRelativeTo(null);
  setResizable(false);
  getContentPane().setBackground(Color.BLACK);
  addKeyListener(this);
  snake = new Snake(WIDTH / 2, HEIGHT / 2);
  spawnFood();
  gameOver = false;
  score = 0;
  new Thread(() -> {
   while (!gameOver) {
    try {
     Thread.sleep(1000 / FPS);
    } catch (InterruptedException e) { e.printStackTrace(); }
    tick();
    repaint();
   }
  }).start();
 }
 private void spawnFood() {
  Random rand = new Random();
  int x, y;
  do {
   x = rand.nextInt(WIDTH);
   y = rand.nextInt(HEIGHT);
  } while (snake.getBody().stream().anyMatch(p -> p.getX() == x && p.getY() == y));
  food = new Food(new Point(x, y));
 }
 private void tick() {
  snake.move();
  if (snake.checkCollision())
   gameOver = true;
   return;
  
  if (snake.getHead().getX() == food.getPos().getX() &&
    snake.getHead().getY() == food.getPos().getY()) {
   snake.grow();
   spawnFood();
   score++;
  }
 }
 @Override
 public void paint(Graphics g) {
  super.paint(g);
  g.setColor(Color.WHITE);
  snake.getBody().forEach(p -> g.fillOval(p.getX() * CELL_SIZE, p.getY() * CELL_SIZE, CELL_SIZE, CELL_SIZE));
  g.setColor(Color.RED);
  g.fillOval(food.getPos().getX() * CELL_SIZE, food.getPos().getY() * CELL_SIZE, CELL_SIZE, CELL_SIZE);
  g.setColor(Color.WHITE);
  g.drawString("分数:" + score, 10, 20);
  if (gameOver) {
   g.drawString("游戏结束!", getWidth() / 2 - 30, getHeight() / 2);
  }
 }
 @Override
 public void keyPressed(KeyEvent e) {
  switch (e.getKeyCode()) {
   case KeyEvent.VK_UP: snake.setDirection(-1); break;
   case KeyEvent.VK_DOWN: snake.setDirection(1); break;
   case KeyEvent.VK_LEFT: snake.setDirection(-2); break;
   case KeyEvent.VK_RIGHT: snake.setDirection(2); break;
  }
 }
 @Override
 public void keyTyped(KeyEvent e) {}
 @Override
 public void keyReleased(KeyEvent e) {}
 public static void main(String[] args) {
  Game game = new Game();
  game.setVisible(true);
 }
}

以上就是Java实现贪吃蛇游戏的全部代码。你可以复制代码到编译器中运行,也可以根据需要进行一些改动,例如改变窗口大小、添加音效等。在这个过程中,你可以学习到Java语言的基本语法,以及图形化界面的实现方法。

  
  

评论区

请求出错了