回答:应该不是,你这个用Java的Swing写的贪吃蛇,但是小蛇没有绘制出来,有可能是绘制线程没有开启或者没有绑定到界面上之类的问题,你可以把代码贴一下
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class AutoSnakeGame extends JFrame {
private Snake snake;
private Timer timer;
private boolean isGameOver;
public AutoSnakeGame() {
setTitle("Auto Snake Game");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
snake = new Snake();
timer = new Timer(200, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!isGameOver) {
snake.move();
checkCollision();
repaint();
}
}
});
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_SPACE) {
if (isGameOver) {
snake.reset();
isGameOver = false;
}
if (!timer.isRunning()) {
timer.start();
}
}
snake.processKey(e.getKeyCode());
}
});
setFocusable(true);
requestFocus();
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (isGameOver) {
g.setColor(Color.RED);
g.setFont(new Font("Arial", Font.BOLD, 24));
g.drawString("Game Over", 150, getHeight() / 2);
g.drawString("Press SPACE to restart", 90, getHeight() / 2 + 30);
} else {
snake.draw(g);
}
}
private void checkCollision() {
if (snake.checkSelfCollision() || snake.checkWallCollision(getWidth(), getHeight())) {
isGameOver = true;
timer.stop();
}
}
public static void main(String[] args) {
AutoSnakeGame game = new AutoSnakeGame();
game.setVisible(true);
}
}
class Snake {
private static final int SIZE = 20;
private static final int INIT_LENGTH = 3;
private int x;
private int y;
private int dx;
private int dy;
private int[] tailX;
private int[] tailY;
private int tailLength;
private boolean isMoving;
private boolean isGrown;
public Snake() {
x = 0;
y = 0;
dx = SIZE;
dy = 0;
tailX = new int[INIT_LENGTH];
tailY = new int[INIT_LENGTH];
tailLength = 0;
isMoving = true;
isGrown = false;
}
public boolean checkWallCollision(int width, int height) {
return false;
}
public boolean checkSelfCollision() {
return false;
}
public void processKey(int keyCode) {
}
public void reset() {
}
public void draw(Graphics g) {
g.setColor(Color.GREEN);
g.fillRect(x, y, SIZE, SIZE);
for (int i = 0; i < tailLength; i++) {
g.fillRect(tailX[i], tailY[i], SIZE, SIZE);
}
}
public void move() {
if (isMoving) {
for (int i = tailLength - 1; i > 0; i--) {
tailX[i] = tailX[i - 1];
tailY[i] = tailY[i - 1];
}
if (tailLength > 0) {
tailX[0] = x;
tailY[0] = y;
}
x += dx;
y += dy;
if (isGrown) {
tailLength++;
isGrown = false;
}
}
}
}