贪吃蛇小游戏源码分享

创建2个文件夹,一个是放源码还有一个文件夹是发图片的。

然后创建三个实体类。

package com.Bubbles.snake;

import javax.swing.*;
import java.net.URL;

public class Data {
  //存放外部数据

  //1.头部的图片  URL :定位图片的地址     ImageIcon:图片
  public  static URL headerURL = Data.class.getResource ("/statics/header.png");
  public static ImageIcon header = new ImageIcon (headerURL);

  //2.头部
  public  static URL upUrl = Data.class.getResource ("/statics/up.png");
  public  static URL downUrl = Data.class.getResource ("/statics/down.png");
  public  static URL leftUrl = Data.class.getResource ("/statics/left.png");
  public  static URL rightUrl = Data.class.getResource ("/statics/right.png");
  public static ImageIcon up = new ImageIcon (upUrl);
  public static ImageIcon down = new ImageIcon (downUrl);
  public static ImageIcon left = new ImageIcon(leftUrl);
  public static  ImageIcon right = new ImageIcon (rightUrl);
   //3.身体
  public  static  URL bodyUrl = Data.class.getResource ("/statics/body.png");
  public  static  ImageIcon body = new ImageIcon (bodyUrl);
  //4.食物
  public static  URL foduUrl = Data.class.getResource ("/statics/food.png");
  public static ImageIcon food = new ImageIcon (foduUrl);

--------------------------------------------------------------------------------------------------------

package com.Bubbles.snake;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.security.Key;
import java.util.Random;

//1.继承JPanel,才能实现面板效果
public class GamePamel  extends JPanel implements KeyListener, ActionListener {
   //7.画蛇
    int lenth; //蛇的长度
    int [] snakex = new int[600]; //蛇的坐标x
    int [] snakeY = new int[500]; //蛇的坐标Y
    String fx ; //12.蛇的方向,R :右,L:左 U: 上 D:下

    boolean isStrart = false; //游戏是否开始

    //定义变量
    Timer timer = new Timer (100,this);//定时器
     //定义一个食物
    int foodx;
    int foody;
    Random random = new Random ();
    //死亡判断
    boolean isFall = false;
    //积分系统
    int score;
    //10.构造器
    public GamePamel(){
        init ();
     //14.获取键盘的监听事件
        this.setFocusable (true);
        this.addKeyListener (this);
        timer.start ();//让时间动起来
    }

    //8.初始化
    public void init(){
        lenth  = 3;
        snakex[0] = 100; snakeY[0] = 100; //头部坐标
        snakex[1] = 75; snakeY[1] = 100; //第一个身体坐标
        snakex[2] = 50; snakeY[2] = 100; //第二个身体坐标
        fx = "R";

        foodx = 25 + 25 * random.nextInt (34);
        foody = 75 + 25 * random.nextInt (24);
        score = 0;
    }

     //2.画板:画界面,画蛇
    //3.重写方法paintComponent
    @Override
    protected void paintComponent(Graphics g) { //Graphics =画笔
        super.paintComponent (g);  //清屏
        this.setBackground (Color.BLACK); //4.设置背景的颜色
        //5.绘制头部的公告栏
         Data.header.paintIcon (this,g,25,11);  //距离
         g.fillRect (25,75,850,600); //6.绘制游戏区域

        //9.画一条静态的小蛇
         if(fx.equals ("R")){ //右走
             Data.right.paintIcon (this,g,snakex[0],snakeY[0]); //脑袋
         } else if (fx.equals ("L")){ //左走
             Data.left.paintIcon (this,g,snakex[0],snakeY[0]); //脑袋
         } else if (fx.equals ("U")){ //上走
             Data.up.paintIcon (this,g,snakex[0],snakeY[0]); //脑袋
         } else if (fx.equals ("D")){ //下走
             Data.down.paintIcon (this,g,snakex[0],snakeY[0]); //脑袋
         }
        //11.一个一个写的身体比较麻烦,所以要将他循环
        for (int i = 1; i < lenth; i++) {
            Data.body.paintIcon (this,g,snakex[i],snakeY[i]); //蛇的身体长度通过lenth来控制
        }
        //画积分
        g.setColor (Color.white);
        g.setFont (new Font ("微软雅黑",Font.BOLD,18));
        g.drawString ("长度:"+lenth,750,35);
        g.drawString ("分数:"+score,750,50);
        //画食物
        Data.food.paintIcon (this,g,foodx,foody);

        //游戏提示:是否开始
        if(isStrart==false){
            //两一个文字,String
             g.setColor (Color.WHITE);//设置画笔的颜色
             g.setFont (new Font ("微软雅黑",Font.BOLD,40)); //设置字体
             g.drawString ("按下空格开始游戏",300,300);
        }
      //失败提醒
        if(isFall){
            //两一个文字,String
            g.setColor (Color.RED);//设置画笔的颜色
            g.setFont (new Font ("微软雅黑",Font.BOLD,40)); //设置字体
            g.drawString ("游戏失败,按下空格重新开始",200,300);
        }

    }


    //13.接收键盘的输入:监听
    @Override
    public void keyPressed(KeyEvent e) {
      //键盘按下,未释放
      //获取按下的键盘是哪个键
      int KeyCode = e.getKeyCode ();
      //判断
        if (KeyCode==KeyEvent.VK_SPACE){ //如果按下的是空格键
            if(isFall){ //失败,游戏再来一遍
               isFall = false;
               init ();//重新初始化游戏
            }else{ //暂停游戏
                isStrart = !isStrart;
            }

              repaint ();//刷新界面
        }
   //键盘控制走向
        if(KeyCode==KeyEvent.VK_LEFT){
            fx="L";//左
        }else if (KeyCode==KeyEvent.VK_RIGHT){
            fx="R";
        }else if (KeyCode==KeyEvent.VK_UP){
            fx="U";
        }else if (KeyCode==KeyEvent.VK_DOWN){
            fx="D";
        }
    }
//定时器,监听时间,帧 :执行定时操作
@Override
public void actionPerformed(ActionEvent e) {
    //如果游戏处于开始状态,并且游戏没有结束
    if(isStrart && isFall==false ){
        //右移
        for (int i = lenth-1; i >0 ; i--) {//除了脑袋,身体都向前移动
            snakex[i] =snakex[i-1];
            snakeY[i] =snakeY[i-1];
        }
         //通过控制方向让头部移动
          if(fx.equals ("R")){
              snakex[0]= snakex[0] + 25; //头部移动
              if(snakex[0]>850){ snakex[0] = 25; }
              }else if (fx.equals ("L")){
               snakex[0] =snakex[0] - 25; //头部移动
              if(snakex[0]<25){ snakex[0] = 850; }
              }else if (fx.equals ("U")){
              snakeY[0] =snakeY[0] - 25; //头部移动
              if(snakeY[0]<75){ snakex[0] = 650; }
          }else if (fx.equals ("D")){
              snakeY[0] =snakeY[0] + 25; //头部移动
              if(snakeY[0]>650){ snakeY[0] = 75; }
          }
//如果小蛇的头和咋们的食物重合了
        if(snakex[0]==foodx && snakeY[0]==foody){
            //长度+1
            lenth++;

            score = score +10;

          //重新生成食物
            foodx = 25 + 25 * random.nextInt (34);
            foody = 75 + 25 * random.nextInt (24);

        }
          //结束判断
        for (int i = 1; i <lenth ; i++) {
             if(snakex[0]==snakex[i] && snakeY[0] ==snakeY[i]){
               isFall = true;
             }
        }
        //刷新界面
        repaint ();
    }
    timer.start ();//让时间动起来
    }

    @Override
    public void keyTyped(KeyEvent e) {
        //键盘按下,弹起:敲击
    }
    @Override
    public void keyReleased(KeyEvent e) {
        //释放某个键
    }

--------------------------------------------------------------------------------------------------

package com.Bubbles.snake;

import javax.swing.*;

public class StartGames {
    public static void main(String[] args) {
        //1.绘制一个静态窗口 JFname
        JFrame frame = new JFrame ("彬哥-贪吃蛇小游戏");
        //2.设置界面的大小
        frame.setBounds (10, 10, 900, 720);
        frame.setResizable (false); //3.窗口大小则不可以改变
        //4.设置关闭事件,游戏可以关闭了
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

        //6.面板 JPanel,可以加入到Frame
        frame.add (new GamePamel ());

        frame.setVisible (true); //5.让窗口能够展现出来
    }
}

--贪吃蛇小游戏源码分享
 

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当然,这是一个简单的C语言贪吃蛇小游戏源代码示例: ```c #include <stdio.h> #include <conio.h> #include <stdlib.h> #include <windows.h> int width = 20, height = 20; int gameover; int x, y, fruitX, fruitY, score; int tailX[100], tailY[100]; int nTail; enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN }; enum eDirection dir; void Setup() { gameover = 0; dir = STOP; x = width / 2; y = height / 2; fruitX = rand() % width; fruitY = rand() % height; score = 0; } void Draw() { system("cls"); for (int i = 0; i < width + 2; i++) printf("#"); printf("\n"); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (j == 0) printf("#"); if (i == y && j == x) printf("O"); else if (i == fruitY && j == fruitX) printf("F"); else { int printTail = 0; for (int k = 0; k < nTail; k++) { if (tailX[k] == j && tailY[k] == i) { printf("o"); printTail = 1; } } if (!printTail) printf(" "); } if (j == width - 1) printf("#"); } printf("\n"); } for (int i = 0; i < width + 2; i++) printf("#"); printf("\n"); printf("Score:%d\n", score); } void Input() { if (_kbhit()) { switch (_getch()) { case 'a': dir = LEFT; break; case 'd': dir = RIGHT; break; case 'w': dir = UP; break; case 's': dir = DOWN; break; case 'x': gameover = 1; break; } } } void Logic() { int prevX = tailX[0]; int prevY = tailY[0]; int prev2X, prev2Y; tailX[0] = x; tailY[0] = y; for (int i = 1; i < nTail; i++) { prev2X = tailX[i]; prev2Y = tailY[i]; tailX[i] = prevX; tailY[i] = prevY; prevX = prev2X; prevY = prev2Y; } switch (dir) { case LEFT: x--; break; case RIGHT: x++; break; case UP: y--; break; case DOWN: y++; break; default: break; } if (x >= width) x = 0; else if (x < 0) x = width - 1; if (y >= height) y = 0; else if (y < 0) y = height - 1; for (int i = 0; i < nTail; i++) { if (tailX[i] == x && tailY[i] == y) gameover = 1; } if (x == fruitX && y == fruitY) { score += 10; fruitX = rand() % width; fruitY = rand() % height; nTail++; } } int main() { Setup(); while (!gameover) { Draw(); Input(); Logic(); Sleep(10); // 控制游戏速度 } return 0; } ``` 这个代码示例实现了一个基本的贪吃蛇小游戏,使用了C语言的基本语法和控制台输入输出函数。你可以将代码复制到一个C语言编译器中(如Dev-C++、Code::Blocks等)进行编译和运行。希望这能帮到你!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值