写一个贪吃蛇游戏的JAVA代码
时间: 2023-11-28 15:47:27 浏览: 166
贪吃蛇游戏JAVA代码
4星 · 用户满意度95%
这是一个简单的贪吃蛇游戏JAVA代码,仅供参考:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JFrame implements KeyListener
{
private static final long serialVersionUID = 1L;
private int x = 50, y = 50;
private int width = 20, height = 20;
private int dx = width, dy = 0;
private int foodX = 100, foodY = 100;
private int score = 0;
private boolean isGameOver = false;
private Timer timer;
private int delay = 100;
private int[] snakeX = new int[1000];
private int[] snakeY = new int[1000];
private int snakeLength = 3;
public SnakeGame()
{
setTitle("贪吃蛇");
setSize(500, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
timer = new Timer(delay, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
move();
repaint();
}
});
timer.start();
setVisible(true);
}
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.RED);
g.fillRect(foodX, foodY, width, height);
for (int i = 0; i < snakeLength; i++)
{
g.setColor(Color.GREEN);
g.fillRect(snakeX[i], snakeY[i], width, height);
}
g.setColor(Color.BLACK);
g.drawString("得分: " + score, 10, 20);
if (isGameOver)
{
g.setColor(Color.RED);
g.drawString("游戏结束!", getWidth() / 2 - 50, getHeight() / 2);
}
}
private void move()
{
for (int i = snakeLength - 1; i > 0; i--)
{
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
snakeX[0] += dx;
snakeY[0] += dy;
if (snakeX[0] < 0 || snakeX[0] + width > getWidth() || snakeY[0] < 0 || snakeY[0] + height > getHeight())
{
isGameOver = true;
timer.stop();
}
if (snakeX[0] == foodX && snakeY[0] == foodY)
{
score++;
snakeLength++;
foodX = (int)(Math.random() * (getWidth() - width));
foodY = (int)(Math.random() * (getHeight() - height));
}
for (int i = 1; i < snakeLength; i++)
{
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i])
{
isGameOver = true;
timer.stop();
break;
}
}
}
@Override
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_UP:
if (dy != height)
{
dx = 0;
dy = -height;
}
break;
case KeyEvent.VK_DOWN:
if (dy != -height)
{
dx = 0;
dy = height;
}
break;
case KeyEvent.VK_LEFT:
if (dx != width)
{
dx = -width;
dy = 0;
}
break;
case KeyEvent.VK_RIGHT:
if (dx != -width)
{
dx = width;
dy = 0;
}
break;
}
}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {}
public static void main(String[] args)
{
new SnakeGame();
}
}
```
阅读全文