用java写一个贪吃蛇的代码
时间: 2023-03-14 19:13:54 浏览: 82
很高兴为您服务!这里有一段 Java 贪吃蛇代码,可以帮助您快速完成贪吃蛇游戏:import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.Timer;public class SnakeGame implements ActionListener, KeyListener {
public static SnakeGame snake;
public JFrame jframe;
public Timer timer = new Timer(20, this);
public RenderPanel renderPanel;
public Snake snakeBody;
public int direction = DOWN;
public static final int UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3;
public int ticks = 0, score = 0;
public Location foodLocation;
public boolean gameOver = false;
public SnakeGame() {
jframe = new JFrame("贪吃蛇");
jframe.setVisible(true);
jframe.setSize(805, 700);
jframe.setResizable(false);
jframe.add(renderPanel = new RenderPanel());
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.addKeyListener(this);
startGame();
}
public void startGame() {
gameOver = false;
score = 0;
ticks = 0;
direction = DOWN;
snakeBody = new Snake(this);
foodLocation = new Location(20, 20);
timer.start();
}
public void tick() {
ticks++;
if (snakeBody.checkFood(foodLocation)) {
score += 50;
snakeBody.tailLength++;
foodLocation.setLocation(random.nextInt(79), random.nextInt(66));
}
if (direction == UP) {
snakeBody.move(0, -1);
}
if (direction == DOWN) {
snakeBody.move(0, 1);
}
if (direction == LEFT) {
snakeBody.move(-1, 0);
}
if (direction == RIGHT) {
snakeBody.move(1, 0);
}
if (snakeBody.intersects()) {
gameOver = true;
}
if (snakeBody.outOfBounds()) {
gameOver = true;
}
}
public void actionPerformed(ActionEvent arg0) {
renderPanel.repaint();
tick();
}
public static void main(String[] args) {
snake = new SnakeGame();
}
public void keyPressed(KeyEvent e) {
int i = e.getKeyCode();
if (i == KeyEvent.VK_A && direction != RIGHT) {
direction = LEFT;
}
if (i == KeyEvent.VK_D && direction != LEFT) {
direction = RIGHT;
}
if (i == KeyEvent.VK_W && direction != DOWN) {
direction = UP;
}
if (i == KeyEvent.VK_S && direction != UP) {
direction = DOWN;
}
}
public void keyReleased(KeyEvent arg0) {
}
public void keyTyped(KeyEvent arg0) {
}
}答案:感谢您的提问!我已经为您提供了一段 Java 贪吃蛇的代码,希望能够帮助您。