Don't step on the implementation of the White block game, jquery implementation

Source: Internet
Author: User

Don't step on the implementation of the White block game, jquery implementation

Reprinted please indicate the source http://www.cnblogs.com/Wxtrkbc/p/5687112.html

Front-end learning is coming to an end, and there is no chance to write anything decent. Then I accidentally think that someone has played a game for me before, I was ridiculed for my hand disability. Now I think it is not difficult to implement this game. So I wrote a small game with jquery last week, just as I wrote 2048 in python at the beginning. Today, I just took the time to write a blog record, which is a summary of my previous studies. If I have never played it, I can go to the next original version to play it. The game is very simple, click black from falling blocks. If you click hundreds of blocks or black blocks are not clicked, the game will end. It is not difficult to implement a game. It is a small knowledge point. At that time, my head was a bit vague, and I couldn't solve a bug after reading it for a long time. Later I saw it when my head woke up the next morning, by the way, I would like to remind myself not to write code when my head is not awake. Well, let's take a look at it for a moment. Here, don't let me talk about css style design...

I. Game html page

The html interface of the game is very simple and consists of four parts,

  • Score title bar,
  • The game interface theme container is a div at the beginning, and then uses jquery to dynamically generate a black and white Lattice
  • Start pause button Column
  • Modal box displayed at game end

Below is the Code Section

<! DOCTYPE html> Iii. jquery implementation

The core of the game is jquery. The main functions are as follows:

  • Game Initialization
  • How to dynamically insert a div row and delete a div row
  • Start to pause button event binding
  • Click hundreds of events and blacklist events during the game process.
  • How the game moves and how it scores
  • How to automatically increase the speed of the whitelist
  • How to determine the game is over

Next let's take a look at the implementation of the initialization code. Before initialization, a function is written to automatically insert a row, and one of the four divs in this row is a random black block for the game to click, there are three white blocks left. How to generate them randomly? How to dynamically create a div requires tips. For details, see the following. After generating a div function, you only need to call it four times in the initialization function.

Function insertDiv () {var rand = Math. floor (Math. random () * 4); // generates a random number ranging from 0 to 3 to determine the position of the Black Block generated $ ("# inner "). prepend ("<div class = 'item'> </div>"); $. each ([0, 1, 2, 3], function (k, v) {if (v = rand) {$ ("# inner. item "). first (). append ("<div class = 'black col'> </div>");} else {$ ("# inner. item "). first (). append ("<div class = 'col'> </div>") ;}} function init () {// initially generates 4*4 div $. each ([0, 1, 2, 3], function () {insertDiv ();});}

What we need to do after Initialization is to make the interface move. Here we write a function. Every time we call this function, the game content will automatically move a few pixels down, then pass the function to the timer to continue sliding down. However, during the fall process, if the falling distance exceeds a row, you need to insert a row again, then delete the row that exceeds the limit and restore the offset to the original position. To speed up the whitelist, you only need to move down and increase each time, the Automatic acceleration behind the game is also based on this. Let's take a look at this part of the code.

Function move () {var ctop = parseInt ($ ("# inner "). offset (). top); ctop + = window. globalSpeed; // custom global variable, the distance from each fall offset $ ("# inner "). offset ({top: ctop}); if (ctop >=114) {insertDiv (); $ ("# inner "). offset ({top: 12}); // just move an item and move it above delDiv ();}}

The next step is to start writing and pause the timer. Here we mainly use the timer. here we need to note that every time we click it, we must first determine whether the timer has been cleared; otherwise, there will be a bug, let's take a look at the code below.

Function bindStart () {$ ("# begin "). mouseover (function () {cursor (this).css ("cursor", 'pointer ');}). click (function () {if (window. globalIsClearT1) {// custom global variable to check whether the timer is clear} else {clearInterval (window. globalT1); // if it is not cleared, clear it first to avoid pressing the start button twice} window. globalT1 = setInterval (move, 30); window. globalStartClick = true; // whether to start the flag of the global variable. Click} only when the flag is started.} function bindStop () {$ ("# stop "). mouseover (function () {cursor (this).css ("cursor", 'pointer ');}). click (function () {clearInterval (window. globalT1); window. globalStartClick = false; window. globalIsClearT1 = true ;})}

Here, let's take a look at how to perform each click, whether to score or not, or if the game is over by mistake. Let's take a look at the code below. There are 4*4 grids on the interface, event delegation is required to determine which white block is clicked. If a Black Block is clicked, change it to a white block and add one point. Otherwise, the game ends when an error occurs.

function bindClick() {    $("#inner").click(function (e) {        if (window.globalStartClick) {            var current = $(e.target);            if (current.hasClass("black")) {                current.removeClass("black");                score();            } else {                gameOver();            }        }    });}

Next, let's take a look at how to calculate the score code and how to achieve automatic acceleration.

Function score () {var score = parseInt ($ ("# score "). text (); if (score % 10 = 0) {window. globalSpeed + = 1; // auto-acceleration after a certain score is obtained} $ ("# score "). text (score + 1 );}

Finally, let's take a look at how to deal with the game when it is over. when the game is over, first pause the game's whereabouts, and then bring up the modal dialog box, asking the user to choose whether to return or re-come. If the game is over again, the score will be cleared, the game interface is cleared, and then the initialization starts at the auto-trigger start button to start the next round of the game,

Function gameOver () {// pause the game and display the modal box $ ("# stop "). trigger ('click'); window. globalIsClearT1 = true; $ (". shadow "). removeClass ('hide '). next (). removeClass ('hide '); $ ("# again "). click (function () {clearInterval (window. globalT1); $ (". shadow "). addClass ('hide '). next (). addClass ('hide '); $ ("# score "). text (0); clearAll (); init (); $ ("# begin "). trigger ('click'); // window. globalT1 = setInterval (move, 30 )});

By now, the entire game is basically implemented, and the game is not complicated, but it should be completely run, and it is not as simple as no bugs. If you are interested, you can also write it, if there is any problem with the above code, you can ask me.

  

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.