Home Web Front-end JS Tutorial How to implement jigsaw puzzle in js object-oriented

How to implement jigsaw puzzle in js object-oriented

Apr 04, 2018 pm 01:46 PM
javascript puzzle object-oriented

This article mainly introduces how to implement js object-oriented jigsaw puzzle. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor and take a look.

1. HTML code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>拼图小游戏</title>

<style>

body,td { margin:0; padding:0; }

#begin { display:block; margin:20px auto; }

table { margin:80px auto; background:#fff; border:10px solid pink;  }

td { width:100px; height:100px; border:1px solid #ccc; cursor:pointer; background:url(img.jpg) no-repeat; }

</style>

<script src="js.js"></script>

<script>

window.onload = function(){

    var thisGame = new PinTuGame(&#39;begin&#39;);

}

</script>

 

</head>

 

<body>

<button id="begin">开始</button>

</body>

</html>

Copy after login

2. JS code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

function PinTuGame(id){

    var that = this;

    this.oBtn = document.getElementById(id);

    this.oTable = document.createElement(&#39;table&#39;);

    this.oTbody = document.createElement(&#39;tbody&#39;);

    this.aTd = null;

    this.aTdMsg = [];       //用于存储每个图片的信息

    this.num = 0;           //用于判断拼图是否完成

    this.oTable.cellSpacing = &#39;0&#39;;

     

    this.createElem();      //初始化游戏界面

    this.oBtn.onclick = function(){

        for(var i = 0; i<that.aTd.length; i++){

            that.aTd[i].style.opacity = 1; 

        }

        this.innerHTML = &#39;重新开始&#39;;

        that.aTd[that.aTd.length-1].style.opacity = 0;

         

        var iAlpha = 100;

        var sp = -10;

        var timer = setInterval(function(){

            iAlpha += sp;

            that.oTbody.style.opacity = iAlpha / 100;

     

            if(iAlpha <=0) { sp = -sp; that.randomElem();}

            if(iAlpha > 100) {clearInterval(timer) };

        },15); 

        that.beginGame();  

    }

}

 

PinTuGame.prototype = {     //初始化游戏界面

    createElem: function(){

        for(var i =0; i<4; i++){

            var oTr = document.createElement(&#39;tr&#39;);

            for(var j =0; j<4; j++){

                var oTd = document.createElement(&#39;td&#39;);

                this.num ++;

                var tdMsg = {

                    seq: this.num,

                    bgPosition: -100*j+&#39;px &#39;+ -100*i+&#39;px&#39;  

                }; 

                this.aTdMsg.push(tdMsg);

                oTr.appendChild(oTd);

            }

            this.oTbody.appendChild(oTr);  

        }  

        this.oTable.appendChild(this.oTbody);

        document.body.appendChild(this.oTable);

         

        this.aTd = this.oTbody.getElementsByTagName(&#39;td&#39;);

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

            this.aTd[i].json = this.aTdMsg[i];

            this.aTd[i].style.backgroundPosition = this.aTd[i].json.bgPosition;

        }

    },

    randomElem: function(){     //随机排序图片

        this.aTdMsg.sort(function (){

            return Math.random()-0.5;    

        });

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

            this.aTd[i].json = this.aTdMsg[i];

            this.aTd[i].style.backgroundPosition = this.aTd[i].json.bgPosition;

        }

    },

    beginGame: function(){      //开始游戏

        var that = this;

        var rows = this.oTbody.rows;

        for(var i =0; i<4; i++){

            for(var j =0; j<4; j++){

                rows[i].cells[j].Y = i;

                rows[i].cells[j].X = j;

                 

                rows[i].cells[j].onclick = function(){

                    var arr = [       //获取该图片的上右下左,四个方向的坐标

                        [this.Y-1, this.X],

                        [this.Y, this.X+1],

                        [this.Y+1, this.X],

                        [this.Y, this.X-1] 

                    ]; 

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

                        if( arr[i][0]<0 || arr[i][1]<0 || arr[i][0]>3 || arr[i][1]>3)continue;

                        if( rows[arr[i][0]].cells[ arr[i][1] ].style.opacity == &#39;0&#39; ){

                             

                            rows[arr[i][0]].cells[ arr[i][1] ].style.opacity = 1;

                            this.style.opacity=0;

     

                            //与隐藏的td交换json对象

                            var thisJson = this.json;

                            this.json = rows[arr[i][0]].cells[ arr[i][1]].json; 

                            rows[arr[i][0]].cells[arr[i][1]].json = thisJson;      

     

                            //与隐藏的td交换bakcground-position

                            this.style.backgroundPosition=this.json.bgPosition;

                            rows[arr[i][0]].cells[arr[i][1]].style.backgroundPosition=rows[arr[i][0]].cells[arr[i][1]].json.bgPosition;

                        }

                    }

                    that.checkWin();

                }; 

            }  

        }

    },

    checkWin: function(){       //检测游戏是否完成

        var aJson = [];

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

            aJson.push(this.aTd[i].json.seq);

        }  

        for(var i = 0; i<aJson.length-1; i++){

            if(aJson[i]>aJson[i+1])return;  

        }

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

            this.aTd[i].style.opacity = 1; 

        }

        alert(&#39;恭喜,胜利啦!&#39;);

        location.reload(); 

    }  

}

Copy after login

2. Game picture materials


# #

The above is the detailed content of How to implement jigsaw puzzle in js object-oriented. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

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

Explore object-oriented programming in Go Explore object-oriented programming in Go Apr 04, 2024 am 10:39 AM

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

PHP Advanced Features: Best Practices in Object-Oriented Programming PHP Advanced Features: Best Practices in Object-Oriented Programming Jun 05, 2024 pm 09:39 PM

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

Analysis of object-oriented features of Go language Analysis of object-oriented features of Go language Apr 04, 2024 am 11:18 AM

The Go language supports object-oriented programming, defining objects through structs, defining methods using pointer receivers, and implementing polymorphism through interfaces. The object-oriented features provide code reuse, maintainability and encapsulation in the Go language, but there are also limitations such as the lack of traditional concepts of classes and inheritance and method signature casts.

Are there any class-like object-oriented features in Golang? Are there any class-like object-oriented features in Golang? Mar 19, 2024 pm 02:51 PM

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

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 jigsaw puzzle with Yitian Camera? How to set up jigsaw puzzle? How to jigsaw puzzle with Yitian Camera? How to set up jigsaw puzzle? Mar 25, 2024 pm 12:50 PM

Download and install the latest version of Yitian Camera 2023. It is a must-have camera tool for everyone. The camera function is very advanced. It is very convenient to take pictures anytime and anywhere. Various styles of theme backgrounds, exquisite stickers, etc. can be downloaded for free. Use, the way to take photos is very simple. One-click beautification will make your skin more delicate. There are many popular and popular photo styles that you can try online every day, allowing you to become a beautiful goddess in minutes, and you can also shoot videos. Continuing to record the most beautiful moments in life, the editor will provide details on how to set up puzzles for Yitian camera partners online. 1. First enter the software interface and click [Template] to enter. 2. Enter the interface and click [Puzzle] to enter. 3. Finally enter the interface and click [Puzzle].

In-depth understanding of PHP object-oriented programming: Debugging techniques for object-oriented programming In-depth understanding of PHP object-oriented programming: Debugging techniques for object-oriented programming Jun 05, 2024 pm 08:50 PM

By mastering tracking object status, setting breakpoints, tracking exceptions and utilizing the xdebug extension, you can effectively debug PHP object-oriented programming code. 1. Track object status: Use var_dump() and print_r() to view object attributes and method values. 2. Set a breakpoint: Set a breakpoint in the development environment, and the debugger will pause when execution reaches the breakpoint, making it easier to check the object status. 3. Trace exceptions: Use try-catch blocks and getTraceAsString() to get the stack trace and message when the exception occurs. 4. Use the debugger: The xdebug_var_dump() function can inspect the contents of variables during code execution.

See all articles