search
HomeWeb Front-endJS TutorialJavascript writing 2048 mini game_javascript skills

Last year, 2048 was very popular. I had never played it before. My colleague said that if you use JS to write 2048, it only takes more than 100 lines of code;

I tried it today, and the logic is not complicated. It mainly involves various operations on the data in the data constructor, and then updates the interface by re-rendering the DOM. The whole thing is not complicated. The total cost of JS, CSS, and HTML is 300. Multiple lines;

The interface is generated using the template method of underscore.js, using jQuery, mainly for DOM selection and operation and animation effects. The binding of events is only compatible with the PC side, and only the keydown event is bound;

Put the code on github-page and click here to view the example: Open the 2048 instance;

The rendering is as follows:

All codes are divided into two blocks, Data and View;

Data is a constructor, which will construct the data, and the data will inherit some methods on the prototype;

View generates views based on instances of Data and binds events. I directly regard events as controllers and put them together with View. There is no need to separate them;

The structure of Data is as follows:

    /**
     * @desc 构造函数初始化
     * */
    init : function
    /**
     * @desc 生成了默认的数据地图
     * @param void
     * */
    generateData : function
    /**
     * @desc 随机一个block填充到数据里面
     * @return void
     * */
    generationBlock : function
    /**
     * @desc 获取随机数 2 或者是 4
     * @return 2 || 4;
     * */
    getRandom : function
    /**
     * @desc 获取data里面数据内容为空的位置
     * @return {x:number, y:number}
     * */
    getPosition : function
    /**
     * @desc 把数据里第y排, 第x列的设置, 默认为0, 也可以传值;
     * @param x, y
     * */
    set : function
    /**
     * @desc 在二维数组的区间中水平方向是否全部为0
     * @desc i明确了二维数组的位置, k为开始位置, j为结束为止
     * */
    no_block_horizontal : function
    no_block_vertica : function
    /**
     * @desc 往数据往左边移动,这个很重要
     * */
    moveLeft : function
    moveRight : function
    moveUp : function
    moveDown : function

With the data model, the view is simple. It mainly uses the template method of the bottom line library underscore to generate html strings with the data, and then redraws the interface:

View’s prototype method:
​​​​ renderHTML: function //Generate html string and put it in the interface
init: function //Constructor initialization method
           bindEvents: function //Bind events to str, just think it is a controller

Because the original 2048 has the movement effect of blocks, we have independently set up a service (tool method, this tool method will be inherited by View), which is mainly responsible for the movement of blocks in the interface. getPost is used by the bottom line library. During the template generation process, it is necessary to dynamically generate horizontal and vertical coordinates according to the position of the node, and then position:

  var util = {
    animateShowBlock : function() {
      setTimeout(function() {
        this.renderHTML();
      }.bind(this),200);
    },
    animateMoveBlock : function(prop) {
      $("#num"+prop.form.y+""+prop.form.x).animate({top:40*prop.to.y,left:40*prop.to.x},200);
    },
    //底线库的模板中引用了这个方法;
    getPost : function(num) {
      return num*40 + "px";
    }
    //这个应该算是服务;
  };

The following is all the code. The referenced JS uses CDN, you can open it directly and have a look:

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
<script src="http://cdn.bootcss.com/underscore.js/1.8.3/underscore-min.js"></script>
<script src="http://cdn.bootcss.com/jquery/2.1.4/jquery.js"></script>
<style>
  #g{
    position: relative;
  }

  .block,.num-block{
    position: absolute;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    border-radius: 4px;
  }
  .block{
    border:1px solid #eee;
    box-sizing: border-box;
  }
  .num-block{
    color:#27AE60;
    font-weight: bold;
  }
</style>
  <div class="container">
    <div class="row">
      <div id="g">
      </div>
    </div>
  </div>

<script id="tpl" type="text/template">
  <% for(var i=0; i<data.length; i++) {%>
      <!--生成背景块元素--->
    <% for(var j=0; j< data[i].length; j++ ) { %>
      <div id="<%=i%><%=j%>" class="block" style="left:<%=util.getPost(j)%>;top:<%=util.getPost(i)%>" data-x="<%=j%>" data-y="<%=i%>" data-info='{"x":<%=[j]%>,"y":<%=[i]%>}'>
      </div>
    <% } %>
      <!--生成数字块元素--->
    <% for(var j=0; j< data[i].length; j++ ) { %>
      <!--如果数据模型里面的值为0,那么不显示这个数据的div--->
      <% if ( 0!==data[i][j] ) {%>
        <div id="num<%=i%><%=j%>" class="num-block" style="left:<%=util.getPost(j)%>;top:<%=util.getPost(i)%>" >
          <%=data[i][j]%>
        </div>
      <% } %>
    <% } %>
  <% } %>
</script>
<script>
  var Data = function() {
    this.init();
  };
  $.extend(Data.prototype, {
    /**
     * @desc 构造函数初始化
     * */
    init : function() {
      this.generateData();
    },
    /**
     * @desc 生成了默认的数据地图
     * @param void
     * */
    generateData : function() {
      var data = [];
      for(var i=0; i<4; i++) {
        data[i] = data[i] || [];
        for(var j=0; j<4; j++) {
          data[i][j] = 0;
        };
      };
      this.map = data;
    },
    /**
     * @desc 随机一个block填充到数据里面
     * @return void
     * */
    generationBlock : function() {
      var data = this.getRandom();
      var position = this.getPosition();
      this.set( position.x, position.y, data)
    },
    /**
     * @desc 获取随机数 2 或者是 4
     * @return 2 || 4;
     * */
    getRandom : function() {
      return Math.random()>0.5 &#63; 2 : 4;
    },
    /**
     * @desc 获取data里面数据内容为空的位置
     * @return {x:number, y:number}
     * */
    getPosition : function() {
      var data = this.map;
      var arr = [];
      for(var i=0; i<data.length; i++ ) {
        for(var j=0; j< data[i].length; j++ ) {
          if( data[i][j] === 0) {
            arr.push({x:j, y:i});
          };
        };
      };
      return arr[ Math.floor( Math.random()*arr.length ) ];
    },
    /**
     * @desc 把数据里第y排, 第x列的设置, 默认为0, 也可以传值;
     * @param x, y
     * */
    set : function(x,y ,arg) {
      this.map[y][x] = arg || 0;
    },
    /**
     * @desc 在二维数组的区间中水平方向是否全部为0
     * @desc i明确了二维数组的位置, k为开始位置, j为结束为止
     * */
    no_block_horizontal: function(i, k, j) {
      k++;
      for( ;k<j; k++) {
        if(this.map[i][k] !== 0)
        return false;
      };
      return true;
    },
    //和上面一个方法一样,检测的方向是竖排;
    no_block_vertical : function(i, k, j) {
      var data = this.map;
      k++;
      for(; k<j; k++) {
        if(data[k][i] !== 0) {
          return false;
        };
      };
      return true;
    },
    /**
     * @desc 往左边移动
     * */
    moveLeft : function() {
      /*
      * 往左边移动;
      * 从上到下, 从左到右, 循环;
      * 从0开始继续循环到当前的元素 ,如果左侧的是0,而且之间的空格全部为0 , 那么往这边移,
      * 如果左边的和当前的值一样, 而且之间的空格值全部为0, 就把当前的值和最左边的值相加,赋值给最左边的值;
      * */
      var data = this.map;
      var result = [];
      for(var i=0; i<data.length; i++ ) {
        for(var j=1; j<data[i].length; j++) {
          if (data[i][j] != 0) {
            for (var k = 0; k < j; k++) {
              //当前的是data[i][j], 如果最左边的是0, 而且之间的全部是0
              if (data[i][k] === 0 && this.no_block_horizontal(i, k, j)) {
                result.push( {form : {y:i,x:j}, to :{y:i,x:k}} );
                data[i][k] = data[i][j];
                data[i][j] = 0;
                //加了continue是因为,当前的元素已经移动到了初始的位置,之间的循环我们根本不需要走了
                break;
              }else if(data[i][j]!==0 && data[i][j] === data[i][k] && this.no_block_horizontal(i, k, j)){
                result.push( {form : {y:i,x:j}, to :{y:i,x:k}} );
                data[i][k] += data[i][j];
                data[i][j] = 0;
                break;
              };
            };
          };
        };
      };
      return result;
    },
    moveRight : function() {
      var result = [];
      var data = this.map;
      for(var i=0; i<data.length; i++ ) {
        for(var j=data[i].length-2; j>=0; j--) {
          if (data[i][j] != 0) {
            for (var k = data[i].length-1; k>j; k--) {
              //当前的是data[i][j], 如果最左边的是0, 而且之间的全部是0
              if (data[i][k] === 0 && this.no_block_horizontal(i, k, j)) {
                result.push( {form : {y:i,x:j}, to :{y:i,x:k}} );
                data[i][k] = data[i][j];
                data[i][j] = 0;
                break;
              }else if(data[i][k]!==0 && data[i][j] === data[i][k] && this.no_block_horizontal(i, j, k)){
                result.push( {form : {y:i,x:j}, to :{y:i,x:k}} );
                data[i][k] += data[i][j];
                data[i][j] = 0;
                break;
              };
            };
          };
        };
      };
      return result;
    },
    moveUp : function() {
      var data = this.map;
      var result = [];
      // 循环要检测的长度
      for(var i=0; i<data[0].length; i++ ) {
        // 循环要检测的高度
        for(var j=1; j<data.length; j++) {
          if (data[j][i] != 0) {
            //x是确定的, 循环y方向;
            for (var k = 0; k<j ; k++) {
              //当前的是data[j][i], 如果最上面的是0, 而且之间的全部是0
              if (data[k][i] === 0 && this.no_block_vertical(i, k, j)) {
                result.push( {form : {y:j,x:i}, to :{y:k,x:i}} );
                data[k][i] = data[j][i];
                data[j][i] = 0;
                break;
              }else if(data[j][i]!==0 && data[k][i] === data[j][i] && this.no_block_vertical(i, k, j)){
                result.push( {form : {y:j,x:i}, to :{y:k,x:i}} );
                data[k][i] += data[j][i];
                data[j][i] = 0;
                break;
              };
            };
          };
        };
      };
      return result;
    },
    moveDown : function() {
      var data = this.map;
      var result = [];
      // 循环要检测的长度
      for(var i=0; i<data[0].length; i++ ) {
        // 循环要检测的高度
        for(var j=data.length - 1; j>=0 ; j--) {
          if (data[j][i] != 0) {
            //x是确定的, 循环y方向;
            for (var k = data.length-1; k>j ; k--) {
              if (data[k][i] === 0 && this.no_block_vertical(i, k, j)) {
                result.push( {form : {y:j,x:i}, to :{y:k,x:i}} );
                data[k][i] = data[j][i];
                data[j][i] = 0;
                break;
              }else if(data[k][i]!==0 && data[k][i] === data[j][i] && this.no_block_vertical(i, j, k)){
                result.push( {form : {y:j,x:i}, to :{y:k,x:i}} );
                data[k][i] += data[j][i];
                data[j][i] = 0;
                break;
              };
            };
          };
        };
      };
      return result;
    }
   });
  var util = {
    animateShowBlock : function() {
      setTimeout(function() {
        this.renderHTML();
      }.bind(this),200);
    },
    animateMoveBlock : function(prop) {
      $("#num"+prop.form.y+""+prop.form.x).animate({top:40*prop.to.y,left:40*prop.to.x},200);
    },
    //底线库的模板中引用了这个方法;
    getPost : function(num) {
      return num*40 + "px";
    }
    //这个应该算是服务;
  };
  var View = function(data) {
    this.data = data.data;
    this.el = data.el;
    this.renderHTML();
    this.init();
  };
  $.extend(View.prototype, {
    renderHTML : function() {
      var str = _.template( document.getElementById("tpl").innerHTML )( {data : this.data.map} );
      this.el.innerHTML = str;
    },
    init : function() {
      this.bindEvents();
    },
    bindEvents : function() {
      $(document).keydown(function(ev){
        var animationArray = [];
        switch(ev.keyCode) {
          case 37:
            animationArray = this.data.moveLeft();
            break;
          case 38 :
            animationArray = this.data.moveUp();
            break;
          case 39 :
            animationArray = this.data.moveRight();
            break;
          case 40 :
            animationArray = this.data.moveDown();
            break;
        };
        if( animationArray ) {
          for(var i=0; i<animationArray.length; i++ ) {
            var prop = animationArray[i];
            this.animateMoveBlock(prop);
          };
        };
        this.data.generationBlock();
        this.animateShowBlock();
      }.bind(this));
    }
  });

  $(function() {
    var data = new Data();
    //随机生成两个节点;
    data.generationBlock();
    data.generationBlock();
    //生成视图
    var view = new View({ data :data, el : document.getElementById("g") });
    //继承工具方法, 主要是动画效果的继承;
    $.extend( true, view, util );
    //显示界面
    view.renderHTML();
  });
</script>
</body>
</html>

The above is the entire content of this article, I hope you all like it.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment