Native js to implement 2048 game

Native js to implement 2048 game

2048 mini game, for your reference, the specific content is as follows

First of all, the 2048 game cannot be separated from 16 grids. We create the corresponding tags and styles through HTML and CSS, and then start the JS logic

<div id="box">//16 small divs in a box
 <div id="son"></div>
 <div id="son"></div>
 <div id="son"></div>
 <div id="son"></div>
 <div id="son"></div>
 <div id="son"></div>
 <div id="son"></div>
 <div id="son"></div>
 <div id="son"></div>
 <div id="son"></div>
 <div id="son"></div>
 <div id="son"></div>
 <div id="son"></div>
 <div id="son"></div>
 <div id="son"></div>
 <div id="son"></div>
</div>

Set the corresponding style: (for reference only)

#box{
 width: 450px;
 height: 450px;
 background-color: brown;
 display: flex;
 flex-wrap: wrap;
 justify-content: space-evenly;
 border: 1px solid #000;
 margin: 100px auto;
 border-radius: 10px;
 }
 div>div{
 margin-top: 5px;
 width: 100px;
 height: 100px;
 border-radius: 5px;
 background-color: bisque;
 text-align: center;
 line-height: 100px;
 font-size: 40px;
 }

The effect is as follows:

Then the real js part really begins. First, use the CSS selector to get all the small grid divs.

var divs = document.querySelectorAll('[id == son]');

Then create a two-dimensional array to receive the DOM objects of these 16 small grid divs

var arr = [[],[],[],[]];
var a = 0;
for(var i=0;i < 4; i++){
 for(var j=0; j < 4; j++){
 arr[i][j] = divs[a];
 a++ ;
 }
}

This forms the i and j axes:

This will facilitate our subsequent mobile operations

Now we write a program that randomly generates a random number 2 and 4 from the 16 cells and fills them into an empty cell. We will call it later!

function sj(){ //Generate random numbers var a = Math.floor(Math.random() * 4);
 var b = Math.floor(Math.random() * 4);
 if(arr[a][b].innerHTML == ""){
 if(Math.random()>0.5){
 arr[a][b].innerHTML = 2;
 }else{
 arr[a][b].innerHTML = 4;
 }
 
 }else{ //If the grid is not empty, we execute the function sj();
 }
}

The second one is the function to determine whether the game is over: the game ends when all the values ​​​​of the grid are not empty! (Called later)

function js(){ //Is the game over? var bool = true;
 for(var i=0;i < 4; i++){
 for(var j=0; j < 4; j++){
 if(arr[i][j].innerHTML == ""){
  bool = false;
 }else{
  
 }
 }
 } 
 if(bool){
 alert("Game over");
 for(var i=0;i < 4; i++){
 for(var j=0; j < 4; j++){
 arr[i][j] = null;
 }
 }
 
 }
}

Then we write functions to be executed by pressing the up, down, left, and right keys respectively:

Take pressing the up key as an example:

①If the upper number is empty and the lower number is not empty, the upper and lower values ​​are swapped;
②If the upper one is a number and is equal to the lower one, then the upper number * 2 and the value below is empty. Other conditions remain unchanged.

function downtop(){ //Function executed by pressing up for(var i=0;i < 4; i++){
 for(var j=0; j < 4; j++){
 if(arr[i][j].innerHTML == "" && i<3 &&arr[i+1][j].innerHTML != ""){
 arr[i][j].innerHTML = arr[i+1][j].innerHTML ;
 arr[i+1][j].innerHTML = "";
 downtop(); // Execute if the condition is met // If it is not met, it will not enter the if statement }else if(i<3&&arr[i][j].innerHTML !="" && arr[i+1][j].innerHTML !="" &&arr[i][j].innerHTML == arr[i+1][j].innerHTML){
 arr[i][j].innerHTML = 2*arr[i+1][j].innerHTML;
 arr[i+1][j].innerHTML = "";
 }else{
 
 }
 }
 }

}

Similarly, you only need to change (some parameters) to complete the logic of the other 3 keys:

function downbottom(){
 for(var i=3 ;i > 0 ; i--){
 for(var j=0; j < 4; j++){
 if(arr[i-1][j].innerHTML != "" && i>0 &&arr[i][j].innerHTML == "" ){ 
 arr[i][j].innerHTML = arr[i-1][j].innerHTML ;
 arr[i-1][j].innerHTML = "";
 downbottom();
 }
 else if(arr[i-1][j].innerHTML !=""&& arr[i][j].innerHTML !="" && i>0 &&arr[i-1][j].innerHTML == arr[i][j].innerHTML){
 arr[i][j].innerHTML = 2*arr[i-1][j].innerHTML;
 arr[i-1][j].innerHTML = "";
 }
 }
 }
}

function downleft(){
 for(var i=0;i < 4; i++){
 for(var j=0; j < 4; j++){
 if(arr[i][j].innerHTML == "" && j<3 &&arr[i][j+1].innerHTML != ""){
 arr[i][j].innerHTML = arr[i][j+1].innerHTML ;
 arr[i][j+1].innerHTML = "";
 downleft();
 }else if( j<3&& arr[i][j].innerHTML !=""&& arr[i][j+1].innerHTML !="" &&arr[i][j].innerHTML == arr[i][j+1].innerHTML){
 arr[i][j].innerHTML = 2*arr[i][j+1].innerHTML;
 arr[i][j+1].innerHTML = "";
 }
 }
 }

}


function downright(){
 
 for(var i=0;i < 4; i++){
 for(var j = 3 ;j > 0; j--){
 if(j > 0 && arr[i][j].innerHTML == ""&&arr[i][j-1].innerHTML != ""){
 arr[i][j].innerHTML = arr[i][j-1].innerHTML ;
 arr[i][j-1].innerHTML = "";
 downright();
 }else if( j>0 && arr[i][j].innerHTML !=""&& arr[i][j-1].innerHTML !="" &&arr[i][j].innerHTML == arr[i][j-1].innerHTML){
 arr[i][j].innerHTML = 2*arr[i][j-1].innerHTML;
 arr[i][j-1].innerHTML = "";
 }
 }
 }

 }

Add different background colors for different values: (optional)

function color(){

for(var i=0;i < 4; i++){
 for(var j=0; j < 4; j++){
 switch(arr[i][j].innerHTML){
 case "": arr[i][j].style.backgroundColor = "bisque";break; 
 case "2": arr[i][j].style.backgroundColor = "red";break; 
 case "4": arr[i][j].style.backgroundColor = "orange";break; 
 case "8": arr[i][j].style.backgroundColor = "yellow";break; 
 case "16": arr[i][j].style.backgroundColor = "green";break; 
 case "32": arr[i][j].style.backgroundColor = "blue";break; 
 case "64": arr[i][j].style.backgroundColor = "#000";break; 
 case "128": arr[i][j].style.backgroundColor = "aqua";break; 
 case "256": arr[i][j].style.backgroundColor = "pink";break; 
 }
 
 
 }
}

}

Then set up keyboard monitoring events for the entire window:

keyCode: 38
The keyCode is: 40
Left keyCode: 37
Right keyCode: 39
Each time you press the button, ① call the function of the corresponding direction ② call the function with a random parameter ③ call the function to determine whether the game is over ④ call the function with different values ​​and different elements ⑤ call 2 times when the game starts (2 by default)

window.onkeydown = function(e){
 switch(e.keyCode){
 case 37: downleft(); sj(); color(); js(); break; //left case 38: downtop(); sj(); color(); js(); break; //upper case 39: downright(); sj(); color(); js(); break; //right case 40: downbottom(); sj(); color(); js(); break; //lower}

}
sj(); //The game starts with two default numbers sj();

The simple 2048 game is completed!

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • AngularJS implementation of the 2048 game function [with source code download]
  • Writing 2048 mini game with native js
  • 2048 game written in Javascript
  • Writing 2048 game with Javascript
  • javascript version of 2048 game
  • JS native 2048 game source code sharing (the latest on the Internet)

<<:  How to configure ssh/sftp and set permissions under Linux operating system

>>:  What to do if you forget your Linux/Mac MySQL password

Recommend

Keepalived implements Nginx load balancing and high availability sample code

Chapter 1: Introduction to keepalived The purpose...

Example of deploying MySQL on Docker

Table of contents 1 What is container cloud? 2 In...

MySQL exposes Riddle vulnerability that can cause username and password leakage

The Riddle vulnerability targeting MySQL versions...

Install mysql5.7.13 using RPM in CentOS 7

0. Environment Operating system for this article:...

Detailed tutorial on installing MySQL database in Linux environment

1. Install the database 1) yum -y install mysql-s...

In-depth study of vue2.x--Explanation of the h function

Table of contents Solution, Summarize: vue projec...

CentOS 7.x docker uses overlay2 storage method

Edit /etc/docker/daemon.json and add the followin...

Common methods of Vue componentization: component value transfer and communication

Related knowledge points Passing values ​​from pa...

Setting up a proxy server using nginx

Nginx can use its reverse proxy function to imple...

Six border transition effects implemented by CSS3

Six effectsImplementation Code html <h1>CSS...

How to display percentage and the first few percent in MySQL

Table of contents Require Implementation Code dat...

IIS7~IIS8.5 delete or modify the server protocol header Server

Requirements: Remove HTTP response headers in IIS...