用Java语言编写一个贪吃蛇游戏
时间: 2023-03-12 12:09:30 浏览: 88
我不是很擅长编程,但我可以给你一些提示,希望能帮到你:1. 先创建一个游戏界面,然后绘制游戏的蛇、食物和地图;2. 实现游戏的控制逻辑,比如控制蛇的移动、吃食物的逻辑、游戏的结束逻辑等;3. 最后,添加一些额外的模式,以增加游戏的可玩性。
相关问题
用java语言编写一个贪吃蛇游戏代码
以下是Java语言编写的简单贪吃蛇游戏代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JFrame implements ActionListener {
private final int WIDTH = 300;
private final int HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
private int x[] = new int[ALL_DOTS];
private int y[] = new int[ALL_DOTS];
private int dots;
private int apple_x;
private int apple_y;
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 SnakeGame() {
setTitle("Snake Game");
setBackground(Color.gray);
setResizable(false);
setSize(WIDTH, HEIGHT);
ImageIcon iid = new ImageIcon(getClass().getResource("dot.png"));
ball = iid.getImage();
ImageIcon iia = new ImageIcon(getClass().getResource("apple.png"));
apple = iia.getImage();
ImageIcon iih = new ImageIcon(getClass().getResource("head.png"));
head = iih.getImage();
addKeyListener(new TAdapter());
timer = new Timer(DELAY, this);
timer.start();
initGame();
}
public void initGame() {
dots = 3;
for (int i = 0; i < dots; i++) {
x[i] = 50 - i * 10;
y[i] = 50;
}
locateApple();
inGame = true;
}
public void paint(Graphics g) {
super.paint(g);
if (inGame) {
g.drawImage(apple, apple_x, apple_y, this);
for (int i = 0; i < dots; i++) {
if (i == 0) {
g.drawImage(head, x[i], y[i], this);
} else {
g.drawImage(ball, x[i], y[i], this);
}
}
Toolkit.getDefaultToolkit().sync();
} else {
gameOver(g);
}
}
public 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);
}
public void checkApple() {
if ((x[0] == apple_x) && (y[0] == apple_y)) {
dots++;
locateApple();
}
}
public void move() {
for (int i = dots; i > 0; i--) {
x[i] = x[i - 1];
y[i] = y[i - 1];
}
if (leftDirection) {
x[0] -= DOT_SIZE;
}
if (rightDirection) {
x[0] += DOT_SIZE;
}
if (upDirection) {
y[0] -= DOT_SIZE;
}
if (downDirection) {
y[0] += DOT_SIZE;
}
}
public void checkCollision() {
for (int i = dots; i > 0; i--) {
if ((i > 4) && (x[0] == x[i]) && (y[0] == y[i])) {
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();
}
}
public void locateApple() {
int r = (int) (Math.random() * RAND_POS);
apple_x = r * DOT_SIZE;
r = (int) (Math.random() * RAND_POS);
apple_y = r * DOT_SIZE;
}
public void actionPerformed(ActionEvent e) {
if (inGame) {
checkApple();
checkCollision();
move();
}
repaint();
}
private class TAdapter extends KeyAdapter {
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 static void main(String[] args) {
new SnakeGame().setVisible(true);
}
}
```
在代码中,我们使用了Java Swing库,创建了一个JFrame窗口,通过继承JFrame类实现,利用paint()方法绘制游戏画面,并且使用了Timer类来控制游戏帧率,使用ImageIcon读取了游戏素材。同时,我们还实现了一些游戏逻辑,比如蛇的移动、碰撞检测、吃苹果等。最后,我们在main()方法中新建了一个SnakeGame对象并可见。
用Java语言编写一个简单的贪吃蛇游戏
好的,以下是一个简单的贪吃蛇游戏的Java代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SnakeGame extends JFrame implements KeyListener, ActionListener {
private int width = 15;
private int height = 15;
private int size = 20;
private int[][] map = new int[width][height];
private int snakeLength = 3;
private int[] snakeX = new int[width * height];
private int[] snakeY = new int[width * height];
private int foodX;
private int foodY;
private int direction = 39;
private Timer timer;
public SnakeGame() {
setTitle("贪吃蛇游戏");
setSize(width * size + 6, height * size + 28);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
init();
timer = new Timer(200, this);
timer.start();
setVisible(true);
}
private void init() {
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
map[i][j] = 0;
}
}
for (int i = 0; i < snakeLength; i++) {
snakeX[i] = width / 2 - i;
snakeY[i] = height / 2;
map[snakeX[i]][snakeY[i]] = 1;
}
generateFood();
}
private void generateFood() {
boolean valid = false;
while (!valid) {
foodX = (int) (Math.random() * width);
foodY = (int) (Math.random() * height);
if (map[foodX][foodY] == 0) {
valid = true;
}
}
}
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, width * size, height * size);
g.setColor(Color.BLACK);
for (int i = 0; i <= width; i++) {
g.drawLine(i * size, 0, i * size, height * size);
}
for (int i = 0; i <= height; i++) {
g.drawLine(0, i * size, width * size, i * size);
}
g.setColor(Color.GREEN);
g.fillRect(foodX * size, foodY * size, size, size);
g.setColor(Color.RED);
for (int i = 0; i < snakeLength; i++) {
g.fillRect(snakeX[i] * size, snakeY[i] * size, size, size);
}
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_LEFT || key == KeyEvent.VK_A) && direction != 39) {
direction = 37;
}
if ((key == KeyEvent.VK_UP || key == KeyEvent.VK_W) && direction != 40) {
direction = 38;
}
if ((key == KeyEvent.VK_RIGHT || key == KeyEvent.VK_D) && direction != 37) {
direction = 39;
}
if ((key == KeyEvent.VK_DOWN || key == KeyEvent.VK_S) && direction != 38) {
direction = 40;
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public void actionPerformed(ActionEvent e) {
int x = snakeX[0];
int y = snakeY[0];
if (direction == 37) {
x--;
}
if (direction == 38) {
y--;
}
if (direction == 39) {
x++;
}
if (direction == 40) {
y++;
}
if (x < 0 || x >= width || y < 0 || y >= height || map[x][y] == 1) {
timer.stop();
JOptionPane.showMessageDialog(null, "游戏结束");
System.exit(0);
}
if (x == foodX && y == foodY) {
snakeLength++;
map[foodX][foodY] = 1;
generateFood();
} else {
map[snakeX[snakeLength - 1]][snakeY[snakeLength - 1]] = 0;
}
for (int i = snakeLength - 1; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
snakeX[0] = x;
snakeY[0] = y;
map[x][y] = 1;
repaint();
}
public static void main(String[] args) {
new SnakeGame();
}
}
```
代码中使用了Java的Swing库来实现界面,在主函数中创建了一个`SnakeGame`对象,该对象实现了`KeyListener`和`ActionListener`接口,分别用于处理键盘事件和定时器事件。
游戏中使用一个二维数组`map`来表示地图,其中0表示空格,1表示蛇身,使用`snakeX`和`snakeY`两个数组来记录蛇身的位置,使用`snakeLength`来记录蛇身的长度。在定时器事件中,根据当前方向移动蛇身,检测是否与食物碰撞,更新蛇身位置和长度,重新生成食物,最后重绘整个界面。
具体实现细节请参考代码注释。