java贪吃蛇游戏源代码idea
时间: 2025-01-06 07:14:46 浏览: 65
### Java贪吃蛇游戏源代码及其在IntelliJ IDEA中的运行
为了帮助理解如何创建和运行一个基于Java的贪吃蛇游戏,下面是一个简化版的游戏框架。该版本利用了`Swing`组件用于图形界面构建,并采用`LinkedList`存储蛇的身体位置。
#### 主要使用的库与类介绍
- `javax.swing.*`: 提供了一套轻量级组件支持GUI应用开发[^1]。
- `java.awt.*`: 包含基本绘图功能的支持,如颜色、字体等设置[^2]。
- `java.util.LinkedList`: 动态链表结构用来保存贪吃蛇的位置坐标列表。
- `java.util.Random`: 生成食物出现位置所需的伪随机数值。
- `java.awt.event.KeyListener`: 处理来自键盘的方向键输入以控制方向变化。
#### 完整示例代码如下:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.LinkedList;
public class SnakeGame extends JPanel implements ActionListener {
private final int UNIT_SIZE = 25; // 单元格大小
private final int GAME_UNITS = (800 * 600) / (UNIT_SIZE * UNIT_SIZE);
private final int DELAY = 75;
private final Timer timer;
private final Random random;
private LinkedList<Point> snakeBody = new LinkedList<>();
private Point applePosition;
private boolean running = false;
private char direction = 'R';
public SnakeGame() {
random = new Random();
this.setPreferredSize(new Dimension(800, 600));
this.setBackground(Color.BLACK);
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
timer = new Timer(DELAY, this);
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
private void startGame(){
addApple();
addSnake();
running=true;
}
// 添加苹果的方法...
private void addApple(){
int x = random.nextInt((int)(getWidth()/UNIT_SIZE))*UNIT_SIZE;
int y = random.nextInt((int)(getHeight()/UNIT_SIZE))*UNIT_SIZE;
applePosition=new Point(x,y);
}
// 初始化蛇身的方法...
private void addSnake(){
snakeBody.clear();
for(int i=4;i>=0;i--){
snakeBody.addFirst(new Point(i*UNIT_SIZE,0));
}
}
// 绘制画面逻辑...
private void draw(Graphics g){
if(running){
g.setColor(Color.RED);
g.fillOval(applePosition.x,applePosition.y,UNIT_SIZE,UNIT_SIZE);
for(Point point : snakeBody){
g.setColor(Color.GREEN);
g.fillRect(point.x ,point.y ,UNIT_SIZE,UNIT_SIZE );
}
Toolkit.getDefaultToolkit().sync();
}else{
gameOver(g);
}
}
// 游戏结束处理...
private void gameOver(Graphics g){
String msg="Game Over";
Font font = new Font("Arial",Font.BOLD,40);
FontMetrics metrics=getFontMetrics(font);
g.setColor(Color.WHITE);
g.setFont(font);
g.drawString(msg,(getWidth()-metrics.stringWidth(msg))/2,
getHeight()/2);
}
// 移动更新逻辑...
private void move(){
switch(direction){
case 'U':
snakeBody.getLast().y-=UNIT_SIZE;break;
case 'D':
snakeBody.getLast().y+=UNIT_SIZE;break;
case 'L':
snakeBody.getLast().x-=UNIT_SIZE;break;
case 'R':
snakeBody.getLast().x+=UNIT_SIZE;break;
}
checkCollision();
updateSnakeBody();
}
// 更新蛇身体节段...
private void updateSnakeBody(){
Point lastPoint = null;
for(int i=snakeBody.size()-2 ;i >= 0 ;i--) {
if(lastPoint==null){
lastPoint =new Point(snakeBody.get(i).x,snakeBody.get(i).y);
}else{
Point temp = new Point(snakeBody.get(i).x,snakeBody.get(i).y);
snakeBody.set(i+1,lastPoint);
lastPoint=temp;
}
}
if(lastPoint!=null){
snakeBody.set(0,lastPoint);
}
}
// 碰撞检测...
private void checkCollision(){
// 检查是否吃到自己或其他边界条件...
for(int i=snakeBody.size()-1;i>0;i--){
if((snakeBody.getFirst().equals(snakeBody.get(i)))){
running=false;
}
}
if(snakeBody.getFirst().x<0 || snakeBody.getFirst().x>=getWidth()){
running=false;
}
if(snakeBody.getFirst().y<0 || snakeBody.getFirst().y>=getHeight()){
running=false;
}
if(!running){
timer.stop();
}
}
// 吃到苹果后的反应...
private void pickUpApple(){
if(snakeBody.getLast().equals(applePosition)){
snakeBody.addLast(new Point(-1,-1));// 增加新的尾巴节点
addApple();// 放置新苹果
}
}
@Override
public void actionPerformed(ActionEvent e) {
if(running){
move();
pickUpApple();
}
repaint();
}
// 键盘监听适配器...
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';
阅读全文
相关推荐


















