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

              
                
<html>
	<head>
		<title>2048</title>
		<meta charset="utf-8" />
	</head>
	<body>
		<div id="goal"></div> <br/>
		<div id="moves"></div> <br/>
		<div id="score"></div> <br/> <br/>

	</body>
	
	<script src="game.js"></script>
</html>

              
            
!

CSS

              
                
              
            
!

JS

              
                

function Game(width, height){


	this.width = width;
	this.height = height;
	this.tileSize = 100;

	this.staticGrid = new Array(width*height);
	this.dynamicGrid = new Array(width*height);
	
	this.staticContainer = null;
	this.dynamicContainer = null;

	this.space = 15;

	this.won = false;
	this.moves = 0;
	this.movesHTMLElement = document.getElementById("moves");
	this.movesHTMLElement.style.textAlign = "center";
	this.movesHTMLElement.style.fontSize = "30px";
	this.movesHTMLElement.style.fontFamily = "Book Antiqua"; 
	this.movesHTMLElement.style.color = "blue";
	this.movesHTMLElement.style.fontWeight = "bold";

	



	//Ajout du nombre a atteindre
	this.goaL = prompt("Choose the number tile to reach");
	this.num = parseInt(this.goaL);
	this.goal = document.getElementById("goal");
	this.goal.style.margin = "auto";
	this.goal.style.textAlign = "center";
	this.goal.style.fontFamily = "sans-serif";
	this.goal.style.fontWeight = "bold";
	this.goal.style.fontSize = "50px";
	this.goal.style.color = "blue";
	this.goal.innerHTML = "Join the numbers and get to the " + this.num + " tile!";

	// Ajout du score dynamique
	this.scoreCourant = 0;
	this.scores = document.getElementById("score");
	this.scores.style.margin = "auto";
	this.scores.style.textAlign = "center";
	this.scores.style.fontFamily = "Palatino Linotype";
	this.scores.style.fontSize = "30px";
	this.scores.style.color = "red";

	


}

Game.prototype.setupHTML = function(){
	var w = this.width,
		h = this.height,
		tileSize = this.tileSize,
		space = this.space,
		sGrid = this.staticGrid,
		dGrid = this.dynamicGrid;

	var staticContainer = document.createElement("div");

	staticContainer.style.position = "absolute";
	staticContainer.style.margin = "auto";
	staticContainer.style.width = (w*tileSize + (space*w) +16) + "px"; //(w*tileSize + space*(w+1)) + "px";
	staticContainer.style.height = (h*tileSize + (space*h) +16) + "px";  //(h*tileSize + space*(h+1)) + "px";
	staticContainer.style.borderRadius = "20px";
	staticContainer.style.backgroundColor = "gray";
	this.staticContainer = staticContainer;
	staticContainer.style.left = "0";
	staticContainer.style.right = "0";
	

	var dynamicContainer = document.createElement("div");
	
	dynamicContainer.style.position = "absolute";
	dynamicContainer.style.margin = "auto";
	dynamicContainer.style.width = (w*tileSize + (space*w) +16) + "px";    //(w*tileSize + space*(w+1)) + "px";
	dynamicContainer.style.height = (h*tileSize + (space*h) +16) + "px";  // (h*tileSize + space*(h+1)) + "px";
	dynamicContainer.style.borderRadius = "20px";
	this.dynamicContainer = dynamicContainer;
	dynamicContainer.style.left = "0";
	dynamicContainer.style.right = "0";
	


	for(var x = 0; x < w; x++){
		for(var y = 0; y < h; y++){
			var div = document.createElement("div");
			div.style.position = "absolute";
			div.style.left = (x*tileSize + (x+1)*space) + "px";
			div.style.top = (y*tileSize + (y+1)*space) + "px";
			div.style.width = tileSize + "px";
			div.style.height = tileSize + "px";
			div.style.borderRadius = "20px";
			div.style.backgroundColor = "lightgray";
			staticContainer.appendChild(div);
			sGrid[x + y*w] = div;
		}
	}

	
	this.generateRandomTile();
	this.generateRandomTile();
	
	document.body.appendChild(staticContainer);
	document.body.appendChild(dynamicContainer);
}

Game.prototype.generateRandomTile = function(){
	var tileSize = this.tileSize,
		space = this.space,
		dGrid = this.dynamicGrid,
		w = this.width,
		h = this.height;
	
	var x = Math.round(Math.random()*(w-1)),
	   y = Math.round(Math.random()*(h-1));
	while(dGrid[x + y*w] !== undefined){
		x = Math.round(Math.random()*(w-1));
	   y = Math.round(Math.random()*(h-1));
	}
	var value = (Math.random() < 0.8) ? 2 : 4;
	var color = this.getColorByValue(value);
	
	var tile = document.createElement("div");
	tile.style.position = "absolute";
	tile.style.top = (y*tileSize + (y+1)*space) + "px";
	tile.style.left = (x*tileSize + (x+1)*space) + "px";
	tile.style.width = tileSize + "px";
	tile.style.height = tileSize + "px";
	tile.style.borderRadius = "20px";
	tile.style.backgroundColor = color;
	tile.style.color = "black";
	tile.style.textAlign = "center";
	tile.style.fontSize = "60px";
	tile.style.fontFamily = "Comic Sans MS";

	
	var text = document.createTextNode(value);
	tile.appendChild(text);
	
	dGrid[x + y*w] = { x : x, y : y, value : value, htmlElement : tile };

	this.dynamicContainer.appendChild(tile);
}

Game.prototype.isWinning = function(){
	var dGrid = this.dynamicGrid;
	for(var i = 0; i < dGrid.length; i++){
		var tile = dGrid[i];
		if(tile !== undefined){
			 if(tile.value === this.num)                          //change from 64
				return true;
		}
	}
	return false;
}

Game.prototype.update = function(){
	
	//Haut
	if(Input.isKeyPressed(38)){
		this.moveUp();
	}
	//Bas
	else if(Input.isKeyPressed(40)){
		this.moveDown();
	}
	//Droite
	if(Input.isKeyPressed(39)){
		this.moveRight();
	}
	//Gauche
	else if(Input.isKeyPressed(37)){
		this.moveLeft();
	}

	
	if(!this.won){
		if(this.isWinning()){
			this.won = true;
			var numero = this.num;
			window.setTimeout(function()
			{
				alert("YOU REACHED THE TILE " + numero + "\n" + "\n" + " !! Yoohoo !!");     // Alerte de victoire
			}, 500);
		}
	}

	Input.update();
	
}


Game.prototype.moveUp = function(){
	var dGrid = this.dynamicGrid,
		w = this.width,
		tileSize = this.tileSize,
		space = this.space;
	
	//Si des cases se sont déplacée, alors c'est true
	//Si c'est true, on génère une autre cases 2 ou 4 aléatoirement
	//Si aucune cases ne s'est déplacée, on ne génère rien
	var change = false;
	
	for(var xx = 0; xx < w; xx++){
		for(var yy = 0; yy < this.height; yy++){
			var tile = dGrid[xx + yy*w];
			if(tile !== undefined){
				for(var i = yy-1; i >= 0; i--){
					if(dGrid[xx + i*w] === undefined){
						dGrid[xx + (i+1)*w] = undefined;
						tile.y = i;
						change = true;
					}
					else {
						if(dGrid[xx + i*w].value === tile.value){
							tile.y = i;
							tile.value *= 2;
							dGrid[xx + (i+1)*w] = undefined;
							this.dynamicContainer.removeChild(dGrid[xx+i*w].htmlElement);
							change = true;

							                                                    // calcul du score dynamiquement
							this.scoreCourant += tile.value;
							this.scores.innerHTML = "Score = " + this.scoreCourant ;
						}
						break;
					}
				}
				
				dGrid[xx + tile.y*w] = tile;

			
				
				tile.htmlElement.style.top = (tile.y*tileSize + (tile.y+1)*space) + "px";
				tile.htmlElement.style.left = (xx*tileSize + (xx+1)*space) + "px";
				tile.htmlElement.style.backgroundColor = this.getColorByValue(tile.value);
				tile.htmlElement.childNodes[0].nodeValue = tile.value;
				

			}
		}
	}
	
	if(change){
		this.generateRandomTile();
		this.moves++;
		this.movesHTMLElement.innerHTML = "You made " + this.moves + " moves !";

	}
}

Game.prototype.moveDown = function(){
	var dGrid = this.dynamicGrid,
		w = this.width,
		tileSize = this.tileSize,
		space = this.space;
	
	//Si des cases se sont déplacée, alors c'est true
	//Si c'est true, on génère une autre cases 2 ou 4 aléatoirement
	//Si aucune cases ne s'est déplacée, on ne génère rien
	var change = false;
	
	for(var xx = 0; xx < w; xx++){
		for(var yy = this.height-1; yy >= 0; yy--){
			var tile = dGrid[xx + yy*w];
			if(tile !== undefined){
				for(var i = yy+1; i < this.height; i++){
					if(dGrid[xx + i*w] === undefined){
						dGrid[xx + (i-1)*w] = undefined;
						tile.y = i;
						change = true;
					}
					else {
						if(dGrid[xx + i*w].value === tile.value){
							tile.y = i;
							tile.value *= 2;
							dGrid[xx + (i-1)*w] = undefined;
							this.dynamicContainer.removeChild(dGrid[xx+i*w].htmlElement);
							change = true;

							                                                     // calcul du score dynamiquement
							this.scoreCourant += tile.value;
							this.scores.innerHTML = "Score = " + this.scoreCourant ;
						}
						break;
					}
				}
				
				dGrid[xx + tile.y*w] = tile;
				
				tile.htmlElement.style.top = (tile.y*tileSize + (tile.y+1)*space) + "px";
				tile.htmlElement.style.left = (xx*tileSize + (xx+1)*space) + "px";
				tile.htmlElement.style.backgroundColor = this.getColorByValue(tile.value);
				tile.htmlElement.childNodes[0].nodeValue = tile.value;
			}
		}
	}
	
	if(change){
		this.generateRandomTile();
		this.moves++;
		this.movesHTMLElement.innerHTML = "You made " + this.moves + " moves !";
	}
	
}

Game.prototype.moveLeft = function(){
	var dGrid = this.dynamicGrid,
		w = this.width,
		tileSize = this.tileSize,
		space = this.space;
	
	//Si des cases se sont déplacée, alors c'est true
	//Si c'est true, on génère une autre cases 2 ou 4 aléatoirement
	//Si aucune cases ne s'est déplacée, on ne génère rien
	var change = false;
	
	for(var yy = 0; yy < this.height; yy++){
		for(var xx = 0; xx < w; xx++){
			var tile = dGrid[xx + yy*w];
			if(tile !== undefined){
				for(var i = xx-1; i >= 0; i--){
					if(dGrid[i + yy*w] === undefined){
						dGrid[(i+1) + yy*w] = undefined;
						tile.x = i;
						change = true;
					}
					else {
						if(dGrid[i + yy*w].value === tile.value){
							tile.x = i;
							tile.value *= 2;
							dGrid[(i+1) + yy*w] = undefined;
							this.dynamicContainer.removeChild(dGrid[i+yy*w].htmlElement);
							change = true;

							                                           // calcul du score dynamiquement
							this.scoreCourant += tile.value;
							this.scores.innerHTML = "Score = " + this.scoreCourant ;
						}
						break;
					}
				}
				
				dGrid[tile.x + yy*w] = tile;
				
				tile.htmlElement.style.top = (yy*tileSize + (yy+1)*space) + "px";
				tile.htmlElement.style.left = (tile.x*tileSize + (tile.x+1)*space) + "px";
				tile.htmlElement.style.backgroundColor = this.getColorByValue(tile.value);
				tile.htmlElement.childNodes[0].nodeValue = tile.value;
			}
		}
	}
	
	if(change){
		this.generateRandomTile();
		this.moves++;
		this.movesHTMLElement.innerHTML = "You made " + this.moves + " moves !";
	}
	
}

Game.prototype.moveRight = function(){
	var dGrid = this.dynamicGrid,
		w = this.width,
		tileSize = this.tileSize,
		space = this.space;
	
	//Si des cases se sont déplacée, alors c'est true
	//Si c'est true, on génère une autre cases 2 ou 4 aléatoirement
	//Si aucune cases ne s'est déplacée, on ne génère rien
	var change = false;
	
	for(var yy = 0; yy < this.height; yy++){
		for(var xx = w-1; xx >= 0; xx--){
			var tile = dGrid[xx + yy*w];
			if(tile !== undefined){
				for(var i = xx+1; i < w; i++){
					if(dGrid[i + yy*w] === undefined){
						dGrid[(i-1) + yy*w] = undefined;
						tile.x = i;
						change = true;
					}
					else {
						if(dGrid[i + yy*w].value === tile.value){
							tile.x = i;
							tile.value *= 2;
							dGrid[(i-1) + yy*w] = undefined;
							this.dynamicContainer.removeChild(dGrid[i+yy*w].htmlElement);
							change = true;

							                                                      // calcul du score dynamiquement
							this.scoreCourant += tile.value;
							this.scores.innerHTML = "Score = " + this.scoreCourant ;
						}
						break;
					}
				}
				
				dGrid[tile.x + yy*w] = tile;
				
				tile.htmlElement.style.top = (yy*tileSize + (yy+1)*space) + "px";
				tile.htmlElement.style.left = (tile.x*tileSize + (tile.x+1)*space) + "px";
				tile.htmlElement.style.backgroundColor = this.getColorByValue(tile.value);
				tile.htmlElement.childNodes[0].nodeValue = tile.value;
			}
		}
	}
	
	if(change){
		this.generateRandomTile();
		this.moves++;
		this.movesHTMLElement.innerHTML = "You made " + this.moves + " moves !";
	}
	
}

Game.prototype.getColorByValue = function(value){
	switch(value){
		case 2: return "white"; break;
		case 4: return "orangered"; break;
		case 8: return "yellow"; break;
		case 16: return "red"; break;
		case 32: return "purple"; break;
		case 64: return "lime"; break;
		case 128: return "brown"; break;
		case 256: return "orchid"; break;
		case 512: return "chocolate"; break;
		case 1024: return "aquamarine"; break;
		case 2048: return "blueviolet"; break;
		default: return "black";
	}
}


var keys = new Array(256);
var previous_keys = new Array(256);
window.addEventListener("keydown", function(e){
	keys[e.keyCode] = true;
});
window.addEventListener("keyup", function(e){
	keys[e.keyCode] = false;
});
var Input = {};
Input.isKeyDown = function(keyCode){
	return keys[keyCode];
}
Input.isKeyPressed = function(keyCode){
	return keys[keyCode] && !previous_keys[keyCode];
}
Input.update = function(){
	for(var k = 0; k < 256; k++){
		previous_keys[k] = keys[k];
	}
}
Input.init = function(){
	for(var k = 0; k < 256; k++){
		previous_keys[k] = false;
		keys[k] = false;
	}
}

                                                        // Generalisation du jeu
var dimension = prompt("Choose the width of your game (integer): ");

var dimension2 = prompt("Choose the height of your game (integer): ");



var game = new Game(dimension, dimension2);

game.setupHTML();

Input.init();

window.setInterval(function(){ game.update(); }, 1000/60);
              
            
!
999px

Console