下面是一个简单的Java实现贪吃蛇游戏的示例代码:
import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class SnakeGame extends JFrame implements KeyListener { private static final int WIDTH = 300; private static final int HEIGHT = 300; private int snakeX; private int snakeY; private int appleX; private int appleY; private int direction; public SnakeGame() { setSize(WIDTH, HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); setResizable(false); addKeyListener(this); snakeX = WIDTH / 2; snakeY = HEIGHT / 2; appleX = (int) (Math.random() * WIDTH); appleY = (int) (Math.random() * HEIGHT); direction = 0; startGameLoop(); } private void startGameLoop() { while (true) { moveSnake(); checkCollision(); repaint(); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } private void moveSnake() { if (direction == 0) snakeX++; if (direction == 1) snakeY++; if (direction == 2) snakeX--; if (direction == 3) snakeY--; } private void checkCollision() { if (snakeX == appleX && snakeY == appleY) { appleX = (int) (Math.random() * WIDTH); appleY = (int) (Math.random() * HEIGHT); } } @Override public void paint(Graphics g) { super.paint(g); g.setColor(Color.BLACK); g.fillRect(0, 0, WIDTH, HEIGHT); g.setColor(Color.RED); g.fillRect(appleX, appleY, 10, 10); g.setColor(Color.GREEN); g.fillRect(snakeX, snakeY, 10, 10); Toolkit.getDefaultToolkit().sync(); g.dispose(); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_RIGHT && direction != 2) direction = 0; if (key == KeyEvent.VK_DOWN && direction != 3) direction = 1; if (key == KeyEvent.VK_LEFT && direction != 0) direction = 2; if (key == KeyEvent.VK_UP && direction != 1) direction = 3; } @Override public void keyReleased(KeyEvent e) { } public static void main(String[] args) { new SnakeGame(); } }
这段代码是一个简单的贪吃蛇游戏的实现,使用Java的Swing库进行绘制。
在构造函数中设置了窗口的大小、位置等属性,并初始化了贪吃蛇和苹果的位置以及当前运动方向。
startGameLoop()方法是游戏的主循环,不断地移动贪吃蛇、检查碰撞并重绘窗口。
moveSnake()方法根据当前的方向移动贪吃蛇的位置。
checkCollision()方法检查贪吃蛇是否与苹果碰撞,如果碰撞则重新生成苹果的位置。
paint()方法用于绘制窗口的内容,包括背景、苹果和贪吃蛇。
keyPressed()方法用于处理键盘按键事件,根据按键改变贪吃蛇的方向。
你可以将这段代码保存为SnakeGame.java文件,并使用Java编译器进行编译运行。