Still at work? Very boring? Digital Huarong Road play address

Source code address

This is called the preface

At the end. Oh, no, it’s Chinese New Year. I used to have to stand all the way to work, but this morning I sat down. In the New Year, there is always a new thing to learn to welcome the new future, so I chose React, which is said to be the most awesome front-end framework in the universe. I watched the official tutorial for two days on the subway at work, so What. Not see accusers, hence think do what, came across a sister sent a play about digital game hua-rong-dao, don’t stop circle of friends, the game at this year’s brain strongest I have ever seen, but saw two little genius in sliding ah ah slip, feels good, program the ape should play more educational classes, play less what jump jump. So I went to the store to play, playing ok, but there are too many advertisements, and can only play five levels below, it looks not difficult, an idea came to mind, why not take this practice hand to make a Demo, after all, we belong to the wisdom family. After the gossip, let’s get down to business. This article includes, but not only includes, the following:

  • Demo Development environment
  • The secret of digital Huarong Road
  • Let’s talk about the implementation of the algorithm
  • React use experience and easy error points

Demo Development environment

React: 16.2.0

The react – the router – dom: 4.2.2

Webpack: 3.8.1

JS: ES6

CSS: Scss

The React tutorial

The project directory structure (perfect for React getting started) : If you feel good, please leave your star as shown below

The secret of digital Huarong Road

Game shows

In foreign countries, Huarong Daoli is called Puzzle, which translates to “number push”, and the most classic is the solution to the situation of 13, 15, and 14 high prizes in Puzzle15. How to play, a picture is worth a thousand words, simply speaking is to speak the left picture of random selection state, slide into the right picture as shown in the order of state. Personally, it is similar to pushing boxes when I was a child.

Secrets you don’t know

In fact, it took one week and one Monday night to write the random sequence page generation and operation interaction of the Demo, but it took three or four more nights to finish the online version (working in the day and studying in the evening, which is the daily life of the front end). Why? Online, because the base version of the deployment to let girlfriend have a pair of, the results play a third order, have two minutes left in STH over and over again (I fastest is 18 seconds reduction), how so stupid, so come and do, to do again, what’s the matter, no feeling, then go to baidu once, see the problem on zhihu, also really have any solutions, questions address. Look at the picture. We’ll see more later. (Tap the blackboard)

Oh, I see. It is not enough for light to randomly generate a sequence of disorderly Ordinal Numbers. It is necessary to ensure that the sequence has an even number of inversions. So in the generation of random sequence, another process is added to judge the parity of sequence inverse number and adjust it. On the subway in the morning, I kept playing the test, three ok, four OK, five OK, and then again, and again. I thought I was done, but here’s what happened. A figure. Who just said 4th order OK… So again tested for many times, found that three, five is really OK, but four does have bugs. Why, after their own every open game, cut a picture, no solution, mark down, the following is a few pictures of meritorious service.

Odd order (3×3,5×5) : If you move a number up or down, the transposition position is even, so it does not change the parity of the number of inversions of the sequence. Therefore, the generated initial random sequence must have an even number of inversions.

Even order (4×4,6×6) : Shifting a number up or down to an odd position changes the parity of the reverse order of the sequence, changing the parity once up and down, and returning to the original state twice. So you can understand it, roughly even square is even still, it has a digital number is an odd number of slider, so there is a digital exchange will inevitably and empty the slider position, if empty slide block is located in the odd lines (empty slider is not involved in the reverse order of sequence of Numbers of counting), can produce 2 n – 1 time exchange, it will change the sequence of the parity of the number of reverse order; In even rows, there will be 2n swaps, which will not change the parity of the inverse number of the sequence, so it can be summed up in a formula :(whether the initial state of the sequence is even) === (whether the empty row is even), simply to find the xor of these two numbers. The implementation of the final code flow

Let’s talk about the implementation of the algorithm

Generates an out-of-order and non-repeating array of 1 to N numbers

There are many methods, but I know of two, here to share, there are others, please leave a comment, let us progress together. The idea of sequential array randomization is basically to form a sequential array of 1 to N, and then shuffle the array through a loop of 1 to n, with O(n) time. Here’s the code.

    export const disorganize = (length) => {
        const arr = [];
        let temp;
        for (var i = 1; i < length; i++) {
            arr.push(i);
        }
        for (i = 0; i < length; i++) {
            let random = Math.round(Math.random() * (length - 2));
            temp = arr[random];
            arr[random] = arr[i];
            arr[i] = temp;
        }
        return arr;
    };
Copy the code

Random number generation Random number group Generates a random number and checks whether it already exists in the target array. When the array number is N, the purpose is achieved. I do not know the time complexity, the code is as follows:

    export const randomArr = (length) => {
        const arr = [];
        let temp;
        while(arr.length<(length-1)){
            let random = 1+Math.round(Math.random() * (length - 2));
            if(random<length && arr.indexOf(random)===-1){
                arr.push(random);
            }
        }
        return arr;
    };
Copy the code

Although the code looks simpler than the above, its time complexity is O(f(n) at the most and unknown at the worst, so it is recommended that the first method, if there is any problem, please timely point out.

The parity judgment of sequence inversion

The first thing that comes to mind is bubble sort, because bubble sort is the process of determining if two numbers are in reverse order, if they are, they switch, if they are not, and then we move on to the next set of judgments. Therefore, we directly record the number of exchanges as the number of sequence reversals, so as to achieve the desired effect. Of course, this problem can also be done with other sorting methods, and if you understand the principle of sorting, it’s easy to calculate the reverse order of the sequence, and I’m going to directly use the previous bubble sorting algorithm.

const bubbleOrder=(arr)=>{ let i ,j ,count=0; const swap=(tar,lastIndex,newIndex)=>{ let temp = tar[lastIndex]; tar[lastIndex] =tar[newIndex]; tar[newIndex] = temp; count++; } for(i=0; i<arr.length; i++){ for(j=arr.length-1; j>i; j--){ (arr[j]<arr[j-1])&&swap(arr,j-1,j); } } return count; }Copy the code

JS Write a stopwatch

Start-pause-stop-reset is not required, but the first and second steps are required. Of course, there are many methods, but they all depend on setTimeout or setInterval. RequestAnimation should also work. Here to provide a written, of course, ideas from the Internet, but with their own ideas expressed. Based on setInterval and Date objects. The source code is as follows:

Const formatter=(t)=>{const res =t>9? t : '0'+t return res; } let startTime = new Date().getTime(),tPass=0,tOffset=offsetTime||0; This. interId = setInterval(()=> {//this.interId is a hold timer value built under the component, used to pause and stop let tNew = new Date().getTime(),ms,sec,min,timeStr; tPass = tOffset +tNew - startTime; ms = Math.floor(tPass/10 % 100); sec = Math.floor((tPass / 1000) % 60); min = Math.floor((tPass / 1000 / 60) % 60); timeStr = formatter(min)+':'+formatter(sec)+':'+formatter(ms); this.tick(timeStr,tPass); },100)} Tick (timeStr,tPass){this.setState({timePass:tPass, time:timeStr})}Copy the code

React React

The difference between using Vue and React. I hold my head and cry bitterly. Vue hasn’t been on the project for half a year, so I almost forget it.

  • The direct feeling is that Vue is indeed easier to learn than React. Its component-based development mode of template, JS and CSS is closer to the development mode of Template + requireJs commonly used in our previous work.
  • React places more emphasis on JS programming and the overall architecture of the project, and which level is controlled by props. Of course, the componentized design of Route 4.0 emphasizes this more.
  • React is still not as popular as Vue in China. For example, when things go wrong, many of them are only available on stackOverflow.
  • However, whether it is Vue or React, I am familiar with ES6 and OBJECT-ORIENTED programming, and I can get used to both quickly.

In the whole learning process, will be a lot of tutorials in the blackboard out of the pit, and solid step on again, now can be said to have a profound impact. I sorted it out and shared it with you. I would like to be a beginner like me. If I meet the following mistakes, I will not be so confused

Cannot read property ‘setState’ of undefined’

Explanation: The main problem is that the constructor of the component object does not point to this in the constructor binding event handler. Constructor () : this.resetClick = this.resetclick.bind (this);

Cannot read property ‘size’ of undefined’

The constructor of the component object does not pass props. As a result, the component object does not have props. In addition to understanding inheritance, it is important to understand the life cycle of the React component.

you are adding a new property in the Synthetic event Object

React: SyntheticEvent is a dom event proxy written for browser compatibility. You can’t add attributes to react.

Others, continue to add later

A question

In the beginning, I used flex layout for my game box, but when I decided that the boxes inside the box needed to slide, I wanted to do a sliding effect, so I switched to absolute positioning layout, where each box counted its anchor point. As it turns out, I used state to manage the position of each block in the box. However, when I adjust state, the React virtualDom automatically calculates and updates the DOM node. Pure CSS is not good, please give some advice.

conclusion

A few hours before the holiday, the article dragged a few days to finish, a little rushed, there is insufficient place also please point out in time. As for this project, I would like to continue to optimize and expand some functions in the later stage, such as access data recording and NxM steps. If you have ideas, please share them with me at [email protected]. In the end, I would like to give some encouragement to myself who has never given up efforts in 2017. I hope 2018 can be a better year for development. I also wish all comrade-in-arms a happy New Year 2018, see you later !!!!!