1. <div id="main">
    2. <div id="core">
    3. <div id="snake">
    4. <div></div>
    5. </div>
    6. <div id="food">
    7. <div></div>
    8. <div></div>
    9. <div></div>
    10. <div></div>
    11. </div>
    12. </div>
    13. <div id="panel">
    14. <div>
    15. SCORE:<span id="score">0</span>
    16. </div>
    17. <div>
    18. level:<span id="level">1</span>
    19. </div>
    20. </div>
    21. </div>
    // 背景颜色
    @bg-color: #b7d4a8;
    
    // 清除样式
    *{
      margin: 0;
      padding: 0;
      // 盒子模型计算方式
      box-sizing: border-box;
    }
    
    body{
      font: bold 20px "Courier New";
    }
    
    // 主窗口
    #main{
      width: 360px;
      height: 420px;
      background-color: @bg-color;
      border: 8px solid #000000;
      border-radius: 15px;
      display: flex;
      flex-flow: column;
      align-items: center;
      justify-content: space-around;
    
      #core{
        width: 304px;
        height: 304px;
        border: 2px solid #000000;
        display: flex;
        position: relative;
    
        #snake{
          &>div{
            width: 10px;
            height: 10px;
            background-color: black;
            border: 1px solid @bg-color;
            position: absolute;
          }
        }
    
        #food{
          width: 10px;
          height: 10px;
          position: absolute;
          left: 40px;
          top: 100px;
          display: flex;
          flex-flow: row wrap;
          justify-content: space-between;
          align-content: space-between;
    
          &>div{
            width: 4px;
            height: 4px;
            background-color: black;
            transform: rotate(45deg);
          }
        }
      }
    
      #panel{
        width: 300px;
        display: flex;
        justify-content: space-between;
      }
    }
    
    import './style/index.less'
    
    import GameControl from "./moduls/GameControl"
    
    new GameControl();
    
    class Snake{
      // 蛇的元素
      head: HTMLElement;
      // 蛇的身体(包括蛇头,是一个集合)
      bodies: HTMLCollection;
      // 蛇的容器
      element: HTMLElement;
    
      constructor() {
        this.element = document.getElementById('snake')!
        this.head = document.querySelector('#snake > div')!;
        this.bodies = document.getElementById('snake')!.getElementsByTagName('div')
      }
    
      // 获取蛇的坐标
      get X(){
        return this.head.offsetLeft;
      }
      get Y(){
        return this.head.offsetTop;
      }
    
      // 设置蛇头的坐标
      set X(value){
    
        // 如果新值和旧值完全相同,则直接返回不再修改
        if(this.X === value){
          return;
        }
    
        // x的合法范围
        if(value <0 || value > 290){
          throw new Error('蛇撞墙了!');
        }
    
        // 修改x时,是在修改水平坐标,蛇在向左移动,不能向右掉头
        if(this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === value){
          if(value > this.X){
            // 新值value大于旧值X,蛇向右走
            value = this.X - 10;
          }else{
            // 向左走
            value = this.X + 10;
          }
        }
    
        // 移动
        this.moveBody();
    
        this.head.style.left = value + 'px';
    
        // 检查身体头碰撞
        this.checkHeadBody();
      }
      set Y(value){
        // 如果新值和旧值完全相同,则直接返回不再修改
        if(this.Y === value){
          return;
        }
    
        // y的合法范围
        if(value <0 || value > 290){
          throw new Error('蛇撞墙了!');
        }
    
        // 修改y时,是在修改垂直坐标,蛇在向上移动,不能向下掉头
        if(this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === value){
          if(value > this.Y){
            // 新值value大于旧值Y,蛇向右走
            value = this.Y - 10;
          }else{
            // 向左走
            value = this.Y + 10;
          }
        }
    
    
        // 移动
        this.moveBody();
    
        this.head.style.top = value + 'px';
    
        // 检查身体头碰撞
        this.checkHeadBody();
      }
    
      // 添加身体
      addBody(){
        // 添加一个div
        this.element.insertAdjacentHTML('beforeend', "<div></div>")
      }
    
      // 添加一个蛇身体移动的方法
      moveBody(){
        // 后边身体设置为前边身体的位置
        for(let i=this.bodies.length-1;i>0;i--){
          // 获取前面身体的位置
          let x = (this.bodies[i-1] as HTMLElement).offsetLeft;
          let y = (this.bodies[i-1] as HTMLElement).offsetTop;
    
          // 将值设置到当前身体上
          (this.bodies[i] as HTMLElement).style.left = x + 'px';
          (this.bodies[i] as HTMLElement).style.top = y + 'px';
        }
      }
    
      // 检查头和身体有没有碰撞
      checkHeadBody(){
        // 获取所有身体,检查其是否和蛇头的坐标发生重叠
        for(let i=1; i < this.bodies.length; i++){
          let bd = this.bodies[i]as HTMLElement
          if(this.X === bd.offsetLeft && this.Y === bd.offsetTop){
            // 撞到身体
            throw new Error('撞到自己了');
          }
        }
      }
    }
    
    export default Snake;
    
    import Snake from "./Snake";
    import Food from "./Food";
    import ScorePanel from "./ScorePanel";
    import scorePanel from "./ScorePanel";
    
    // 控制器,控制其他所有类
    class GameControl{
        // 定义三个属性
        // 蛇
        snake: Snake;
        // 食物
        food: Food;
        // 记分牌
        scorePanel: ScorePanel;
    
        // 创建一个属性来存储蛇的移动方向(也就是按键的方向)
        direction: string = '';
    
        // 游戏是否结束
        isLive = true;
    
        constructor() {
            this.snake = new Snake();
            this.food = new Food();
            this.scorePanel = new scorePanel(10,2);
    
            this.init();
        }
    
        // 游戏开始
        init(){
            document.addEventListener('keydown',this.keydownHandler.bind(this));
            this.run()
        };
    
        // 创建一个键盘按下的响应函数
        keydownHandler(event:KeyboardEvent){
            this.direction = event.key
            // console.log(event.key)
        }
    
        // 移动
        run(){
            let X = this.snake.X;
            let Y = this.snake.Y;
    
            switch (this.direction){
                case "ArrowUp":
                case 'Up':
                    Y -= 10;
                    break;
                case "ArrowDown":
                case 'Down':
                    Y += 10;
                    break;
                case "ArrowLeft":
                case 'Left':
                    X -= 10;
                    break;
                case "ArrowRight":
                case 'Right':
                    X += 10;
                    break;
            }
    
            // 检查蛇是否吃到了食物
            this.checkEat(X,Y);
    
            // 修改蛇的x值和y值
            try{
                this.snake.X = X;
                this.snake.Y = Y;
            }catch (e){
                alert(e+'GAME OVER!');
                this.isLive = false;
            }
    
            this.isLive && setTimeout(this.run.bind(this),300 - (this.scorePanel.level-1)*30);
            console.log(this.scorePanel.level-1)
        }
    
        // 定义一个方法,用来检查蛇是否吃到食物
        checkEat(X:number, Y:number){
            if(X === this.food.X && Y===this.food.Y){
                this.food.change();
                this.scorePanel.addScore();
                this.snake.addBody();
            }
        }
    
    }
    
    export default GameControl;
    
    // 定义记分牌的类
    class ScorePanel{
        score = 0;
        level = 1;
        scoreEle : HTMLElement;
        levelEle : HTMLElement;
    
        // 限制等级
        maxLevel : number;
        // 多少分升一级
        upScore: number;
    
        constructor(maxLevel:number = 100,upScore:number = 10) {
            this.scoreEle = document.getElementById('score')!;
            this.levelEle = document.getElementById('level')!;
            this.maxLevel = maxLevel;
            this.upScore = upScore;
        }
    
        // 设置加分方法
        addScore(){
            this.score++;
            this.scoreEle.innerHTML = this.score + ''
            // 判断分数是多少
            if(this.score % this.upScore ===0){
                this.levelUp();
            }
        }
    
        // 提升等级的方法
        levelUp(){
            if(this.level < this.maxLevel){
                this.levelEle.innerHTML = ++this.level + ''
            }
        }
    }
    
    export default ScorePanel;
    
    // 定义食物类
    class Food{
        // 定义一个属性表示食物所对应的元素
        element: HTMLElement;
    
        constructor() {
            // 获取页面中的food元素并将其赋值给element
            this.element = document.getElementById('food')!;
        }
    
        // 定义一个获取食物x轴坐标的方法
        get X(){
            return this.element.offsetLeft;
        }
        get Y(){
            return this.element.offsetTop;
        }
    
        // 修改食物的位置
        change(){
            // 随机位置
            // 食物的位置最小是0,最大是290
            // 蛇移动一次就是一格,一格大小是10,食物移动必须也为10为单位
    
            let top = Math.round(Math.random() * 29) *10;
            let left = Math.round(Math.random() * 29) *10;
            this.element.style.top = top + 'px';
            this.element.style.left = left + 'px';
        }
    }
    
    export default Food;