java贪吃蛇代码。只需要一个JAVA类,实现简单的贪吃蛇游戏,手撸代码已经测试过,可正常运行,废话不说,直接上代码:
package store.tbfl;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SnakeGame extends JPanel {
private static final int NUM_CELLS = 20;
private static final int CELL_SIZE = 20;
private int[] x;
private int[] y;
private int length;
private int foodX;
private int foodY;
private Direction direction;
private Timer timer;
public SnakeGame() {
setPreferredSize(new Dimension(NUM_CELLS * CELL_SIZE, NUM_CELLS * CELL_SIZE));
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
handleKeyPress(e);
}
});
x = new int[NUM_CELLS * NUM_CELLS];
y = new int[NUM_CELLS * NUM_CELLS];
length = 1;
direction = Direction.RIGHT;
generateFood();
timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
move();
repaint();
}
});
timer.start();
}
private void handleKeyPress(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
if (direction != Direction.DOWN) {
direction = Direction.UP;
}
break;
case KeyEvent.VK_DOWN:
if (direction != Direction.UP) {
direction = Direction.DOWN;
}
break;
case KeyEvent.VK_LEFT:
if (direction != Direction.RIGHT) {
direction = Direction.LEFT;
}
break;
case KeyEvent.VK_RIGHT:
if (direction != Direction.LEFT) {
direction = Direction.RIGHT;
}
break;
}
}
private void generateFood() {
foodX = (int) (Math.random() * NUM_CELLS);
foodY = (int) (Math.random() * NUM_CELLS);
}
private void move() {
for (int i = length – 1; i > 0; i–) {
x[i] = x[i – 1];
y[i] = y[i – 1];
}
switch (direction) {
case UP:
y[0]–;
break;
case DOWN:
y[0]++;
break;
case LEFT:
x[0]–;
break;
case RIGHT:
x[0]++;
break;
}
checkCollision();
}
private void checkCollision() {
if (x[0] = NUM_CELLS || y[0] = NUM_CELLS) {
gameOver();
}
for (int i = 1; i < length; i++) {
if (x[i] == x[0] && y[i] == y[0]) {
gameOver();
}
}
if (x[0] == foodX && y[0] == foodY) {
length++;
generateFood();
}
}
private void gameOver() {
timer.stop();
JOptionPane.showMessageDialog(this, “Game Over”, “Game Over”,0 );
resetGame();
}
private void resetGame() {
x = new int[NUM_CELLS * NUM_CELLS];
y = new int[NUM_CELLS * NUM_CELLS];
length = 1;
direction = Direction.RIGHT;
generateFood();
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 绘制蛇身
g.setColor(Color.GREEN);
for (int i = 0; i < length; i++) {
g.fillRect(x[i] * CELL_SIZE, y[i] * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
// 绘制食物
g.setColor(Color.RED);
g.fillRect(foodX * CELL_SIZE, foodY * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
public static void main(String[] args) {
JFrame frame = new JFrame(“贪吃蛇-头条号-伊伊动漫”);
SnakeGame snakeGame = new SnakeGame();
frame.add(snakeGame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
snakeGame.requestFocus();
}
private enum Direction {
UP, DOWN, LEFT, RIGHT
}
}
直接运行main方法即可,
效果如图: