Java编写贪吃蛇的代码
时间: 2023-09-16 13:06:05 浏览: 417
Snake-java-source-code.rar_Snake!
### 回答1:
以下是一份简单的 Java 代码实现贪吃蛇游戏的示例:
```
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.Timer;
public class SnakeGame implements ActionListener, KeyListener {
public static SnakeGame snake;
public JFrame jframe;
public RenderPanel renderPanel;
public Timer timer = new Timer(20, this);
public ArrayList<Point> snakeParts = new ArrayList<Point>();
public static final int UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3, SCALE = 10;
public int ticks = 0, direction = DOWN, score, tailLength = 10, time;
public Point head, cherry;
public Random random;
public boolean over = false, paused;
public Dimension dim;
public SnakeGame() {
dim = Toolkit.getDefaultToolkit().getScreenSize();
jframe = new JFrame("Snake Game");
jframe.setVisible(true);
jframe.setSize(805, 700);
jframe.setResizable(false);
jframe.setLocation(dim.width / 2 - jframe.getWidth() / 2, dim.height / 2 - jframe.getHeight() / 2);
jframe.add(renderPanel = new RenderPanel());
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.addKeyListener(this);
startGame();
}
public void startGame() {
over = false;
paused = false;
time = 0;
score = 0;
tailLength = 14;
direction = DOWN;
head = new Point(0, -1);
random = new Random();
snakeParts.clear();
cherry = new Point(random.nextInt(79), random.nextInt(66));
timer.start();
}
@Override
public void actionPerformed(ActionEvent e) {
renderPanel.repaint();
ticks++;
if (ticks % 2 == 0 && head != null && !over && !paused) {
time++;
snakeParts.add(new Point(head.x, head.y));
if (snakeParts.size() > tailLength) {
snakeParts.remove(0);
}
if (direction == UP) {
if (head.y - 1 >= 0 && noTailAt(head.x, head.y - 1)) {
head = new
### 回答2:
贪吃蛇是一款经典的游戏,以下是使用Java编写贪吃蛇的代码示例:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GreedySnake extends JFrame {
private static final int WIDTH = 400; // 窗口宽度
private static final int HEIGHT = 400; // 窗口高度
private int snakeSize; // 蛇的大小
private int snakeX; // 蛇头的横坐标
private int snakeY; // 蛇头的纵坐标
private int foodX; // 食物的横坐标
private int foodY; // 食物的纵坐标
public GreedySnake() {
setTitle("Greedy Snake"); // 设置窗口标题
setSize(WIDTH, HEIGHT); // 设置窗口大小
setLocationRelativeTo(null); // 将窗口居中显示
setResizable(false); // 禁止窗口大小调整
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
snakeSize = 3;
snakeX = 20; snakeY = 20; // 初始蛇头位置
foodX = 100; foodY = 100; // 初始食物位置
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
// 根据按键设置蛇头的位置
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
snakeY -= 10;
break;
case KeyEvent.VK_DOWN:
snakeY += 10;
break;
case KeyEvent.VK_LEFT:
snakeX -= 10;
break;
case KeyEvent.VK_RIGHT:
snakeX += 10;
break;
}
repaint(); // 更新界面显示
}
});
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
g.fillRect(snakeX, snakeY, 10, 10); // 绘制蛇头
g.setColor(Color.RED);
g.fillRect(foodX, foodY, 10, 10); // 绘制食物
}
public static void main(String[] args) {
GreedySnake snake = new GreedySnake();
snake.setVisible(true); // 显示游戏窗口
}
}
```
这段代码通过`JFrame`类实现了贪吃蛇游戏的窗口界面,并使用`KeyListener`监听键盘按键事件来控制游戏。在`paint`方法中,使用`Graphics`类的相关方法绘制蛇头和食物的位置。在`main`方法中,创建了一个`GreedySnake`对象,并将其设为可见,从而启动游戏窗口。在窗口中,按上下左右箭头键可以控制蛇头的移动。
### 回答3:
贪吃蛇是一款经典的游戏,以下是一个简单的Java代码示例:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JFrame {
private Snake snake;
private Timer timer;
private final int DELAY = 100;
public SnakeGame() {
snake = new Snake();
initUI();
initGame();
}
private void initUI() {
setTitle("贪吃蛇");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
add(snake);
pack();
setLocationRelativeTo(null);
}
private void initGame() {
timer = new Timer(DELAY, new ActionListener() {
public void actionPerformed(ActionEvent e) {
snake.move();
repaint();
}
});
timer.start();
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
SnakeGame game = new SnakeGame();
game.setVisible(true);
});
}
}
class Snake extends JPanel {
private final int DOT_SIZE = 10;
private final int BOARD_SIZE = 300;
private final int TOTAL_DOTS = (BOARD_SIZE * BOARD_SIZE) / (DOT_SIZE * DOT_SIZE);
private final int[] x = new int[TOTAL_DOTS];
private final int[] y = new int[TOTAL_DOTS];
private int dots;
private int appleX;
private int appleY;
private boolean isMovingLeft;
private boolean isMovingRight;
private boolean isMovingUp;
private boolean isMovingDown;
public Snake() {
setPreferredSize(new Dimension(BOARD_SIZE, BOARD_SIZE));
setBackground(Color.black);
setFocusable(true);
initGame();
addKeyListener(new SnakeKeyListener());
}
private void initGame() {
dots = 3;
for (int i = 0; i < dots; i++) {
x[i] = 50 - i * DOT_SIZE;
y[i] = 50;
}
locateApple();
}
private void locateApple() {
int r = (int) (Math.random() * (BOARD_SIZE / DOT_SIZE));
appleX = r * DOT_SIZE;
r = (int) (Math.random() * (BOARD_SIZE / DOT_SIZE));
appleY = r * DOT_SIZE;
}
private void checkCollision() {
for (int i = dots - 1; i > 0; i--) {
if (i > 3 && x[0] == x[i] && y[0] == y[i]) {
timer.stop();
}
}
if (y[0] >= BOARD_SIZE || y[0] < 0 || x[0] >= BOARD_SIZE || x[0] < 0) {
timer.stop();
}
}
void move() {
for (int i = dots; i > 0; i--) {
x[i] = x[i - 1];
y[i] = y[i - 1];
}
if (isMovingLeft) {
x[0] -= DOT_SIZE;
}
if (isMovingRight) {
x[0] += DOT_SIZE;
}
if (isMovingUp) {
y[0] -= DOT_SIZE;
}
if (isMovingDown) {
y[0] += DOT_SIZE;
}
checkCollision();
checkApple();
}
private void checkApple() {
if (x[0] == appleX && y[0] == appleY) {
dots++;
locateApple();
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
private void draw(Graphics g) {
if (dots > 0) {
g.setColor(Color.green);
g.fillOval(appleX, appleY, DOT_SIZE, DOT_SIZE);
for (int i = 0; i < dots; i++) {
if (i == 0) {
g.setColor(Color.white);
g.fillRect(x[i], y[i], DOT_SIZE, DOT_SIZE);
} else {
g.setColor(Color.green);
g.fillRect(x[i], y[i], DOT_SIZE, DOT_SIZE);
}
}
} else {
gameOver(g);
}
}
private void gameOver(Graphics g) {
String msg = "Game Over";
Font font = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metrics = getFontMetrics(font);
g.setColor(Color.white);
g.setFont(font);
g.drawString(msg, (BOARD_SIZE - metrics.stringWidth(msg)) / 2, BOARD_SIZE / 2);
}
private class SnakeKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT && !isMovingRight) {
isMovingLeft = true;
isMovingUp = false;
isMovingDown = false;
} else if (key == KeyEvent.VK_RIGHT && !isMovingLeft) {
isMovingRight = true;
isMovingUp = false;
isMovingDown = false;
} else if (key == KeyEvent.VK_UP && !isMovingDown) {
isMovingUp = true;
isMovingLeft = false;
isMovingRight = false;
} else if (key == KeyEvent.VK_DOWN && !isMovingUp) {
isMovingDown = true;
isMovingLeft = false;
isMovingRight = false;
}
}
}
}
```
这段代码使用Java的Swing库创建了一个简单的窗口,并在窗口内绘制了一个贪吃蛇游戏。Snake类是一个面板,它处理游戏逻辑和绘制。SnakeGame类是游戏的主类,它创建了窗口并初始化游戏。
Snake类包括一些变量来跟踪贪吃蛇的位置、苹果的位置以及游戏状态。它使用定时器来控制贪吃蛇的移动,并根据用户的按键输入来改变运动方向。游戏结束时,它会在屏幕上显示“Game Over”消息。
请注意,这只是一个简单的示例代码,实际的贪吃蛇游戏可能包含更多功能和复杂性。
阅读全文