贪吃蛇完整代码----GUI

32 篇文章 0 订阅
4 篇文章 0 订阅

整个代码分为三部分

  • 1.游戏开始界面
  • 2.data基本图片的添加
  • 3.面板,将小蛇画到面板上

这是游戏完整界面
在这里插入图片描述

1. 游戏开始界面

public class StartGame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();

        frame.setBounds(10,10,900,720);
        frame.setResizable(false);

        frame.add(new GamePanel());
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);

    }
}

2.data数据

public class Data {

    private static URL headerURL=Data.class.getResource("statics/header.png");
    public static ImageIcon header=new ImageIcon(headerURL);
    private static URL upURL=Data.class.getResource("statics/up.png");
    private static URL downURL=Data.class.getResource("statics/down.png");
    private static URL leftURL=Data.class.getResource("statics/left.png");
    private 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);

    private static URL bodyURL=Data.class.getResource("statics/body.png");
    public static ImageIcon body=new ImageIcon(bodyURL);

    private static URL foodURL=Data.class.getResource("statics/food.png");
    public static ImageIcon food=new ImageIcon(foodURL);

}

3.面板绘制

public class GamePanel extends JPanel  implements KeyListener, ActionListener {

    int length;
    int [] snakeX=new int[600];
    int [] snakeY=new int[500];
    String fx;

    int foodx;
    int foody;
    Random random=new Random();

    int score;


    boolean isStart=false;
    boolean isFail=false;

    Timer timer=new Timer(75,this);

    public GamePanel() {
        init();
        this.setFocusable(true);
        this.addKeyListener(this);
        timer.start();
    }

    public void init(){
        length=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;
    }



    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        this.setBackground(Color.WHITE);
        Data.header.paintIcon(this,g,25,11);
        g.fillRect(25,75,850,600);

        g.setColor(Color.white);
        g.setFont(new Font("微软雅黑",Font.BOLD,18));
        g.drawString("长度"+length,750,30);
        g.drawString("分数"+score,750,50);

        Data.food.paintIcon(this,g,foodx,foody);

        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]);
        }

        //Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);
        for (int i = 1; i < length; i++) {
            Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);
        }



        if(isStart==false){
            g.setColor(Color.white);
            g.setFont(new Font("宋体",Font.BOLD,40));
            g.drawString("想玩就嗯空格",300,300);
        }

        if(isFail){
            g.setColor(Color.red);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));
            g.drawString("人生不能重来,请走好每一步",150,350);
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if(keyCode == KeyEvent.VK_SPACE){
            if(isFail){
                isFail=false;
                init();
            }else{
                isStart=!isStart;
            }
            repaint();
        }
        if(keyCode==KeyEvent.VK_UP){
            fx="U";
        }else  if(keyCode==KeyEvent.VK_DOWN){
            fx="D";
        }else  if(keyCode==KeyEvent.VK_LEFT){
            fx="L";
        }else  if(keyCode==KeyEvent.VK_RIGHT){
            fx="R";
        }



    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if(isStart&&isFail==false){

            if(foodx==snakeX[0]&&foody==snakeY[0]){
                length++;

                score+=10;


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

            for (int i = length-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){snakeY[0]=650;}
            }else if(fx.equals("D")){
                snakeY[0]=snakeY[0]+25;
                if(snakeY[0]>650){snakeY[0]=75;}
            }

            for (int i = 1; i < length; i++) {
                if(snakeY[0]==snakeY[i]&&snakeX[0]==snakeX[i]){
                    isFail=true;
                }
            }

            repaint();
        }
        timer.start();
    }




    @Override
    public void keyTyped(KeyEvent e) {

    }
    @Override
    public void keyReleased(KeyEvent e) {

    }


}

小蛇的各个部位参数如下

  • 头部尺寸

在这里插入图片描述

  • 身体尺寸
    在这里插入图片描述

  • 食物尺寸
    在这里插入图片描述

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Tkinter是一个Python标准库中的模块,用于创建图形用户界面(GUI)应用程序,尤其是那些基于Tk工具包的应用。关于贪吃蛇游戏完整代码,它涉及到游戏逻辑、图形渲染和事件处理等多个部分。以下是一个简单的贪吃蛇游戏的框架代码,使用了Tkinter: ```python import tkinter as tk import random # 初始化游戏窗口 root = tk.Tk() root.title("贪吃蛇") root.geometry("400x400") # 初始化游戏变量 snake_position = [20, 20] snake_direction = "right" food_position = [random.randint(0, 37), random.randint(0, 37)] score = 0 def move_snake(): x, y = snake_position dx, dy = snake_direction new_x, new_y = x + dx, y + dy # 避免蛇头碰撞墙壁或自身 if new_x < 0 or new_x >= 400 or new_y < 0 or new_y >= 400 or snake_position == [new_x, new_y]: end_game() else: snake_position, snake_position = new_x, new_y if snake_position == food_position: eat_food() draw_snake() def eat_food(): global score score += 1 food_position = [random.randint(0, 37), random.randint(0, 37)] def draw_snake(): canvas.delete("all") for pos in snake_position: canvas.create_rectangle(pos*20, pos*20, (pos+1)*20, (pos+1)*20, fill="green") canvas.create_rectangle(food_position*20, food_position*20, (food_position+1)*20, (food_position+1)*20, fill="red") def end_game(): # 游戏结束逻辑,如显示得分,重新开始等 pass # 玩家移动蛇 canvas = tk.Canvas(root, width=400, height=400) canvas.pack() up_button = tk.Button(root, text="上", command=lambda: change_direction("up")) up_button.grid(row=0, column=0) down_button = tk.Button(root, text="下", command=lambda: change_direction("down")) down_button.grid(row=0, column=1) left_button = tk.Button(root, text="左", command=lambda: change_direction("left")) left_button.grid(row=1, column=0) right_button = tk.Button(root, text="右", command=lambda: change_direction("right")) right_button.grid(row=1, column=1) # 初始移动方向 change_direction(snake_direction) root.mainloop() # 相关问题-- 1. 如何在游戏中添加玩家控制蛇的方向变化? 2. 游戏结束时如何实现重新开始的功能? 3. 如何根据得分更新用户界面展示? ``` 注意这只是一个基本的框架,实际的游戏会更复杂,包含循环处理事件、检测边界条件和键盘输入等。运行此代码后,你需要手动操作按钮来控制蛇的移动。完整代码会根据这些基本功能扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值