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

              
                <h2>My 2048</h2>
<div id='msg-board'>
		<div id='msg'></div>
		<button id='resart-btn'>Restart</button>
</div>
<div id='boxContainer'>
		<div id='row0' class='row'>

		</div>
		<div id='row1' class='row'>

		</div>
		<div id='row2' class='row'>
		</div>
		<div id='row3' class='row'>

		</div>
</div>
              
            
!

CSS

              
                div {
		margin: 1px;
		padding-top: 1px;
		padding-left: 1px;
		padding-right: 1px;
		border-radius: 10px 10px 10px 10px;
		-moz-border-radius: 10px 10px 10px 10px;
		-webkit-border-radius: 10px 10px 10px 10px;
}

h2 {
		margin: 10px auto;
		text-align: center;
}

#msg-board {
		height: 50px;
		width: 280px;
		margin: 10px auto;
		text-align: center;
		line-height: 50px;
		background: #40DBE5;
}

#resart-btn {
		height: 50px;
		width: 280px;
		margin: 10px auto;
		line-height: 50px;
		background: #40DBE5;
}

div div {
		display: inline-block;
		text-align: center;
		line-height: 50px;
}

.left {
		float: left;
		margin: 3px;
}

.nleft {
		float: right;
		margin: 3px;
}

#boxContainer {
		height: 295px;
		width: 280px;
		margin: 100px auto;
		background: #BEAEA1;
}

.c2048 {
		height: 60px;
		width: 60px;
		background: #D8A20D;
}

.c1024 {
		height: 60px;
		width: 60px;
		background: #E7B812;
}

.c516 {
		height: 60px;
		width: 60px;
		background: #EFD14D;
}

.c256 {
		height: 60px;
		width: 60px;
		background: #EFD14D;
}

.c128 {
		height: 60px;
		width: 60px;
		background: #E75A3C;
}

.c64 {
		height: 60px;
		width: 60px;
		background: #E75A3C;
}

.c32 {
		height: 60px;
		width: 60px;
		background: #F17F5D;
}

.c16 {
		height: 60px;
		width: 60px;
		background: #ED8D5D;
}

.c8 {
		height: 60px;
		width: 60px;
		background: #EFB279;
}

.c4 {
		height: 60px;
		width: 60px;
		background: #EEDFCA;
}

.c2 {
		height: 60px;
		width: 60px;
		background: #EEE4DA;
}

.e {
		height: 60px;
		width: 60px;
		background: #CCC0B4;
}
              
            
!

JS

              
                (function() {
		var My2048 = {
				stepCount: 0,
				restartBtn: "resart-btn",
				msgEle: "msg",
				numberboxs: {},
				emptyboxIds: [],
				init: function() {
						//init step count
						this.updateMsg("Step Count: " + this.stepCount);
						// init restart button
						document.getElementById(this.restartBtn).removeEventListener('click', this.restart(), false);
						document.getElementById(this.restartBtn).addEventListener('click', this.restart(), false);
						// init number boxes
						for (var x = 0; x < 4; x++) {
								for (var y = 0; y < 4; y++) {
										this.numberBoxFactory('row' + x, "", "e left", x, y, "");
								}
						}
						this.generateBox(2, 2);
				},
				restart: function() {
						var that = this;
						return function() {
								//clearing work
								that.stepCount = 0;
								that.emptyboxIds = [];
								for (var key in that.numberboxs) {
										var box = that.numberboxs[key]['ele'];
										box.parentElement.removeChild(box);
								}
								that.numberboxs = {};
								// app init
								console.log(that);
								that.init();
						}

				},
				moveUp: function() {
						var columnData = this.arrayDataByColumn();
						// console.log('before up'+columnData);
						//console.log(columnData);
						for (var key in columnData) {
								var columnArray = columnData[key];
								var columnArrayPost = this.doMovingLogic(columnArray);
								columnData[key] = columnArrayPost;
								for (var k in columnData[key]) {
										//find correspondent Ele And update view
										var box = this.numberboxs[k + '_' + key]['ele'];
										this.updateNumbox(box, columnData[key][k]);
								}

						}
						this.afterMove();
				},
				moveDown: function() {
						var columnData = this.arrayDataByColumn();
						for (var key in columnData) {
								var columnArray = columnData[key];
								var columnArrayPost = this.doMovingLogic(columnArray.reverse());
								columnData[key] = columnArrayPost.reverse();
								for (var k in columnData[key]) {
										//find correspondent Ele And update view
										var box = this.numberboxs[k + '_' + key]['ele'];

										this.updateNumbox(box, columnData[key][k]);
								}

						}
						this.afterMove();

				},
				moveLeft: function() {
						var rowData = this.arrayDataByRow();
						// console.log(rowData);
						for (var key in rowData) {
								var rowArray = rowData[key];
								var rowArrayPost = this.doMovingLogic(rowArray);
								rowData[key] = rowArrayPost;

								for (var k in rowArrayPost) {
										//find correspondent Ele And update view

										var box = this.numberboxs[key + '_' + k]['ele'];

										this.updateNumbox(box, rowData[key][k]);
								}
						}
						this.afterMove();
						// console.log(rowData);
				},
				moveRight: function() {
						var rowData = this.arrayDataByRow();
						//console.log(rowData);
						for (var key in rowData) {
								var rowArray = rowData[key];
								var rowArrayPost = this.doMovingLogic(rowArray.reverse());
								rowData[key] = rowArrayPost.reverse();

								for (var k in rowData[key]) {
										//find correspondent Ele And update view

										var box = this.numberboxs[key + '_' + k]['ele'];

										this.updateNumbox(box, rowData[key][k]);
								}
						}
						//console.log(rowData);
						this.afterMove();
				},
				afterMove: function() {
						// check if sucess OR fail
						var status = this.checkGameStatus();
						if (status != 'continue') {
								return;
						}
						// update step count
						this.stepCount += 1;
						this.updateMsg("Step Count: " + this.stepCount);
						//getEmptybox object length
						var emptyboxIdsLength = this.emptyboxIds.length;
						// randomly add 2 box Or 4 box, if empty box is less then expected 
						var guess = parseInt((Math.random() * 100).toFixed(0)) % 3;

						if (!guess) {
								if (emptyboxIdsLength < 1) return;
								this.generateBox(2, 1)
						} else if (guess == 1) {
								if (emptyboxIdsLength < 2) return;
								this.generateBox(2, 2)
						} else {
								if (emptyboxIdsLength < 1) return;
								this.generateBox(4, 1);
						}

				},
				checkGameStatus: function() {
						// check every box in numberboxs, if there is 2048 box, game succeed
						for (var key in this.numberboxs) {
								var box = this.numberboxs[key];
								var name = box['name'];
								if (name == 2048) {
										this.updateMsg("You Are Awesome!!!");
										return 'success';
								}
						}
						// if not success check if failed by row and column
						var canMove = false;
						// by row
						var rowData = this.arrayDataByRow();
						for (var i = 0; i < rowData.length; i++) {
								var rowArray = rowData[i];
								// use doMovingLogic function to check
								var pRowArray = this.doMovingLogic(rowArray);
								for (var y = 0; y < rowArray.length; y++) {
										if (rowArray[y] != pRowArray[y]) {
												canMove = true;
										}
								}
						}
						// by row reverse
						var rowDataReverse = this.arrayDataByRow();
						for (var i = 0; i < rowDataReverse.length; i++) {
								var rowArray = rowDataReverse[i].reverse();
								// use doMovingLogic function to check
								var pRowArray = this.doMovingLogic(rowArray.slice(0));
								for (var y = 0; y < rowArray.length; y++) {
										if (rowArray[y] != pRowArray[y]) {
												canMove = true;
										}
								}
						}
						//by column
						var columnData = this.arrayDataByColumn();
						for (var i = 0; i < columnData.length; i++) {
								var columnArray = columnData[i];
								var pcolumnArray = this.doMovingLogic(rowArray);
								for (var y = 0; y < columnArray.length; y++) {
										if (columnArray[y] != pcolumnArray[y]) {
												canMove = true;
										}
								}
						}
						// by column reverse
						var columnDataReverse = this.arrayDataByColumn();
						for (var i = 0; i < columnDataReverse.length; i++) {
								var columnArray = columnDataReverse[i].reverse();
								var pcolumnArray = this.doMovingLogic(columnArray.slice(0));
								for (var y = 0; y < columnArray.length; y++) {
										if (columnArray[y] != pcolumnArray[y]) {
												canMove = true;
										}
								}
						}

						if (!canMove && this.emptyboxIds.length == 0) {
								this.updateMsg("Lack of a little luck, try again.");
								return 'failed';
						}
						// neither succeed or failed, then continue
						return 'continue';
				},
				updateMsg: function(msg) {
						var msgEle = document.getElementById(this.msgEle);
						msgEle.innerText = msg;
				},
				arrayDataByRow: function() {
						var rowObj = {};
						for (var key in this.numberboxs) {
								var boxObj = this.numberboxs[key];
								var rowIndex = boxObj['x'];
								rowObj[rowIndex] = [];
						}
						for (var key in this.numberboxs) {
								var boxObj = this.numberboxs[key];
								var rowIndex = boxObj['x'];
								var boxSeq = boxObj['y'];
								for (var k in rowObj) {
										if (rowIndex == k) {
												rowObj[k][boxSeq] = boxObj['name'];
										}
								}
						}

						return rowObj;

				},
				arrayDataByColumn: function() {
						var columnObj = {};
						for (var key in this.numberboxs) {
								var boxObj = this.numberboxs[key];
								var columnIndex = boxObj['y'];
								columnObj[columnIndex] = [];
						}
						for (var key in this.numberboxs) {
								var boxObj = this.numberboxs[key];
								var columnIndex = boxObj['y'];
								var boxSeq = boxObj['x'];
								for (var k in columnObj) {
										if (columnIndex == k) {
												columnObj[k][boxSeq] = boxObj['name'];
										}
								}
						}
						return columnObj;
				},
				doMovingLogic: function(arr) {
						var pFirstHalf = [];
						var pSecdHalf = [];
						for (var i = 0; i < arr.length; i++) {
								if (arr[i] == 0) {
										pSecdHalf.push(arr[i]);
								} else {
										pFirstHalf.push(arr[i]);
								}
						}
						arr = pFirstHalf.concat(pSecdHalf);
						//var arr = [4,2,0,4];
						for (var i = 0; i < arr.length; i++) {
								if (arr[i] == arr[i + 1]) {
										arr[i + 1] = arr[i] * 2;
										arr[i] = 0;
								}
						}
						//console.log(arr);
						//arr = [4,2,0,]
						var firstHalf = [];
						var secdHalf = [];
						for (var i = 0; i < arr.length; i++) {
								if (arr[i] == 0) {
										secdHalf.push(arr[i]);
								} else {
										firstHalf.push(arr[i]);
								}
						}
						arr = firstHalf.concat(secdHalf);
						return arr;
				},
				generateBox: function(boxName, count) {
						for (var i = 0; i < count; i++) {
								var ph1 = Math.random() * this.emptyboxIds.length;
								var fEle = this.emptyboxIds[Math.floor(ph1)];
								this.updateNumbox(this.numberboxs[fEle].ele, boxName);

						}

				},
				updateNumbox: function(target, name) {
						var index = target.getAttribute('id');
						var className = target.getAttribute('class');
						className = "c" + name + " left";
						if (!name) {
								className = "e left";
								name = "";
						}
						target.setAttribute('name', name);
						target.setAttribute("class", className);
						target.innerText = name;
						//update related objects in numberboxs
						var targetObj = this.numberboxs[index];
						targetObj.name = name;
						targetObj.className = className;
						className.content = name;
						//if name is 0 then remove from emptyboxids
						//   console.log('box before:');
						//  console.log(this.emptyboxIds);
						if (name) {
								this.removeFromEmptyBox(index);
								//  console.log(this.emptyboxIds);
						}
						//	console.log(this.emptyboxIds);
						// add to emptyboxIds
						if (!name && this.emptyboxIds.indexOf(index) == -1) {
								this.emptyboxIds.push(index);
						}
						//    console.log('box after:');
						//  console.log(this.emptyboxIds);
				},
				removeFromEmptyBox: function(index) {
						var a = this.emptyboxIds.indexOf(index);
						if (a >= 0) {
								this.emptyboxIds.splice(a, 1);
								return true;
						}
						return false;
				},
				numberBoxFactory: function(parentEleId, name, className, x, y, content) {

						var index = x + "_" + y;
						var pEle = document.getElementById(parentEleId);
						var box = document.createElement("div");
						box.setAttribute('id', index);
						box.setAttribute('name', name);
						box.setAttribute("class", className);
						box.innerText = content;
						pEle.appendChild(box);

						var obj = {
								'id': x * y,
								'name': name,
								'className': className,
								'x': x,
								'y': y,
								'content': content,
								'ele': box
						}
						this.numberboxs[index] = obj;
						this.emptyboxIds.push(index);

				},
				run: function() {
						var self = this;
						//init 
						self.init();
						window.onkeydown = function(e) {
								//alert(e.keyCode);
								e && e.preventDefault();
								switch (e.keyCode) {
										case 37:
												self.moveLeft();
												break;
										case 38:
												self.moveUp();
												break;
										case 39:
												self.moveRight();
												break;
										case 40:
												self.moveDown();
												break;
								}

						};
				}
		}
		return window.My2048 = My2048;
})(window)

window.My2048.run();
              
            
!
999px

Console