Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <table>
  <tr>
    <th></th>
    <th><input type="button" value="up"></th>
    <th></th>
  </tr>
  <tr>
    <th><input type="button" value="left"></th>
    <th><table>
      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </table></th>
    <th><input type="button" value="right"></th>
  </tr>
  <tr>
    <th></th>
    <th><input type="button" value="down"></th>
    <th></th>
  </tr>
</table>
<pre></pre>
<p>This is my 2048 game implementation in <span></span>JavaScript (see JS pane).</p>
<p>
To simplify things, I employ a linear array of whole numbers (exponents of two) to represent the game grid. For easy "falling" and "merging", I freely transform this into a 2-dimensional array as a traditional "table" or its row-column flipped "pivot". The "Falling" effect is achieved by dropping all the zero values, then right-padding it to its original length. "Merging" adjacent non-zero values is accomplished by incrementing one value and zeroing out the other, then simply "falling" again. The visible powers of two are actually just some css-injected content. With each "render" invocation, the game grid's internal representation is displayed in the console.
</p>
<p>
  The game ends when no zero values remain. You win if the max (exponent of two) value is greater than 10 (namely, "2048").
</p>
<p>Enjoy.</p>
              
            
!

CSS

              
                * {
  font-family: Arial;
}
td,
input {
  border: dotted silver 1px;
  width: 3em;
  height: 3em;
  text-align: center;
}
th > input {
  color: black;
}
td {
  color: white;
}
input.disabled {
  color: white;
}
td.n0::before {
  content: "1";
}
td.n1::before {
  content: "2";
}
td.n2::before {
  content: "4";
}
td.n3::before {
  content: "8";
}
td.n4::before {
  content: "16";
}
td.n5::before {
  content: "32";
}
td.n6::before {
  content: "64";
}
td.n7::before {
  content: "128";
}
td.n8::before {
  content: "256";
}
td.n9::before {
  content: "512";
}
td.p1::after {
  content: "K";
}
td.p2::after {
  content: "M";
}
td.p3::after {
  content: "G";
}
td.p4::after {
  content: "T";
}
td.p5::after {
  content: "P";
}
td.p6::after {
  content: "E";
}
td.p7::after {
  content: "Z";
}
td.p8::after {
  content: "Y";
}
td.n0 {
  background-color: silver;
}
td.n1 {
  background-color: red;
}
td.n2 {
  background-color: green;
}
td.n3 {
  background-color: gold;
}
td.n4 {
  background-color: blue;
}
td.n5 {
  background-color: magenta;
}
td.n6 {
  background-color: tan;
}
td.n7 {
  background-color: brown;
}
td.n8 {
  background-color: black;
}
td.n9 {
  background-color: cyan;
}

              
            
!

JS

              
                $(function game() {
  function feedback(...message) {
    $("pre").text(message.join("\n"));
  }
  function linear(...x) { // accepts numeric params, a linear array or 2-dimensional array
    var a = String(x).match(/\d+/g);
    a = a ? a.map(Number) : []; // linear array of whole numbers (non-negative integers)
    return a;
  }
  function pad(n, ...x) { // n establishes the desired (minimum) array length
    var a = linear(x);
    while (a.length < n) a.push(0); // pad with trailing (not leading!) zeroes
    return a;
  }
  function etc(n, ...x) { // extends array to n elements with incrementing values
    var a = linear(x);
    if (arguments.length)
      if (a.length) while (a.length < n) a.push(a[a.length - 1] + 1);
      // pad with ascending values
      else return etc(n, 0);
    return a;
  }
  function table(...x) {  // traditional table as a 2-dimensional array (outer array of rows)
    var a = linear(x);
    var e = Math.round(Math.sqrt(a.length));
    a = a.reduce(function (b, v, i) {
      var n = Math.floor(i / e); // n (row number) increases slowly
      if (n == b.length) b.push([]);
      b[n].push(v);
      return b;
    }, []); // for array.reduce, the accumulator can be another array!
    // console.log("table:", a);
    return a;
  }
  function pivot(...x) {  // pivot transform as a 2-dimensional array (outer array of columns)
    var a = linear(x);
    var e = Math.round(Math.sqrt(a.length));
    a = a.reduce(function (b, v, i) {
      var n = i % e; // n (column number) cycles quickly
      if (n == b.length) b.push([]);
      b[n].push(v);
      return b;
    }, []); // thankfully, this pivot transform is reflexive (like negation or array.reverse).
    // console.log("pivot:", a);
    return a;
  }
  function fall(...x) { // non-zero values "fall" to the bottom of the given array
    var a = linear(x);
    var n = a.length;
    return pad(n, a.filter(Boolean)); // drop every zero, pad out to original length
  }
  function merge(...x) { // after falling, pairs of like-valued neighbors merge together
    var a = fall(x);
    for (var i = 1; i < a.length; i++)
      if (a[i] && a[i] == a[i - 1]) {
        a[i] = 0;
        a[i - 1]++; // same neighbors merged and incremented
      }
    return fall(a);
  }
  function rand(n) {
    return Math.floor(Math.random() * n); // 0 to n-1
  }
  function seed(n, ...x) {  // adds n seed values (or maybe less, when full)
    var a = linear(x);
    var z = a.reduce(function (z, v, i) {
      if (!v) z.push(i);
      return z;
    }, []); // indices of zero values
    for (var i = n; i && z.length; i--) {
      var j = z.splice(rand(z.length), 1)[0];
      a[j] = rand(10) < 9 ? 1 : 2; // "2" or "4" seed value (per game rules)
    }
    // console.log("seed:", a);
    return table(a);
  }
  function changed(...x) {
    if (changed.snapshot) {
      var result = changed.snapshot != String(linear(x));
      // if (result)
      //   console.log(changed.snapshot + " is now " + String(linear(x)));
      // else console.log(changed.snapshot + " remains the same.");
      changed.snapshot = false;
      return result;
    } else {
      changed.snapshot = String(linear(x));
      // console.log("recording... " + changed.snapshot);
      return changed.snapshot;
    }
  }
  var swipe = {
    left: function lf(q, ...x) {  // sliding left is rather intuitive...
      changed(x);
      var a = table(x).map(function (v) {
        return merge(v);
      });
      console.log("left:", a);
      if (changed(a)) a = seed(q, a);
      else feedback("(already full)");
      return a;
    },
    right: function rt(q, ...x) {  // sliding right requires a double-reverse on each row...
      changed(x);
      var a = table(x).map(function (v) {
        return merge(v.reverse()).reverse();
      });
      console.log("right:", a);
      if (changed(a)) a = seed(q, a);
      else feedback("(already full)");
      return a;
    },
    up: function up(q, ...x) {   // sliding up requires a double-pivot to act upon each column...
      changed(x);
      var a = pivot(
        pivot(x).map(function (v) {
          return merge(v);
        })
      );
      console.log("up:", a);
      if (changed(a)) a = seed(q, a);
      else feedback("(already full)");
      return a;
    },
    down: function dn(q, ...x) {   // sliding down requires a double-reverse and a double-pivot...
      changed(x);
      var a = pivot(
        pivot(x).map(function (v) {
          return merge(v.reverse()).reverse();
        })
      );
      console.log("down:", a);
      if (changed(a)) a = seed(q, a);
      else feedback("(already full)");
      return a;
    }
  };
  function style(n) {   // Those powers of two are nowhere in the page code! (see CSS pane)
    var N = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512];
    var P = " KMGTPEZY".split("");
    var p = 0;
    for (var x = n; x > 9; x -= 10) p++;
    // console.log('2 ^ '+n+' = '+N[n % 10]+P[p]);
    return n ? `n${n % 10} p${p}` : ``; // ECMA6 does some cool micro-templating!
  }
  var grid = seed(2, pad(16)); // The grid starts with 16 zero values, and exactly two seed values.
  function gameover(...x) {  // FIXME: Merging may still be possible, even when the board is full.
    var a = linear(x);
    var messages = [];
    var max = Math.max.apply(this, a);
    messages.push(`${(max - 1) * 10}% done! `);
    if (a.indexOf(0) < 0) messages.push("Game over"); // Board is full (no zero values remain).
    if (max > 10) messages.push("You win!"); // High value is "2048" (or more).
    feedback.apply(0, messages);
  }
  function render(...x) { // Using jQuery to apply some CSS tricks (see "style" function above)...
    var a = linear(x);
    // console.log(a);
    $("td")
      .removeClass(
        "n0 n1 n2 n3 n4 n5 n6 n7 n8 n9 p0 p1 p2 p3 p4 p5 p6 p7 p8 p9"
      )
      .each(function (i) {
        $(this).addClass(style(a[i]));
      });
    console.log(table(a)); // to understand what's happening, look in the console... (you're welcome)
    // choices(1, a);
    gameover(a);
  }
  render(grid); // and renders it.
  function button() {
    console.clear();
    var f = $(this).val(); // This handler uses the button text...
    grid = swipe[f](1, grid); // to invoke the selected action
    render(grid);
  }
  $("input:button").click(button); // Installs the button handler.
  $("span").text(
    `just ${String(game).split(/\n/g).length} lines of commented `
  );
});

              
            
!
999px

Console