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 ? 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.

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
