Home Web Front-end JS Tutorial Native JavaScript implements Lianliankan game

Native JavaScript implements Lianliankan game

Nov 28, 2016 pm 01:32 PM
javascript

首先看一下html的布局方式在index.html文件中:

 

[html]  

 

 

     

         

        连连看  

       

     

     

       

 

           

 

               

 

                   

 

                   

 

               

 

               

 

               

 

                    分  数  

               

 

               

 

                    0  

               

 

               

 

                    时  间  

               

 

               

 

                    0  

               

 

               

 

                     

                     

               

                 

           

 

       

 

         

         

         

     

 

 

css文件夹下的index.css文件如下:

 

[css] 

body {  

  

    font-size : 16px;  

    font-weight : bold;  

    color : grey;  

  

}  

  

#whole {  

  

    border : 1px double #999999;  

    border-width : 5px;  

    width : 800px;  

    height : 505px;  

    position : relative;  

  

}  

  

#gamePanel {  

      

    margin: 1px 1px 1px 1px;  

    width : 602px;  

    height : 502px;  

    background : url(../img/background.gif) repeat;  

    position : absolute;  

  

}  

  

#pieces {  

  

    margin-top : 35px;  

    border : 1px solid #999999;  

    width : 546px;  

    height : 434px;  

    position: relative;  

  

}  

  

#pieces .piece {  

  

    width : 32px;  

    height : 36px;  

    position : relative;  

    cursor : pointer;  

    float : left;  

  

}  

  

#pieces .track {  

  

    width : 32px;  

    height : 36px;  

    position : relative;  

    float : left;  

  

}  

  

#pieces .track2 {  

  

    width : 32px;  

    height : 36px;  

    position : relative;  

    float : left;  

    background : red;  

  

}  

  

#gameLogo {  

      

    margin-top : 60px;  

    border : 1px solid #999999;  

    left : 607px;  

    width : 187px;  

    height : 73px;  

    background : url(../img/logo.gif);  

    position: absolute;  

  

}  

  

#scorePanel {  

  

    border : 1px solid #999999;  

    left : 607px;  

    top : 200px;  

    width : 187px;  

    height : 30px;  

    position : absolute;  

  

}  

  

#score {  

  

    border : 1px solid #999999;  

    left : 607px;  

    top : 240px;  

    width : 187px;  

    height : 30px;  

    position : absolute;  

  

}  

  

#timePanel {  

  

    border : 1px solid #999999;  

    left : 607px;  

    top : 300px;  

    width : 187px;  

    height : 30px;  

    position : absolute;  

  

}  

  

#time {  

  

    border : 1px solid #999999;  

    left : 607px;  

    top : 340px;  

    width : 187px;  

    height : 30px;  

    position : absolute;  

  

}  

  

#button {  

  

    border : 1px solid #999999;  

    left : 607px;  

    top : 400px;  

    width : 187px;  

height : 30px;

position : absolute;

}

Let’s take a look at the core js part implementation code. The js part is divided into three source files: game Each source file of .js, map.js, and piece.js corresponds to a class. This game uses the game class to manipulate map and picture piece objects:

game.js code is as follows:

[javascript]

// Game control class

var Game = {

  // Game background

  gamePanel: null,

       

    //   Score

 Score : 0,

// Time

time: 0,

// Picture map

pieceMap: null,

// Picture list

pieceList: [],

                                                                   pieceimglist: [],

// Picture random number list

randomlist: [],

// trajectory list

tracklist: [],

// whether the game starts

isgamebigin: false,

                                                                                                                                                                              

// Whether the picture element is clicked for the first time

isFirstClick: true,

                                                                                                                                                                              GetElementById ( "). elementById("reset").disabled = false;

                                                                                                                                                                

                                                                                                          

                                                                                                                                                                                                                                                                                             

reset : function() {

           document.getElementById("start").disabled = false;               document.getElementById("reset").                             document.getElementById("reset").disabled =                          document.getElementById("reset").

this.initPieces();

this.initImgPieces();

this.time = 0;

document.getElementById("time").innerHTML = 0;

this.score = 0;

document.getElementById("score"). innerHTML = 0;

             

          this.isGameReset = true;

// Initialization

init : function() {

if (this .isGameBegin) {

       

                                                                                                                                                         

    var _this = this;

       

          this.time = 0;

This.gamePanel = document.getElementById("pieces");

This.initPieces(); this.initImgPieces(); This.isGameBegin = true;

},

机 随 // Add the randomly generated 150 pictures into the canvas

Initpieces: Function () {

var _This = this;

this.initrandomList (); Random list sorting

this.messRandomList();

                                                                                         var piece = new Piece(this);               this.pieceList .push(piece);

           

        var x = (i%17);         var y = Math.floor(i/17);

This.pieceMap.put(x+","+y, piece);

                                                                          piece.setPosition(x, y);

                                                                                                                          if (x == 0 || x == 16 || y == 0 || y == 11) {

                                                                                                         

              piece.dom.appendChild(piece.track) ;

                  piece.isTracked = true;                                                                                                                                  ) {

e piece.Setatedge (true);

}

this.pieceimglist.push (piece);

// Initialize pictures

initImgPieces : function() {

                                                                                                 This.pieceImgList[i].initImg ();

This.pieceImgList[i].img.src = "img/pieces/"+this.randomList[i]+".gif"

This.pieceImgList[i].setImgSrc(this.pieceImgList[i].img. src);

                                                                                                                                              function() {

                                                                                                                                                                                                   Int(Math.random() *22*10000, 10);

var number = random%23;

this.randomList.push(number);

this.randomList.push(number);                                                                                               

                                                                                                                                                                                                                                                                                    parseInt(Math.random()*15*10000, 10);

var number = random%150;

var temp;

temp = this.randomList [i];

this.randomList[i] = this.randomList[number];

this.randomList[number] = temp;

} }

},

                                                                                   var _this = this;

                                                                            } else {

                                                                                                                                   . innerHTML = this.time;

this.isGameBegin = true;

setTimeout(function() {_this.startTime();}, 1000);

}

                                                                                                                                              Clear

clear : function() {

for (var i = 0; i < this.pieceList.length; i ++) {

i] .dom);                                                                                                                                                       

this.pieceImgList = [];

this.isGameOver = true;

this.isGameBegin = false; ElementById("start").disabled = false;

document.getElementById("reset").disabled = true;

}

// Game start entrance

function Start() {

Game.start();

}

// Game reset entry

function Reset() {

Game.reset();

}

Customized js version mapping structure map.js The source file is as follows:

[javascript]

var Map = function(){

this.data = [];

}

M ap.prototype = {

put : function(key, value) {

                                                                                                                                                      return this.data[key]; },

                                                                                           

isEmpty : function() {

return this.data .length == 0;

},

size: function() {

} return this.data.length;

}

pictures The source file of class piece.js is as follows:

[javascript]

var Piece = function(game) {

// Game object

this.game = game;

// Is it an edge? Element

this.isEdge = false;

// Whether it is next to the edge element

this.atEdge = false;

// Image dom element

this.dom = null;

/ / Image element

this.img = null;

// Image element source

this.src = null;

// Track element

this.track = null;

// Whether it can be used as a track

This.isTracked = false;

// Check mark element

this.selected = null;

// Pictures arranged horizontally This.x = 0;

// Pictures are arranged vertically

this.y = 0;

​ ​

​ // Picture flash Id

​ this.flashId = null;

​ ​

​ // Whether the picture is clicked

​this.onClicked = false;

// Number of flashes

this.flashCount = 0;

this.init();

}

Piece.prototype = {

// Initialization

init : function( ) {

  This.dom = document.createElement("div");

this.dom.className = "piece"; createElement("img");

},

// Initialization image

initImg: function() {

this.img = document.createElement("img");

     

        this.dom.appendChild(this.img);  

      

    },  

      

    // 满足算法后初始化track元素  

    initTrack : function() {  

  

        if (this.flashId != null) {  

              

            // 停止闪烁  

            this.stopFlash();  

              

        }         

          

        //alert("initTrack middle");  

        if (this.track != null) {  

          

            return;  

        }  

          

        this.onClicked = false;  

          

        this.dom.removeChild(this.img);  

      

        this.track = document.createElement("div");  

        this.track.className = "track";  

        this.dom.appendChild(this.track);  

      

    },  

      

    // 位图片设置来源  

    setImgSrc : function(src) {  

  

        this.src = src;  

      

    },  

      

    // 为图片设置二维排列位置  

    setPosition : function(x, y) {  

      

        this.x = x;  

        this.y = y;  

      

    },  

      

    // 为图片设置选中元素  

    setSelected : function() {  

          

        if (this.flashCount ++ % 2 == 0) {  

              

            //this.dom.removeChild(this.img);  

            //this.selected.src = "img/selected.gif";  

            //this.dom.appendChild(this.selected);    

            this.img.src = "img/pieces/flash.gif";  

          

        } else {  

              

            //if (this.selected != null) {  

                          

            //  this.dom.removeChild(this.selected);              

              

            //}  

              

            this.img.src = this.src;  

            //this.dom.appendChild(this.img);  

          

        }  

                      

    },  

      

    // 设置是否为边缘元素  

    setEdge : function(isEdge) {  

      

        this.isEdge = isEdge;  

      

    },  

      

    // 设置是否挨着边缘元素  

    setAtEdge : function(atEdge) {  

      

        this.atEdge = atEdge;  

      

    },  

      

    // 开始闪烁  

    flash : function() {  

          

        var _this = this;  

This.flashId = setInterval(function() {_this.setSelected();}, 500);

},

// Stop flashing

stopFlash : function() {

clearInterval( this.flashId);

                                                                                                                                                                                if (this.flashCount % 2 == 1) {

                                                                                                                .selected);

                                                                                        //this.dom.appendChild(this.img); ,

对 // Object internal function

OnClick: Function () {

if (this.OnClicked) {

Return;

}}

var _This = this;

                                                                                                                                                                                                                                                                     . if (_this.onClicked) {

Return;

}}

(_this.checkpiece ()) {

Return;

}}

_this.flash ( );

            _this.onClicked = true;

// Check if there is a clicked picture

checkPiece: function() {

         

                         i = 0; i < this.game.pieceList.length; i ++) {

                                                                                                                                                                                              )) {

                                                                                                  //alert("The same Image"); [i]);

                                                                                             pieceList[i].stopFlash();

                         this.game.pieceList[i].onClicked = false;                                                                                           return false;                                                                  ;

                                                                           

                                                                                                                                                                                                                                                                                                                                                                      

                                                                               .

                                                                                                                                                                             ,                                                                                                        

                                                                                                               

                                                                                                                                                         );

                                                                                                                                                                                                               - this.x) == 1) && (piece.y == this.y)

          || (Math.abs(piece.y - this.y) == 1) && (piece.x == this. x);

                                                                                                                                                          //alert("isStraightReach");

if (this.isNear(piece )) {

                                                                                      a = false;

var b = false;

                                                                                                                                                                                                                       ​= pieces. < this.max(this.y, piece.y); i ++) {

                      //alert("this.x == piece.x: " + piece.x + "," + i);

                if (this.game.pieceMap.get(piece.x + "," + i).isPass()) {  

                  

                    a = true;  

                      

                    this.game.trackList.push(this.game.pieceMap.get(piece.x + "," + i));  

                      

                    continue;  

                } else {  

                  

                    a = false;  

                    this.game.trackList = [];  

                      

                    return a;     

                }  

              

            }  

                          

        }  

          

        // 沿x轴方向搜索  

        if (this.y == piece.y) {  

            //alert("!!!!!!!!!!!");  

            for (var i = this.min(this.x, piece.x) + 1; i < this.max(this.x, piece.x); i ++) {  

                //alert("this.y == piece.y: " + i + "," + piece.y);  

                if (this.game.pieceMap.get(i + "," + piece.y).isPass()) {  

                      

                    b = true;  

                    this.game.trackList.push(this.game.pieceMap.get(i + "," + piece.y));  

                      

                    continue;  

                } else {  

                  

                    b = false  

                    this.game.trackList = [];  

                      

                    return b;  

                }  

              

            }  

              

        }  

  

        return a || b;  

    },  

  

      

    // 拐一次弯搜索  

    isReach1 : function(piece) {  

        //alert("isReach1");  

        var corner_1 = this.game.pieceMap.get(this.x + "," + piece.y);  

        var corner_2 = this.game.pieceMap.get(piece.x + "," + this.y);  

                          

        var _this = this;  

  

          

        if ((_this.isStraightReach(corner_1))  

            && (corner_1.isStraightReach(piece))  

            && corner_1.isPass()) {  

              

                //alert("corner_1: " + this.x + "," + piece.y);  

                this.game.trackList.push(corner_1);  

              

                return true;  

        }  

      

        if ((_this.isStraightReach(corner_2))  

            && (corner_2.isStraightReach(piece))  

            && corner_2.isPass()) {  

                //alert("corner_2: " + piece.x + "," + this.y);  

                this.game.trackList.push(corner_2);  

              

            return true;  

        }  

  

        return false;  

    },  

      

    // 直接或拐一次弯搜索  

    isReach : function(piece) {  

          

        var a = this.isStraightReach(piece);  

          

        var b = this.isReach1(piece);  

                  

        return a || b;  

    },  

      

    // 拐两次弯搜索  

    isReach2 : function(piece) {  

              

        // 沿x轴正向搜索  

        for (var i = this.x + 1; i < 17; i ++) {  

              

            if (!this.game.pieceMap.get(i + "," + this.y).isPass()) {  

                  

                this.game.trackList = [];  

                  

                break;  

                  

            } else if (this.game.pieceMap.get(i + "," + this.y).isReach(piece)  

                && this.game.pieceMap.get(i + "," + this.y).isPass()) {  

                  

                this.game.trackList.push(this.game.pieceMap.get(i + "," + this.y));  

                      

                return true;  

            }     

          

        }  

          

        // 沿x轴搜索  

        for (var i = this.x - 1; i >= 0; i --) {  

              

            if (!this.game.pieceMap.get(i + "," + this.y).isPass()) {  

              

                this.game.trackList = [];  

                  

                break;  

                  

            } else if (this.game.pieceMap.get(i + "," + this.y).isReach(piece)  

                && this.game.pieceMap.get(i + "," + this.y).isPass()) {  

              

                this.game.trackList.push(this.game.pieceMap.get(i + "," + this.y));  

                      

                return true;  

            }  

          

        }  

          

        // 沿y轴搜索  

        for (var i = this.y - 1; i >= 0; i --) {  

              

            if (!this.game.pieceMap.get(this.x + "," + i).isPass()) {  

                  

                this.game.trackList = [];  

                  

                break;  

                  

            } else if (this.game.pieceMap.get(this.x + "," + i).isReach(piece)  

                && this.game.pieceMap.get(this.x + "," + i).isPass()) {  

                  

                this.game.trackList.push(this.game.pieceMap.get(this.x + "," + i));  

                      

                return true;  

            }  

          

        }  

  

        // 沿y轴正向搜索  

        for (var i = this.y + 1; i < 12; i ++) {  

  

            if (!this.game.pieceMap.get(this.x + "," + i).isPass()) {  

                  

                this.game.trackList = [];  

                  

                break;  

            } else if (this.game.pieceMap.get(this.x + "," + i).isReach(piece)  

                && this.game.pieceMap.get(this.x + "," + i).isPass()) {  

                  

                this.game.trackList.push(this.game.pieceMap.get(this.x + "," + i));  

                      

                return true;  

            }  

          

        }  

          

        return false;  

    },  

      

    // 路径连接  

    linkTrack : function(piece) {  

      

        this.initTrack();  

        piece.initTrack();  

        this.changeScore();  

        this.showTrack(piece);  

              

    },  

      

    // 显示足迹  

    showTrack : function(piece) {  

      

        this.game.trackList.push(piece);  

        this.track.className = "track2";  

          

        for (var i = 0; i < this.game.trackList.length; i ++) {  

            //alert(i);  

            this.game.trackList[i].track.className = "track2";  

          

        }  

          

        var _this = this;  

        setTimeout(function() {_this.hideTrack()}, 500);  

      

    },  

      

    // 隐匿足迹  

    hideTrack : function() {  

      

        for (var i = 0; i < this.game.trackList.length; i ++) {  

              

            this.game.trackList[i].track.className = "track";  

              

        }  

              

        this.game.trackList = [];  

        this.track.className = "track";  

        this.isTracked = true;  

          

    },  

      

    // 分数增加  

    changeScore : function() {  

              

        this.game.score += 100;  

        document.getElementById("score").innerHTML = this.game.score;         

      

    },  

      

    min : function(a, b) {  

      

        if (a < b) {  

          

            return a;  

          

        } else {  

          

            return b;  


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles