_javascript skills of digital jigsaw puzzle based on Vue.js

Source: Internet
Author: User

Let's take a look at the effect chart:

Functional analysis

Of course play back to play, as a Vue enthusiasts, we should go deep inside the game, a code to achieve. Next, we will analyze how to complete such a game, the main need to implement what functions. I'll just list the function points of this instance directly below:

1. Randomly generated 1~15 of the digital lattice, each number must appear and only once

2. Click on a number of squares, such as its upper and lower left and right there is a space, the two exchange positions

3. Lattice every move step, we all need to check whether it succeeds

4. Click Reset Game button to reorder puzzles

The above is the main function point of this example, visible game function is not complicated, we just have to break the OK, then I will show the various function points of the Vue code.

Building the game panel

As a data-driven JS framework, Vue of the HTML template should be binding data many times, than so the game box lattice, we here must not be written dead, the code is as follows:

<template>
  <div class= "box" >
    <ul class= "Puzzle-wrap" >
      <li 
        : class= "{' Puzzle '" : True, ' Puzzle-empty ':!puzzle} ' v-for= ' puzzle in puzzles ' v-text= ' puzzle '
      ></li>
    </ul >
  </div>
</template>

<script>
Export Default {
  data () {return
    {
      puzzles: [1, 2, 3, 4, 5, 6, 7, 8, 9, A, one, N, N]
}} </script>

Here I omitted the CSS style section, you can not care about first. The above code we will write the number of 1~15 to death in an array, which is obviously not random ordering, then we will implement the function of random ordering.

Random sort number

<template>
  <div class= "box" >
    <ul class= "Puzzle-wrap" >
      <li 
        : class= "{' Puzzle '" : True, ' Puzzle-empty ':!puzzle} ' v-for= ' puzzle in puzzles ' v-text= ' puzzle '
      ></li>
    </ul >
  </div>
</template>

<script>
Export Default {
  data () {return
    {
      puzzles: []
    }
  },
  methods: {

    //Reset render
    render () {let
      Puzzlearr = [],
        i = 1

      Generates an array containing 1 ~ 15 digits for
      (i; i < i++) {
        Puzzlearr.push (i)
      }

      //random scrambling array
      Puzzlearr = Puzzlearr. Sort (() => {return
        math.random ()-0.5
      });

      Page display
      this.puzzles = Puzzlearr
      this.puzzles.push (')
    },
  ready () {
    this.render ()
  }
}

The above code, we use the For loop to generate a 1~15 ordered array, and then we use the original JS sort method randomly scrambling numbers, here also contains a knowledge point is the Math.random() method.

By using the sort() method for custom sorting, we need to provide a comparison function, and then return a number that describes the relative order of the two values, and the return value is as follows:

1. Returns a value less than 0, stating that A is less than B

2. return 0, stating that a equals B

3. Returns a value greater than 0 stating that A is greater than B

Here use Math.random() to generate a 0 ~ 1 of the random number, and then subtract 0.5, so that there will be half the probability of returning a value less than 0, half the probability of returning a value greater than 0, to ensure the randomness of the generation of arrays, the realization of the dynamic random generation of digital lattice function.

It should be noted that we also inserted an empty string at the end of the array to generate a unique blank lattice.

Swap square Position

<template> <div class= "box" > <ul class= "puzzle-wrap" > <li:class= "{' Puzzle ': TR
      UE, ' puzzle-empty ':!puzzle} "v-for=" Puzzle in Puzzles "v-text=" puzzle "@click =" Movefn ($index) " ></li> </ul> </div> </template> <script> Export Default {data () {RE

      Turn {puzzles: []}}, methods: {//Reset render render () {Let Puzzlearr = [], i = 1  Generates an array containing 1 ~ 15 digits for (i; i < i++) {Puzzlearr.push (i)}//random scrambling array Puzzlearr =

      Puzzlearr.sort (() => {return math.random ()-0.5}); Page display this.puzzles = Puzzlearr this.puzzles.push (')},//Click on box Movefn (index) {//Get click Position and its top and bottom values let Curnum = This.puzzles[index], Leftnum = this.puzzles[index-1], Rightnum = This.puzz Les[index + 1], Topnum = this.puzzles[index-4], bOttomnum = This.puzzles[index + 4]//and NULL position Exchange value if (Leftnum = = ") {this.puzzles. $set (Index-1, C Urnum) this.puzzles. $set (Index, ')} else if (Rightnum = = ") {this.puzzles. $set (index + 1, Curnu
        m) this.puzzles. $set (Index, ')} else if (Topnum = = ") {this.puzzles. $set (index-4, Curnum)
        This.puzzles. $set (Index, ')} else if (Bottomnum = = ") {this.puzzles. $set (Index + 4, curnum) This.puzzles. $set (Index, ')}}}, Ready () {This.render ()}} </script>

1. Here we first add the Click event @click= "Movefn ($index)" On the li of each lattice to get the position of the click box in the array by $index parameter

2. Next get its top and bottom numbers in the array the index value is index-4, index + 4, index-1, index + 1.

3. When we find up and down there is a place for empty when we assign the empty position to the current click on the grid number, the current click position to Empty

Note: Why do we use the $set method instead of assigning it directly to the equals sign, which contains the knowledge points of the Vue response principle.

Because of JavaScript limitations, Vue.js cannot detect the following array changes:

//1. Set elements directly with the index, such as vm.items[0] = {};
//2. Modify the length of the data, such as Vm.items.length = 0. //
to solve the problem (1), Vue.js expands the observation array and adds a $set () method to it:

//Is the same as ' example1.items[0 ' = ... ', but can trigger the view update
Example1.items. $set (0, {childmsg: ' changed! '})

Detect if successful

<template> <div class= "box" > <ul class= "puzzle-wrap" > <li:class= "{' Puzzle ': TR
      UE, ' puzzle-empty ':!puzzle} "v-for=" Puzzle in Puzzles "v-text=" puzzle "@click =" Movefn ($index) " ></li> </ul> </div> </template> <script> Export Default {data () {RE

      Turn {puzzles: []}}, methods: {//Reset render render () {Let Puzzlearr = [], i = 1  Generates an array containing 1 ~ 15 digits for (i; i < i++) {Puzzlearr.push (i)}//random scrambling array Puzzlearr =

      Puzzlearr.sort (() => {return math.random ()-0.5}); Page display this.puzzles = Puzzlearr this.puzzles.push (')},//Click on box Movefn (index) {//Get click Position and its top and bottom values let Curnum = This.puzzles[index], Leftnum = this.puzzles[index-1], Rightnum = This.puzz Les[index + 1], Topnum = this.puzzles[index-4], bOttomnum = This.puzzles[index + 4]//and NULL position Exchange value if (Leftnum = = ") {this.puzzles. $set (Index-1, C Urnum) this.puzzles. $set (Index, ')} else if (Rightnum = = ") {this.puzzles. $set (index + 1, Curnu
        m) this.puzzles. $set (Index, ')} else if (Topnum = = ") {this.puzzles. $set (index-4, Curnum)
        This.puzzles. $set (Index, ')} else if (Bottomnum = = ") {this.puzzles. $set (Index + 4, curnum) This.puzzles. $set (Index, ')} THIS.PASSFN ()},//Verify Clearance PASSFN () {if (this.puzzles[1 5] = = = "{Const Newpuzzles = this.puzzles.slice (0) Const ISPASS = Newpuzzles.every ((e, i) => E = = = i + 1) if (ispass) {alert (' Congratulations, success! ')}}}, Ready () {This.render ()}} </script>

We moveFn call methods in the method passFn to detect, and passFn the method involves two points of knowledge:

(1) Slice method

By slice method We intercept the first 15 elements of the array to generate a new array, assuming that an array followed by an element is empty

(2) Every method

By every method, we iterate over whether each element of the array is equal to its index+1 value, returns True if all Equals, and returns False if one is not equal

If the successful ispass, then the value of true, will alert "Congratulations, success!" "Hint window, if not, do not prompt."

Reset Game

Resetting the game is really simple, just add the reset button and invoke the method on it render :

<template> <div class= "box" > <ul class= "puzzle-wrap" > <li:class= "{' Puzzle ': TR
      UE, ' puzzle-empty ':!puzzle} "v-for=" Puzzle in Puzzles "v-text=" puzzle "@click =" Movefn ($index) " ></li> </ul> <button class= "btn btn-warning btn-block btn-reset" @click = "Render" > Reset game &L 
    t;/button> </div> </template> <script> Export Default {data () {return {puzzles: []
      }, Methods: {//Reset render render () {Let Puzzlearr = [], i = 1//generate array containing 1 ~ 15 digits  for (i; i < i++) {Puzzlearr.push (i)}//random scrambling array Puzzlearr = Puzzlearr.sort (() =>

      {return math.random ()-0.5}); Page display this.puzzles = Puzzlearr this.puzzles.push (')},//Click on box Movefn (index) {//Get click Position and its top and bottom values let Curnum = This.puzzles[index], Leftnum = this.puzzles[index-1], Rightnum = This.puzzles[index + 1], Topnum = this.puzzles[index-4], Bottomnum = this.puzzles[ Index + 4]//and NULL position Exchange value if (Leftnum = = ") {this.puzzles. $set (index-1, Curnum) this.puzz Les. $set (Index, ')} else if (Rightnum = = ") {this.puzzles. $set (index + 1, curnum) this.puzzles. $set (Index, ')} else if (Topnum = = ") {this.puzzles. $set (index-4, Curnum) this.puzzles. $set (i Ndex, ')} else if (Bottomnum = = ") {this.puzzles. $set (Index + 4, curnum) this.puzzles. $set (Inde x, ')} THIS.PASSFN ()},//checksum clearance PASSFN () {if (this.puzzles[15] = = ') {con St Newpuzzles = this.puzzles.slice (0) Const ISPASS = Newpuzzles.every ((e, i) => e = = i + 1) if ( Ispass) {alert (' Congratulations, success! ')}}}, Ready () {This.render ()}} </script> <style> @import urL ('./assets/css/bootstrap.min.css '); 
Body {font-family:arial, "Microsoft Yahei";
  box {width:400px;
margin:50px Auto 0;
  }. puzzle-wrap {width:400px;
  height:400px;
  margin-bottom:40px;
  padding:0;
  Background: #ccc;
List-style:none;
  }. puzzle {float:left;
  width:100px;
  height:100px;
  font-size:20px;
  Background: #f90;
  Text-align:center;
  line-height:100px;
  border:1px solid #ccc;
  box-shadow:1px 1px 4px;
  text-shadow:1px 1px 1px #B9B4B4;
Cursor:pointer;
  }. puzzle-empty {background: #ccc;
Box-shadow:inset 2px 2px 18px; }. btn-reset {box-shadow:inset 2px 2px 18px} </style>

Here I add the CSS code.

Summarize

The above is the entire content of this article, in fact, the game's code is not much, function point is not very complicated, but through Vue to write such a game, help us understand the Vue data-driven response principle, in the simplification of the amount of code while also increasing the readability of the code. I hope this article will help you learn some vue.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.