用JAVA写一个贪吃蛇的代码
时间: 2023-09-15 21:05:43 浏览: 142
### 回答1:
我很乐意为你编写一段贪吃蛇的JAVA代码:
public class SnakeGame {
public static void main(String[] args) {
// 创建一个SnakeGame对象
SnakeGame game = new SnakeGame();
// 设置游戏界面的大小,如果没有参数,默认界面大小为20*20
game.setSize(30, 30);
// 开始游戏
game.startGame();
}
}
### 回答2:
贪吃蛇是一个经典的游戏,以下是一个用Java实现的简单贪吃蛇游戏的代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Random;
public class SnakeGame extends JFrame {
private final int SIZE = 20; // 游戏格子的大小
private final int WIDTH = 30; // 游戏窗口的宽度
private final int HEIGHT = 20; // 游戏窗口的高度
private int score = 0; // 当前得分
private ArrayList<Point> snake; // 蛇身的坐标构成的ArrayList
private Point food; // 食物的坐标
private Direction direction = Direction.RIGHT; // 蛇的初始移动方向
private Timer timer; // 定时器,用于不断刷新画面
public SnakeGame() {
setTitle("贪吃蛇");
setSize(WIDTH * SIZE, HEIGHT * SIZE);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
snake = new ArrayList<>();
snake.add(new Point(10, 10)); // 初始化蛇
generateFood(); // 初始化食物
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
if (direction != Direction.DOWN) {
direction = Direction.UP;
}
break;
case KeyEvent.VK_DOWN:
if (direction != Direction.UP) {
direction = Direction.DOWN;
}
break;
case KeyEvent.VK_LEFT:
if (direction != Direction.RIGHT) {
direction = Direction.LEFT;
}
break;
case KeyEvent.VK_RIGHT:
if (direction != Direction.LEFT) {
direction = Direction.RIGHT;
}
break;
}
}
});
timer = new Timer(200, e -> {
move();
repaint();
});
timer.start();
setVisible(true);
}
private void move() {
Point head = snake.get(0);
int newX = head.x;
int newY = head.y;
switch (direction) {
case UP:
newY--;
break;
case DOWN:
newY++;
break;
case LEFT:
newX--;
break;
case RIGHT:
newX++;
break;
}
Point newHead = new Point(newX, newY);
snake.add(0, newHead); // 将新头部添加到蛇身
if (newHead.equals(food)) {
score += 10;
generateFood();
} else {
snake.remove(snake.size() - 1); // 若没吃到食物,去掉蛇尾
}
if (collision(newHead) || newX < 0 || newX >= WIDTH || newY < 0 || newY >= HEIGHT) {
timer.stop();
JOptionPane.showMessageDialog(null, "游戏结束,得分:" + score);
System.exit(0);
}
}
private boolean collision(Point head) {
for (int i = 1; i < snake.size(); i++) {
if (snake.get(i).equals(head)) {
return true; // 头部和蛇身某一部分相撞
}
}
return false;
}
private void generateFood() {
Random random = new Random();
int x, y;
do {
x = random.nextInt(WIDTH);
y = random.nextInt(HEIGHT);
food = new Point(x, y);
} while (snake.contains(food)); // 若生成的食物坐标与蛇身坐标重合,则重新生成
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.GRAY);
g.fillRect(0, 0, WIDTH * SIZE, HEIGHT * SIZE);
g.setColor(Color.GREEN);
for (Point p : snake) {
g.fillRect(p.x * SIZE, p.y * SIZE, SIZE, SIZE); // 在对应坐标上绘制蛇身
}
g.setColor(Color.RED);
g.fillRect(food.x * SIZE, food.y * SIZE, SIZE, SIZE); // 绘制食物
g.setColor(Color.WHITE);
g.setFont(new Font("Arial", Font.BOLD, 16));
g.drawString("Score: " + score, 10, 20); // 绘制得分
}
public static void main(String[] args) {
new SnakeGame();
}
private enum Direction {
UP, DOWN, LEFT, RIGHT
}
}
```
这个代码使用Java编写的贪吃蛇游戏实现了以下功能:
1. 游戏窗口的初始化和设置。
2. 蛇身的移动和控制,通过键盘的上下左右键控制蛇的方向。
3. 食物的随机生成,并在吃到食物时增加得分。
4. 碰撞检测,判断蛇头是否和蛇身或边界相撞,游戏结束。
5. 绘制游戏界面,包括蛇身、食物和得分的显示。
这个代码只是一个简单的贪吃蛇游戏实现,可能还有更多的功能可以进一步完善。
### 回答3:
贪吃蛇是一款经典的游戏,下面是一个使用Java编写的贪吃蛇代码示例:
```java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Snake extends JPanel implements ActionListener {
private final int width = 300;
private final int height = 300;
private final int dotSize = 10;
private final int allDots = 900;
private final int x[] = new int[allDots];
private final int y[] = new int[allDots];
private int dots;
private int appleX;
private int appleY;
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() {
initSnake();
}
private void initSnake() {
addKeyListener(new TAdapter());
setBackground(Color.black);
setFocusable(true);
setPreferredSize(new Dimension(width, height));
loadImage();
initGame();
}
private void loadImage() {
ImageIcon ballIcon = new ImageIcon("dot.png");
ball = ballIcon.getImage();
ImageIcon appleIcon = new ImageIcon("apple.png");
apple = appleIcon.getImage();
ImageIcon headIcon = new ImageIcon("head.png");
head = headIcon.getImage();
}
private void initGame() {
dots = 3;
for (int z = 0; z < dots; z++) {
x[z] = 50 - z * dotSize;
y[z] = 50;
}
locateApple();
timer = new Timer(140, this);
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g) {
if (inGame) {
g.drawImage(apple, appleX, appleY, this);
for (int z = 0; z < dots; z++) {
if (z == 0) {
g.drawImage(head, x[z], y[z], this);
} else {
g.drawImage(ball, x[z], y[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 checkApple() {
if ((x[0] == appleX) && (y[0] == appleY)) {
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] -= dotSize;
}
if (rightDirection) {
x[0] += dotSize;
}
if (upDirection) {
y[0] -= dotSize;
}
if (downDirection) {
y[0] += dotSize;
}
}
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] >= height) {
inGame = false;
}
if (y[0] < 0) {
inGame = false;
}
if (x[0] >= width) {
inGame = false;
}
if (x[0] < 0) {
inGame = false;
}
if (!inGame) {
timer.stop();
}
}
private void locateApple() {
int r = (int) (Math.random() * 29);
appleX = r * dotSize;
r = (int) (Math.random() * 29);
appleY = r * dotSize;
}
@Override
public void actionPerformed(ActionEvent e) {
if (inGame) {
checkApple();
checkCollision();
move();
}
repaint();
}
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;
}
}
}
}
```
这个代码使用`JPanel`继承类来创建游戏界面,在`initSnake`方法中初始化游戏各种属性。在`paintComponent`方法中绘制游戏,使用`doDrawing`方法实现贪吃蛇、苹果和游戏结束时的绘制。通过`checkApple`方法检测贪吃蛇是否吃到了苹果,并使用`move`方法来控制贪吃蛇的移动。使用`checkCollision`方法来检测贪吃蛇是否与自身或边界碰撞,若碰撞则游戏结束。`locateApple`方法用于随机放置苹果。`TAdapter`类实现了键盘监听,根据按键改变贪吃蛇的移动方向。
阅读全文