JS Write 2048 game code

Source: Internet
Author: User
Tags new set

<! DOCTYPE html>

*{margin:0;padding:0;} Body{text-align:center;font-size:20px;font-family: "Microsoft Jas Black";} Button{width:60px;height:30px;background: #222; Text-align:center;line-height:30px;color: #fff; border:none; Font-size:18px;margin-top:10px;outline:none;border-radius:5px;cursor:pointer;} button:active{opacity:0.8;}. C{width:400px;height:400px;background: #eee; margin:0 auto;position:relative;}. block{width:100px;height:100px;border-radius:3px;position:absolute;text-align:center;line-height:100px; Font-size:40px;color: #fff;}. Block.b2{background: #21adbe;}. Block.b4{background: #3706ef;}. Block.b8{background: #06e1ef;}. Block.b16{background: #05795c;}. Block.b32{background: #08b028;}. Block.b64{background: #8af027;}. Block.b128{background: #ccf027;}. Block.b256{background: #f0b027;}. Block.b512{background: #f06e27;}. Block.b1024{background: #f027b5;}. Block.b2048{background: #f02743;}

/** * 2017.6.9-2017.6.15 * * (function (win,doc,$,undefined) {var G2048 = function (DOM) {THIS.C = $ (DOM); this.autor= " Lianxiaozhuang "; this.method=" sets the tag for each piece of the box, such as position 00,01,02 .... Move the direction key by line (or column) to move the block (the superposition of the number of implementations) "This.arr = [" 2 "," 4 "," 8 ", "+", "a", "" "," "" "," "", "" "," "", "" "," "2048"];this.arrclassname = ["B2", "B4", "B8", "B16", "B32", "b64", "b128", " B256 "," b512 "," b1024 "," b2048 "];this.b_width = 100;//block width. Consistent with CSS This.maxnum = 16;//box holds up to the number of squares This.initnum = 2;//initialization in number this.end = false;//End flag This.timer = null;// After moving delay add block this.arrcoreadd ();//ie8 add IndexOf Method This.init ();} G2048.prototype = {constructor:g2048,init:function () {var _this = This;while (_this.initnum>0) {//Initialize (throw a few initial blocks into the box) _ This.initnum--;_this.radomcreateblock ();} Doc.onkeydown = function (evt) {//keyboard if (!_this.end) {//End flag _this.keyboardevent (Win.event | | evt);//Keyboard Event Cleartimeout (_ This.timer) _this.timer = SetTimeout (function () {_this.radomcreateblock ();//Add a piece of},300)}}},arrcoreadd:function () {/ /solve IE8 under array without indexof () method error if (! ARRAY.PROTOTYPE.INDEXOF) {Array.protOtype.indexof = function (ELT/*, from*/) {var len = this.length >>> 0; var from = number (Arguments[1]) | |    0; From = (from < 0)?    Math.ceil (from): Math.floor (from);    if (from < 0) from + = Len;    for (; from < Len; from++) {if (from the this &&this[from] = = = ELT) return from;  } return-1; };}},radomcreateblock:function () {///randomly generate a piece put into box var _this = This;var C_width = _this.c.width (); var c_top = This.c.offset () . Top,c_left = This.c.offset (). Left;var bl = ' <div class= ' set block B2 ' > ' +_this.arr[0]+ ' </div> '; _ This.c.append ($ (BL). css ({"Visibility": "Hidden"});//Do not display first, then determine if the var is coincident $set = $ (". Set"), if ($ (". Ready"). Length==_ This.maxnum) {//Full _this.end = True;alert ("Game over!");} if (!_this.end) {do{//sets the random position until appropriate $set.offset ({"Top": C_top+parseint (Math.random ()) *_this.b_width, "left": C_left +parseint (Math.random ()) *_this.b_width})}while (_this.checklap (). Lap)//position not appropriate false when executing the DO statement}_this.setmark ($set );//Set tag $set.css ({"Visibility": "VisiblE "}). Removeclass (" Set "). AddClass (" Ready ");//Display},checklap:function () {//monitor this time for exceeding or coincident var _this = This;var lap = false;/ /non-coincident flag var s_top = $ (". Set"). Offset (). Top,s_left = $ (". Set"). Offset (). Left;_this.c.find (". Ready"). index,element) {var r_top = $ (Element). Offset (). Top,r_left = $ (Element). Offset (). Left;if (R_top-s_top==0&&r_ left-s_left==0) {lap = true;//coincident return false;}}) Return{lap:lap}},moveblock:function (dir) {//mobile var _this = This;var C_top = This.c.offset (). Top,c_left = This.c.offset () . left;if (dir== "left") {/////////////////////////for (var loop=0;loop<=3;loop++) {//Loop four times (because one is not moved by a directional key block One Direction can be moved up to four times to ensure that this direction can no longer be moved) for (Var i=0;i<=3;i++) {//row var II = i.tostring ();//to String for (j=1;j<=3;j++) {//column (left to right) var JJ = J.tostring (); var jj_next = (j-1). toString ();//The number of columns on the left side of the current block var $now = $ ('. ready[mark= ' ' +ii+jj+ ' "] ');//Current Var $now _ Next = $ ('. ready[mark= ' ' +ii+jj_next+ ' "]);//the current block on the left of the IF ($now. length!=0) {//traverse the current position exists var $now _left = $now. Offset (). if ($now _next.length!=0) {//The left of the current block is not a blank bit if ($Now.text () = = $now _next.text ()) {//two block values are equal, overlap and Sum $now_next.remove ();//Remove overlapping blocks (one of them) var $text = $now. Text (); var $index = _ This.arr.indexOf ($text);//The value of the current move block is $now.offset ({"Left": $now _left-100}) in the array's subscript. Text (_this.arr[$index +1]). Removeclass (_this.arrclassname[$index]). addclass (_this.arrclassname[$index +1]);//value change and change class name}}else{// The left side of the current block is a blank $now.offset ({"Ieft": $now _left-100})}_this.setmark ($now);//current block from the new setting tag}}}}}else if (dir== "right") {//////// for (Var loop=0;loop<=3;loop++) {//Loop four (because each key block is moved one step at a time, One direction can be moved up to four times to ensure that this direction can no longer be moved) for (Var i=0;i<=3;i++ ) {//row var II = i.tostring ();//Number of strings for (j=2;j>=0;j--) {//Columns (right-to-left) var JJ = j.tostring ();//Convert to string var Jj_next = (j+1). ToString ();//The right side of the current block is the column var $now = $ ('. ready[mark= ' ' +ii+jj+ ' "]);//Current var $now _next = $ ('. ready[mark= ' +ii+jj_next+ "]);//The right piece of the current block if ($now. length!=0) {//traverse the current position exists var $now _left = $now. Offset (). Left;if ($now _next.length!=0) {// The right side of the current block is not a blank bit if ($now. Text () = = $now _next.text ()) {//two block values are equal, overlapping and summing $now_next.removeclass ("ready"). Hide (). remove (); Remove overlapping blocks (one of them)var $text = $now. Text (), var $index = _this.arr.indexof ($text);//The value of the currently moving block is $now.offset ({"Left": $now _left+100}) in the array. Text (_this.arr[$index +1]). Removeclass (_this.arrclassname[$index]). addclass (_this.arrclassname[$index +1]);// Change the value and replace the class name}}else{//the right side of the current block is a blank $now.offset ({"Left": $now _left+100})}_this.setmark ($now);//current block new set tag}}}}}else if (dir== "Up") {///////////////////for (var loop=0;loop<=3;loop++) {//Cycle four times (because each key block is moved one step at a time, One direction can be moved up to four times to ensure that this direction can no longer be moved) for (Var j=0 ; j<=3;j++) {//column var JJ = j.tostring ();//Number of strings for (i=1;i<=3;i++) {//rows (top to bottom) var II = i.tostring ();//Convert to string var ii_next = (i-1). toString ();//The upper section of the current block is the row var $now = $ ('. ready[mark= "' +ii+jj+ '"]);//Current var $now _next = $ ('. ready[mark= ' +ii_ Next+jj+ ' "]);//the piece of the current block if ($now. length!=0) {//traverse the current position exists var $now _top = $now. Offset (). Top;if ($now _next.length!=0) {// The top of the current block is not a blank bit if ($now. Text () = = $now _next.text ()) {//two block values are equal, overlap and Sum $now_next.remove ();//Remove overlapping blocks (one of them) var $text = $now. Text ( var $index = _this.arr.indexof ($text);//The value of the current move block is $now.offset ({"Top": $now _top-100}). Text (_this.arr[$index +1]). Removeclass (_this.arrclassname[$index]). addclass (_this.arrclassname[$index +1]); /value change, and replace the class name}}else{//the top of the current block is a blank $now.offset ({"Top": $now _top-100})}_this.setmark ($now);//current block from the new set tag}}}}}else if ( dir== "Down") {///////////////////for (var loop=0;loop<=3;loop++) {//Loop four times (because each keystroke block moves one step at a time, Move up to four times in one direction to ensure that this direction can no longer be moved) for (Var j=0;j<=3;j++) {//column var JJ = j.tostring ();//Number of strings for (i=2;i>=0;i--) {//rows (bottom to top) Var II  = i.ToString ();//Convert to string var Ii_next = (i+1). toString ();//The line under the current block var $now = $ ('. ready[mark= ' ' +ii+jj+ ' "]);//Current Var $now _next = $ ('. ready[mark= "' +ii_next+jj+ '"]);//The block below the current chunk if ($now. length!=0) {//traverse the current position exists var $now _top = $now. Offset (). Top;if ($now _next.length!=0) {///the bottom of the current block is not a blank bit if ($now. Text () = = $now _next.text ()) {//two block values are equal; overlap and Sum $now_next.remove ();// Remove overlapping blocks (one of them) var $text = $now. Text (); var $index = _this.arr.indexof ($text);//The value of the current move block is $now.offset ({"Top": $now _top +100}). Text (_this.arr[$index +1]). Removeclass (_this.arrclassname[$index]). addclass (_this.arrclassname[$index +1] );Change the value and replace the class name}}else{//the top of the current block is a blank $now.offset ({"Top": $now _top+100})}_this.setmark ($now);//the current block from the new set Tag}}}}, Setmark:function (DOM) {//traverse each piece; set tag (corresponding to the row and column of the position) var c_top = This.c.offset (). Top,c_left = This.c.offset (). Left;var $left = Dom.offset (). Left, $top = Dom.offset (). Top;var Left_mark = Math.Round (($left-c_left)/100). ToString (),// Add Math.Round () here to prevent IE parsing is not an integer and error Top_mark = Math.Round (($top-c_top)/100). ToString ();d om.attr ("Mark", Top_mark+left_    Mark);//For example, the first line of the first block is set to "XX"},keyboardevent:function (e) {///keyboard event var _this = This,_key = E.keycode | | e.which; switch (_key) {    Case 37://Left _this.moveblock    Case 38: The//Up key _this.moveblock ("up");    Case 39://_this.moveblock ("right");    Case 40: the//DOWN ARROW key _this.moveblock ("Down");  Case 13://Enter Break;case 32://Space break;default:break;} }}new G2048 (". C")} (Window,document,jquery))

JS Write 2048 game code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.