snakegame java代码
时间: 2023-07-16 19:02:20 浏览: 67
### 回答1:
贪吃蛇游戏(Snake Game)是一种经典的视频游戏。下面是一个简单的Java代码示例,实现了贪吃蛇游戏的基本功能:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SnakeGame extends JFrame {
private static final long serialVersionUID = 1L;
private Board board;
public SnakeGame() {
setTitle("Snake Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
board = new Board();
getContentPane().add(board);
pack();
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new SnakeGame();
}
}
class Board extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 300;
private static final int HEIGHT = 300;
private static final int DOT_SIZE = 10;
private static final int ALL_DOTS = 900;
private static final int RAND_POS = 29;
private static final int DELAY = 140;
private final int[] x = new int[ALL_DOTS];
private final int[] y = new int[ALL_DOTS];
private int dots;
private int apple_x;
private int apple_y;
private boolean leftDirection;
private boolean rightDirection = true;
private boolean upDirection;
private boolean downDirection;
private boolean inGame = true;
private Timer timer;
public Board() {
initBoard();
}
private void initBoard() {
setBackground(Color.black);
setFocusable(true);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
addKeyListener(new TAdapter());
startGame();
}
private void startGame() {
dots = 3;
for (int z = 0; z < dots; z++) {
x[z] = 50 - z * DOT_SIZE;
y[z] = 50;
}
locateApple();
timer = new Timer(DELAY, this);
timer.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g) {
if (inGame) {
g.setColor(Color.red);
g.fillOval(apple_x, apple_y, DOT_SIZE, DOT_SIZE);
for (int z = 0; z < dots; z++) {
if (z == 0) {
g.setColor(Color.green);
g.fillRect(x[z], y[z], DOT_SIZE, DOT_SIZE);
} else {
g.setColor(Color.white);
g.fillRect(x[z], y[z], DOT_SIZE, DOT_SIZE);
}
}
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] == apple_x) && (y[0] == apple_y)) {
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] -= DOT_SIZE;
}
if (rightDirection) {
x[0] += DOT_SIZE;
}
if (upDirection) {
y[0] -= DOT_SIZE;
}
if (downDirection) {
y[0] += DOT_SIZE;
}
}
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() * RAND_POS);
apple_x = ((r * DOT_SIZE));
r = (int) (Math.random() * RAND_POS);
apple_y = ((r * DOT_SIZE));
}
@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`进行绘制,通过监听键盘事件控制蛇的移动方向。游戏中,蛇每次吃到食物会变长,如果蛇头碰撞到自己或者碰到边界,则游戏结束。游戏画面使用基本的图形绘制,包括蛇身和食物,使用`Timer`控制游戏速度。
### 回答2:
以下是一个简单的贪吃蛇游戏的Java代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SnakeGame extends JPanel {
private final int BOX_SIZE = 10;
private final int NUM_BOXES = 400;
private final int GAME_SPEED = 100;
private int[] snakeX;
private int[] snakeY;
private int snakeSize;
private int directionX;
private int directionY;
private int foodX;
private int foodY;
private boolean isGameOver;
public SnakeGame() {
setPreferredSize(new Dimension(400, 400));
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(new SnakeKeyListener());
snakeX = new int[NUM_BOXES];
snakeY = new int[NUM_BOXES];
snakeSize = 3;
directionX = 1;
directionY = 0;
spawnFood();
Timer gameTimer = new Timer(GAME_SPEED, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!isGameOver) {
moveSnake();
checkCollision();
repaint();
} else {
((Timer) e.getSource()).stop();
}
}
});
gameTimer.start();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (!isGameOver) {
// 画蛇头
g.setColor(Color.GREEN);
g.fillRect(snakeX[0], snakeY[0], BOX_SIZE, BOX_SIZE);
// 画蛇身
g.setColor(Color.WHITE);
for (int i = 1; i < snakeSize; i++) {
g.fillRect(snakeX[i], snakeY[i], BOX_SIZE, BOX_SIZE);
}
// 画食物
g.setColor(Color.RED);
g.fillRect(foodX, foodY, BOX_SIZE, BOX_SIZE);
} else {
// 游戏结束
g.setColor(Color.WHITE);
g.setFont(new Font("Arial", Font.BOLD, 20));
g.drawString("Game Over", 150, 200);
}
}
private void moveSnake() {
for (int i = snakeSize - 1; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
snakeX[0] += directionX * BOX_SIZE;
snakeY[0] += directionY * BOX_SIZE;
}
private void checkCollision() {
// 检查碰撞边界
if (snakeX[0] < 0 || snakeX[0] >= getWidth() || snakeY[0] < 0 || snakeY[0] >= getHeight()) {
isGameOver = true;
return;
}
// 检查碰撞自身
for (int i = 1; i < snakeSize; i++) {
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
isGameOver = true;
return;
}
}
// 检查是否吃到食物
if (snakeX[0] == foodX && snakeY[0] == foodY) {
snakeSize++;
spawnFood();
}
}
private void spawnFood() {
foodX = (int) (Math.random() * (getWidth() / BOX_SIZE)) * BOX_SIZE;
foodY = (int) (Math.random() * (getHeight() / BOX_SIZE)) * BOX_SIZE;
}
private class SnakeKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
switch (keyCode) {
case KeyEvent.VK_UP:
if (directionY != 1) {
directionX = 0;
directionY = -1;
}
break;
case KeyEvent.VK_DOWN:
if (directionY != -1) {
directionX = 0;
directionY = 1;
}
break;
case KeyEvent.VK_LEFT:
if (directionX != 1) {
directionX = -1;
directionY = 0;
}
break;
case KeyEvent.VK_RIGHT:
if (directionX != -1) {
directionX = 1;
directionY = 0;
}
break;
default:
break;
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Snake Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SnakeGame());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```
这是一个使用Java Swing库编写的贪吃蛇游戏。游戏根据用户的按键输入移动蛇身并检查碰撞,包括边界碰撞、自身碰撞和食物碰撞。蛇身和食物会在面板上绘制,并且在碰撞检测时更新。游戏会在用户碰撞或游戏结束时停止,并显示"Game Over"的文字提示。
### 回答3:
Java代码如下:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
public class SnakeGame extends JFrame {
private static final int WIDTH = 400;
private static final int HEIGHT = 400;
private static final int UNIT_SIZE = 20;
private static final int GAME_UNITS = (WIDTH * HEIGHT) / UNIT_SIZE;
private static final int DELAY = 75;
private final int x[] = new int[GAME_UNITS];
private final int y[] = new int[GAME_UNITS];
private int bodyParts = 6;
private int applesEaten;
private int appleX;
private int appleY;
private char direction = 'R';
private boolean running = false;
private Timer timer;
private Random random;
public SnakeGame() {
random = new Random();
this.setTitle("Snake Game");
this.setSize(WIDTH, HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);
this.addKeyListener(new MyKeyAdapter());
this.setFocusable(true);
startGame();
}
private void startGame() {
newApple();
running = true;
timer = new Timer(DELAY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (running) {
move();
checkApple();
checkCollision();
}
repaint();
}
});
timer.start();
}
@Override
public void paint(Graphics g) {
// 绘制背景
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
// 绘制蛇
for (int i = 0; i < bodyParts; i++) {
if (i == 0) {
g.setColor(Color.green);
} else {
g.setColor(Color.yellow);
}
g.fillRect(x[i], y[i], UNIT_SIZE, UNIT_SIZE);
}
// 绘制苹果
g.setColor(Color.red);
g.fillOval(appleX, appleY, UNIT_SIZE, UNIT_SIZE);
// 绘制得分
g.setColor(Color.white);
g.setFont(new Font("Ink Free", Font.BOLD, 20));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Score: " + applesEaten, (WIDTH - metrics.stringWidth("Score: " + applesEaten)) / 2, g.getFont().getSize());
}
private 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;
}
}
private void checkApple() {
if ((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++;
applesEaten++;
newApple();
}
}
private void checkCollision() {
// 碰到自己的身体游戏结束
for (int i = bodyParts; i > 0; i--) {
if ((x[0] == x[i]) && (y[0] == y[i])) {
running = false;
}
}
// 碰到边界游戏结束
if (x[0] < 0 || x[0] >= WIDTH || y[0] < 0 || y[0] >= HEIGHT) {
running = false;
}
if (!running) {
timer.stop();
}
}
private void newApple() {
appleX = random.nextInt((int) (WIDTH / UNIT_SIZE)) * UNIT_SIZE;
appleY = random.nextInt((int) (HEIGHT / UNIT_SIZE)) * UNIT_SIZE;
}
private 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;
}
}
}
public static void main(String[] args) {
new SnakeGame();
}
}
```
这是一个简单的贪吃蛇游戏的Java代码。游戏窗口大小为400x400像素,每个方块大小为20像素。蛇由一系列方块组成,初始长度为6个方块。蛇在窗口中移动,并根据玩家的操作改变方向。目标是吃掉苹果,并且每吃一个苹果,蛇的长度增加1。游戏结束的条件为蛇碰到自己的身体或者碰到窗口边界。游戏使用了计时器来控制蛇的运动和窗口的绘制。