用Java写一个贪吃蛇小游戏
时间: 2023-12-07 13:12:47 浏览: 14
贪吃蛇是一款经典的俄罗斯方块游戏,可以用Java语言编写。下面是一个简单的实现:
首先,我们需要创建一个窗口,可以使用Java的 `JFrame` 和 `JPanel` 来实现。接着,我们需要实现贪吃蛇的移动,可以使用Java的 `Thread` 来实现。然后,我们需要实现吃食物的功能,当贪吃蛇的头碰到食物的位置时,可以增加贪吃蛇的长度。
最后,我们需要处理贪吃蛇碰到边界或者碰到自己的身体时的游戏结束的情况。
这只是一个简单的实现,如果您希望添加更多的功能,可以继续完善代码。希望对您有所帮助!
相关问题
用 Java 写一个贪吃蛇小游戏
好的,我可以为您提供一个用Java编写的简单贪吃蛇小游戏的示例代码。这个游戏包含基本的贪吃蛇移动、吃食物和碰撞检测功能。以下是完整的代码:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class SnakeGame extends JFrame {
public SnakeGame() {
this.add(new GamePanel());
this.setTitle("贪吃蛇游戏");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
new SnakeGame();
}
}
class GamePanel extends JPanel implements ActionListener {
static final int SCREEN_WIDTH = 600;
static final int SCREEN_HEIGHT = 600;
static final int UNIT_SIZE = 25;
static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/UNIT_SIZE;
static final int DELAY = 75;
final int[] x = new int[GAME_UNITS];
final int[] y = new int[GAME_UNITS];
int bodyParts = 6;
int applesEaten;
int appleX;
int appleY;
char direction = 'R';
boolean running = false;
Timer timer;
Random random;
public GamePanel() {
random = new Random();
this.setPreferredSize(new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT));
this.setBackground(Color.black);
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
}
public void startGame() {
newApple();
running = true;
timer = new Timer(DELAY, this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
if (running) {
// 画网格线
/*
for (int i = 0; i < SCREEN_HEIGHT/UNIT_SIZE; i++) {
g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);
g.drawLine(0, i*UNIT_SIZE, SCREEN_WIDTH, i*UNIT_SIZE);
}
*/
// 画食物
g.setColor(Color.red);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
// 画蛇
for (int i = 0; i < bodyParts; i++) {
if (i == 0) {
g.setColor(Color.green);
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
} else {
g.setColor(new Color(45, 180, 0));
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
}
// 画分数
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 40));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Score: " + applesEaten, (SCREEN_WIDTH - metrics.stringWidth("Score: " + applesEaten))/2, g.getFont().getSize());
} else {
gameOver(g);
}
}
public void newApple() {
appleX = random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE;
appleY = random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE))*UNIT_SIZE;
}
public void move() {
for (int i = bodyParts; i > 0; i--) {
x[i] = x[i-1];
y[i] = y[i-1];
}
switch(direction) {
case 'U':
y[0] = y[0] - UNIT_SIZE;
break;
case 'D':
y[0] = y[0] + UNIT_SIZE;
break;
case 'L':
x[0] = x[0] - UNIT_SIZE;
break;
case 'R':
x[0] = x[0] + UNIT_SIZE;
break;
}
}
public void checkApple() {
if ((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++;
applesEaten++;
newApple();
}
}
public void checkCollisions() {
// 检查是否撞到自己
for (int i = bodyParts; i > 0; i--) {
if ((x[0] == x[i]) && (y[0] == y[i])) {
running = false;
break;
}
}
// 检查是否撞到边界
if (x[0] < 0 || x[0] >= SCREEN_WIDTH || y[0] < 0 || y[0] >= SCREEN_HEIGHT) {
running = false;
}
if (!running) {
timer.stop();
}
}
public void gameOver(Graphics g) {
// 画分数
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 40));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.drawString("Score: " + applesEaten, (SCREEN_WIDTH - metrics1.stringWidth("Score: " + applesEaten))/2, g.getFont().getSize());
// 画"游戏结束"
g.setColor(Color.red);
g.setFont(new Font("Ink Free", Font.BOLD, 75));
FontMetrics metrics2 = getFontMetrics(g.getFont());
g.drawString("Game Over", (SCREEN_WIDTH - metrics2.stringWidth("Game Over"))/2, SCREEN_HEIGHT/2);
}
@Override
public void actionPerformed(ActionEvent e) {
if (running) {
move();
checkApple();
checkCollisions();
}
repaint();
}
public class MyKeyAdapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if(direction != 'R') {
direction = 'L';
}
break;
case KeyEvent.VK_RIGHT:
if(direction != 'L') {
direction = 'R';
}
break;
case KeyEvent.VK_UP:
if(direction != 'D') {
direction = 'U';
}
break;
case KeyEvent.VK_DOWN:
if(direction != 'U') {
direction = 'D';
}
break;
}
}
}
}
```
这个代码实现了以下功能:
1. 游戏窗口的创建和设置
2. 贪吃蛇的绘制和移动
3. 食物的生成和绘制
4. 碰撞检测(与自身和边界)
5. 分数统计和显示
6. 游戏结束画面
要运行这个游戏,你需要创建一个Java项目,将这段代码保存为`SnakeGame.java`,然后编译并运行它。游戏窗口会弹出,你可以使用箭头键来控制贪吃蛇的移动。
用java写一个贪吃蛇小游戏
当然可以!这里是一个简单的贪吃蛇小游戏的Java代码示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SnakeGame extends JFrame {
private Snake snake;
private Timer timer;
private boolean gameOver;
public SnakeGame() {
setTitle("贪吃蛇游戏");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setSize(400, 400);
setLocationRelativeTo(null);
snake = new Snake();
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
snake.keyPressed(e.getKeyCode());
}
});
timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!gameOver) {
snake.move();
if (snake.collidedWithSelf() || snake.collidedWithWall()) {
gameOver = true;
}
repaint();
}
}
});
timer.start();
setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (gameOver) {
g.setColor(Color.RED);
g.setFont(new Font("Arial", Font.BOLD, 20));
g.drawString("游戏结束", 150, 180);
} else {
snake.draw(g);
}
}
public static void main(String[] args) {
new SnakeGame();
}
}
class Snake {
private static final int UNIT_SIZE = 20;
private static final int GAME_UNITS = (400 * 400) / (UNIT_SIZE * UNIT_SIZE);
private static final int DELAY = 100;
private int[] x;
private int[] y;
private int bodyParts;
private int appleX;
private int appleY;
private char direction;
private boolean moving;
public Snake() {
x = new int[GAME_UNITS];
y = new int[GAME_UNITS];
bodyParts = 6;
direction = 'R';
generateApple();
moving = true;
}
public void generateApple() {
appleX = (int) (Math.random() * (400 / UNIT_SIZE)) * UNIT_SIZE;
appleY = (int) (Math.random() * (400 / UNIT_SIZE)) * UNIT_SIZE;
}
public void draw(Graphics g) {
for (int i = 0; i < bodyParts; i++) {
if (i == 0) {
g.setColor(Color.GREEN);
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
} else {
g.setColor(new Color(45, 180, 0));
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
}
g.setColor(Color.RED);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
}
public void move() {
for (int i = bodyParts; i > 0; i--) {
x[i] = x[i - 1];
y[i] = y[i - 1];
}
switch (direction) {
case 'U':
y[0] -= UNIT_SIZE;
break;
case 'D':
y[0] += UNIT_SIZE;
break;
case 'L':
x[0] -= UNIT_SIZE;
break;
case 'R':
x[0] += UNIT_SIZE;
break;
}
if (x[0] == appleX && y[0] == appleY) {
bodyParts++;
generateApple();
}
moving = true;
}
public boolean collidedWithSelf() {
for (int i = bodyParts; i > 0; i--) {
if (x[0] == x[i] && y[0] == y[i]) {
return true;
}
}
return false;
}
public boolean collidedWithWall() {
return x[0] < 0 || x[0] >= 400 || y[0] < 0 || y[0] >= 400;
}
public void keyPressed(int keyCode) {
switch (keyCode) {
case KeyEvent.VK_UP:
if (!moving) {
direction = 'U';
moving = true;
}
break;
case KeyEvent.VK_DOWN:
if (!moving) {
direction = 'D';
moving = true;
}
break;
case KeyEvent.VK_LEFT:
if (!moving) {
direction = 'L';
moving = true;
}
break;
case KeyEvent.VK_RIGHT:
if (!moving) {
direction = 'R';
moving = true;
}
break;
}
}
}
```
这个代码示例使用Java的Swing库来创建窗口和绘制游戏界面。贪吃蛇的移动由定时器控制,当贪吃蛇与自身或墙壁发生碰撞时游戏结束。你可以尝试运行这段代码,体验一下这个简单的贪吃蛇小游戏!
阅读全文