Java贪吃蛇

在一些培训机构学期的记录

 

                          

package com.a;//顶级域名.公司.

import javax.swing.JFrame;
import javax.swing.JFrame;

//后续部分根据不同机构各自内部的命名规范而不尽相同。这类命名规范可能以特定目录名的组成来区分部门(department),项目(project),机器(machine),或注册名(login names)
//顶级域名,通常是com,edu,gov,mil,net,org
//类名:每个单词首字母要大写。例如:class FirstSnake{}
//接口名:与类名一样。例如:interface RasterDelegate{}
//方法名:第一个单词首字母小写,其余单词首字母大写。例如:public void firstSnake(){}
//变量:与方法名一样。例如:int myWidth
//实例变量:与变量相似。例如:int _myWidth
//常量变量:每个字母大写,单词之间用下划线隔开。例如:static final int GET_THE_CPU = 1;

public class FirstSnake {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        // 创建一个JFrame窗口对象frame
        frame.setBounds(500, 150, 900, 720);
        // 设置frame窗口的位置(以电脑左上角为原点,y轴向下为正方向,x轴向右为正方向建立平面直角坐标系,先x轴后y轴)和大小900*720
        frame.setResizable(false);
        // 用户不能调整frame窗口的大小
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置用户在frame窗口上发起“close”时默认(看不到了)
        frame.add(new FirstSnakeMpanel());
        // 将Mpanel的组件添加到frame窗口上
        frame.setVisible(true);
        // frame窗口可见
    }
}

 

 

package com.a;

import java.awt.Color;
import java.awt.Font;
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 java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;

public class FirstSnakeMpanel extends JPanel implements KeyListener, ActionListener {
    ImageIcon title = new ImageIcon("title.jpg");
    // 添加标题图片
    ImageIcon body = new ImageIcon("body.png");
    // 添加身体图片
    ImageIcon food = new ImageIcon("food.png");
    // 添加食物图片
    ImageIcon up = new ImageIcon("up.png");
    // 添加向上的蛇头
    ImageIcon down = new ImageIcon("down.png");
    // 添加向下的蛇头
    ImageIcon left = new ImageIcon("left.png");
    // 添加向左的蛇头
    ImageIcon right = new ImageIcon("right.png");
    // 添加向右的蛇头
    int length = 3;
    // 蛇的初始长度为3
    int score = 0;
    // 显示分数
    int snakeX[] = new int[750];
    // 储存每一节的x坐标
    int snakeY[] = new int[750];
    // 储存每一节的y坐标
    int foodX, foodY;
    // 食物坐标
    int difficulty = 0;
    // 难度系数
    char direction = 'R';
    // 方向上U下D左L右R,与下面的switch相关联,初始蛇头方向
    String state;
    // 状态:未开始、正在游戏中、暂停、获胜(胜利状态附加暂停状态)、死亡
    boolean isStart = false;
    // false为未开始,true为开始
    boolean isDead = false;
    // true为死亡
    boolean isStop = false;
    // false为不暂停,true为暂停
    boolean isWin = false;
    // 是否获胜
    Timer time = new Timer(100, this);
    // 创建一个java定时器对象time
    Random random = new Random();
    // 创建生成随机数对象random

    public FirstSnakeMpanel() {
        initSnake();
        // 初始化蛇
        this.setFocusable(true);
        // 设置其可以获取键盘事件
        this.addKeyListener(this);
        // 添加键盘监听器
        time.start();
        // 启动计时器
    }

    public void paintComponent(Graphics g)/* Graphics画笔g */ {
        super.paintComponent(g);
        // 重写父类中的paintComponent方法
        this.setBackground(Color.yellow);
        // 背景颜色白色
        title.paintIcon(this, g, 25, 11);
        /*
         * 标题图片位置(以frame窗口左上角为原点,y轴向下为正方向,x轴向右为正方向建立平面直角坐标系) 发现:超出frame窗口范围的部分不可见
         */
        g.fillRect(25, 75, 850, 600);
        /*
         * 添加游戏区,游戏区的位置(以frame窗口左上角为原点,y轴向下为正方向,x轴向右为正方向建立平面直角坐标系) 游戏区的大小850*600,先x轴后y轴
         */
        switch (direction) {
        case 'R':
            // 蛇头向右
            right.paintIcon(this, g, snakeX[0], snakeY[0]);
            break;
        case 'L':
            // 蛇头向左
            left.paintIcon(this, g, snakeX[0], snakeY[0]);
            break;
        case 'U':
            // 蛇头向上
            up.paintIcon(this, g, snakeX[0], snakeY[0]);
            break;
        case 'D':
            // 蛇头向下
            down.paintIcon(this, g, snakeX[0], snakeY[0]);
            break;
        }
        for (int i = 1; i < length; i++)
            body.paintIcon(this, g, snakeX[i], snakeY[i]);
        // 循环描述每一节蛇身的位置
        food.paintIcon(this, g, foodX, foodY);
        // 食物图片
        g.setColor(Color.white);
        g.drawString("length=" + length, 750, 20);
        // 添加长度显示
        g.drawString("score=" + score, 750, 35);
        // 添加分数显示
        g.drawString("difficulty=" + difficulty, 750, 50);
        // 添加难度显示
        g.drawString("state=" + state, 750, 65);
        // 添加状态显示
        if (isStart == false && isDead == false && isStop == false)/* 未开始时显示提示字符串 */ {
            g.setColor(Color.blue);
            // 字符串颜色蓝色
            g.setFont(new Font("宋体", Font.BOLD, 40));
            // 字符串样式,加粗,大小
            g.drawString("按下空格开始", 238, 293);
            // 具体字符串内容,字体位置
        }
        if (isStart == true && isDead == true && isStop == false)/* 死亡时显示提示字符串 */ {
            g.setColor(Color.RED);
            // 字符串颜色红色
            g.setFont(new Font("宋体", Font.BOLD, 40));
            // 字符串样式,加粗,大小
            g.drawString("you died", 238, 293);
            // 具体字符串内容,字体位置
        }
        if (isStart == true && isDead == false && isStop == true)/* 暂停时显示提示字符串 */ {
            g.setColor(Color.RED);
            // 字符串颜色红色
            g.setFont(new Font("宋体", Font.BOLD, 40));
            // 字符串样式,加粗,大小
            g.drawString("Stop", 238, 293);
            // 具体字符串内容,字体位置
        }
        if (isWin == true && isStart == true && isDead == false)/* 难度达到11级算通关成功 */ {
            g.setColor(Color.red);
            // 字符串颜色红色
            g.setFont(new Font("宋体", Font.BOLD, 60));
            // 字符串样式,加粗,大小
            g.drawString("you are lucky and you win", 40, 181);
            // 具体字符串内容,字体位置
            g.drawString("按下空格继续", 238, 454);
        }
    }

    public void initSnake()/* 初始化数据 */ {
        length = 3;
        score = 0;
        difficulty = 0;
        snakeX[0] = 75;
        snakeY[0] = 75;
        snakeX[1] = 50;
        snakeY[1] = 75;
        snakeX[2] = 25;
        snakeY[2] = 75;
        foodX = 25 + 25 * random.nextInt(34);
        foodY = 75 + 25 * random.nextInt(24);
        direction = 'R';
        state = "not start";
        isWin = false;
        Timer time = new Timer(100, this);
    }

    public void levelDifficulty()/* 难度梯度 */ {
        if (score >= 10 && score <= 30) {
            Timer time = new Timer(90, this);
            difficulty = 1;
        } else if (score > 30 && score <= 66) {
            Timer time = new Timer(80, this);
            difficulty = 2;
        } else if (score > 66 && score <= 80) {
            Timer time = new Timer(70, this);
            difficulty = 3;
        } else if (score > 80 && score <= 100) {
            Timer time = new Timer(60, this);
            difficulty = 4;
        } else if (score > 100 && score <= 150) {
            Timer time = new Timer(50, this);
            difficulty = 5;
        } else if (score > 150 && score <= 250) {
            Timer time = new Timer(40, this);
            difficulty = 6;
        } else if (score > 250 && score <= 350) {
            Timer time = new Timer(30, this);
            difficulty = 7;
        } else if (score > 350 && score <= 500) {
            Timer time = new Timer(20, this);
            difficulty = 8;
        } else if (score > 500 && score <= 666) {
            Timer time = new Timer(10, this);
            difficulty = 9;
        } else if (score > 666 && score <= 800) {
            Timer time = new Timer(1, this);
            difficulty = 10;
        } else if (score == 816 && difficulty == 10) {
            difficulty = 11;
            isWin = true;
            state = "win";
            isStop = true;
        }
    }

    public void actionPerformed(ActionEvent k) {
        if (isStart == true && isDead == false && isStop == false)
            for (int i = length - 1; i > 0; i--) {
                snakeX[i] = snakeX[i - 1];
                snakeY[i] = snakeY[i - 1];
                // 蛇的每一节身体都向前一节移动
                time.start();
            }
        switch (direction) {
        case 'R':
            if (isStart == true)
                snakeX[0] += 25;
            //持续向右移动
            if (snakeX[0] > 850) {
                isDead = true;
                state = "failed";
                time.stop();
            }
            //超出右边界,死亡
            break;
        case 'L':
            if (isStart == true)
                snakeX[0] -= 25;
            //持续向左移动
            if (snakeX[0] < 25) {
                isDead = true;
                state = "failed";
                time.stop();
            }
            //超出左边界,死亡
            break;
        case 'U':
            if (isStart == true)
                snakeY[0] -= 25;
            //持续向上移动
            if (snakeY[0] < 75) {
                isDead = true;
                state = "failed";
                time.stop();
            }
            //超出上边界,死亡
            break;
        case 'D':
            if (isStart == true)
                snakeY[0] += 25;
            //持续向下移动
            if (snakeY[0] > 670) {
                isDead = true;
                state = "failed";
                time.stop();
            }
            //超出下边界,死亡
            break;
        }
        if (snakeX[0] == foodX && snakeY[0] == foodY)/* 吃掉食物 */ {
            length++;
            // 长度加1
            score += 1;
            // 分数加1
            levelDifficulty();
            //调用方法,判断是否增加难度
            foodX = 25 + 25 * random.nextInt(34);
            foodY = 75 + 25 * random.nextInt(24);
            // 随机生成食物
            for (int i = 0; i < length; i++)
                if (snakeX[i] == foodX && snakeY[i] == foodY) {
                    foodX = 25 + 25 * random.nextInt(34);
                    foodY = 75 + 25 * random.nextInt(24);
                }
            //如果食物生成在蛇的内,重新生成食物
        }
        for (int i = 1; i < length; i++)
            if (snakeX[i] == snakeX[0] && snakeY[i] == snakeY[0]) {
                isDead = true;
                state = "failed";
                time.stop();
            }
        //蛇头咬到身体,死亡
        if (isWin == true)
            time.stop();
        //胜利状态时间暂停
        repaint();
        //重画
    }

    public void keyPressed(KeyEvent k) {
        int keycode = k.getKeyCode();
        // 获取按下键的值
        switch (keycode) {
        case KeyEvent.VK_SPACE:
            if (isStart == true && isDead == false && isWin == false) {
                if (isStop == true) {
                    isStop = false;
                    state = "start";
                    repaint();
                    time.start();
                } else {
                    isStop = true;
                    state = "stop";
                    repaint();
                    time.stop();
                }
            }
            //开始状态与暂停状态相互转换
            if (isStart == false && isStop == false && isDead == false && isWin == false) {
                isStart = true;
                initSnake();
                state = "start";
                repaint();
            }
            //未开始状态改为开始状态
            if (isStart == true && isStop == false && isDead == true && isWin == false) {
                isStart = false;
                isDead = false;
                initSnake();
                time.start();
                repaint();
            }
            //死亡状态改为未开始状态
            if (isWin == true && isStart == true && isStop == true && isDead == false) {
                isWin = false;
                isStop = false;
                Timer time = new Timer(1, this);
                state = "start";
                time.start();
                repaint();

            }
            //胜利状态改为开始状态
            break;
        case KeyEvent.VK_RIGHT:
            if (direction != 'L')
                // 如果蛇头不为向左
                direction = 'R';
            // 按下“->”改变蛇头方向向右
            break;
        case KeyEvent.VK_LEFT:
            if (direction != 'R')
                // 如果蛇头不为向右
                direction = 'L';
            // 按下“<-”改变蛇头方向向左
            break;
        case KeyEvent.VK_UP:
            if (direction != 'D')
                // 如果蛇头不为向下
                direction = 'U';
            // 按下“上键”改变蛇头方向向上
            break;
        case KeyEvent.VK_DOWN:
            if (direction != 'U')
                // 如果蛇头不为向上
                direction = 'D';
            // 按下“下键”改变蛇头方向向下
            break;
        default:
            break;
        }
    }

    public void keyReleased(KeyEvent k) {
    }

    public void keyTyped(KeyEvent k) {
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值