Javascript implementation do not step on the white block mini-games

Source: Internet
Author: User
We first saw that the black and white blocks of the unstarted pages were randomly generated, and the black and white blocks remained unchanged when so many pages were not found. Click the Square once to determine whether it is black or white. If it is black, of course, the program also implements a self-subtraction, which is implemented once in the animation, when I move down the page, the box that I clicked to the yellow area will become gray. Recently, a friend asked me to use JS to help me simulate a small game program that I used to step on the white block, however, the source code provided by him is troublesome, without comments, and cannot be understood. I made this small game with my own ideas, mainly using JS to perform DOM and Array Operations.

Program idea: Set the CSS of the game area to relative positioning and overflow to hide. The two "game boards" are arranged with 24 squares, and each black line is randomly generated, the "game board" scroll down and alternately display, store the Black Block position of each operation Board into an array, and pop the array each time you click it for comparison (I think the highlight is here ......).

Here is the GitHub address of the game. You can click the Download ZIP button on the rightmost side of the central menu to Download it to the desktop. HTML and JS require no servers.

The following are specific implementations. The key parts are annotated.

HTML section:

Do not step on the white Block

// Initialize a boardb so that AB exists simultaneously

CSS section:

The Code is as follows:

* {Margin: 0px; padding: 0px; box-sizing: border-box;} // perform a simple reset and use box-sizing to set the box size to calculate the border, easy to calculate the location of small blocks

# GameZone {width: 302px; height: 602px; border: 1px solid green; margin: 20px auto; position: relative; overflow: hidden;} // game region, two more pixels are used to remove enough 300*600 space outside the border.

. Square {width: 75px; height: 100px; float: left; border: 1px solid black ;}

. SquareBlack {width: 75px; height: 100px; border: 1px solid black; float: left; background: black;} // each small square is 75*100, and set the background color of the black small square.

JS section:

Function introduction:

Global variable Initialization

Var loc = 600; // var count = 0 when the Black Block fails to be implemented; // var locArr = [] when the total number of Black Blocks hit during initialization; // initialize the var order = (function () {var ord = "A"; return function () {if (ord = 'boarda') of the Black Block location on the game board ') ord = 'boardb'; else ord = 'boarda'; return ord ;}})()

// Use the closure function to set the ID of the game board created each time to boarda and boardb. In fact, you can use a global variable, but it is a little difficult...

Function for each click to determine the result

Function judge () {var num = this. id. substr (3) // obtain the element id if (num! = LocArr. pop () {// comparison with position array pop clearTimeout (timer); alert ("your score is:" + count +! "); Return; // failed to clear the timer, settlement score. } Else {loc + = 100; this. style. background = "silver"; count + = 1; // The landing sign is successfully added to the height of the square, and the background color of the square is changed, hitting the number + 1} if (count! = 0 & count % 15 = 0) {clearTimeout (timer); newtimer = 50-count/15*5; timer = setInterval ('fall ()', newtimer);} // speed up after 15 hits. This formula can be customized .}

Generates a random number at the location of the black box in the large box. This function is called each time a game board is created. The location of the Black Block is defined based on the number of Black Blocks generated.

function generateRand(){    var numArr=[];    for(var j=0;j<6;j++){        var num=Math.floor(Math.random()*4)+j*4;        numArr.push(num);    }    return numArr;}

Each call generates a game board to scroll down at the top of the game area, and pushes the numbers of the black part to the locArr.

Function drawBoard () {var temArr = generateRand (); // a temporary location array is applied here to prevent location conflicts between the two game boards. LocArr = temArr. concat (locArr); // connects the temporary array to the global position array. var board = document. createElement ('P'); board. setAttribute ('id', order (); board. style. position = "absolute"; board. style. top = '-600px'; for (var I = 0; I <24; I ++) {var ele = document. createElement ('P'); ele. setAttribute ('id', "ele" + I); if (temArr. indexOf (I)>-1) {// determine whether the ID sequence of the currently created small square belongs to the temporary location array ele. setAttribute ('class', 'squareblack')} else {ele. setAttribute ('class', 'square ');} ele. addEventListener ('click', judge, false); // Add the click decision board function to each small square. appendChild (ele);} var gameZone = document. getElementById ('gamezone '); gameZone. appendChild (board );}

Locate the two game boards in the script and scroll them down.

Function fall () {gameZone = document. getElementById ('gamezone '); var boarda = document. getElementById ('boarda'); // because the two game boards of AB always exist globally, you do not need to define the logic var anowtop = parseInt (boarda. style. top); // because the obtained top position is of the xxxpx type, use a parseInt () to convert it to an integer for processing. If (anowtop = 595) {// The number here is 595 instead of 600 because after this frame is deleted, the next frame is exactly 600px, and the two game boards are properly connected. GameZone. removeChild (boarda); drawBoard (); // Delete the game board in the game area and generate a new one at the top. } Anowtop + = 5; boarda. style. top = anowtop + "px"; var boardb = document. getElementById ('boardb'); var bnowtop = parseInt (boardb. style. top); if (bnowtop == 595) {gameZone. removeChild (boardb); drawBoard ();} bnowtop + = 5; boardb. style. top = bnowtop + "px"; loc-= 5; if (loc = 0) {clearTimeout (timer); alert ("your score is: "+ count +" points! "); Return;} // each frame is reduced by 5. When the frame is set to 0, it indicates the landing and settlement score .}

Write the call of the subject in the window. onload function so that the game Area of the page is loaded before calling the function.

window.onload=function(){    drawBoard();    fall();    var timer=setInterval('fall()',50);}

Game extension:

Add page UI: Because the HTML at the beginning is very simple, the UI is also well modified. Set the button and click to trigger the start function.

Change the game difficulty: Modify the setInterval value, modify the number of intervals in the judge function, or optimize the expression of the whereabouts acceleration.

Add score rankings: Use ajax to connect to the server, write the results to the database after the game ends, and reference the ranking list in the data.

Change to Arcade Mode: remove the timer and modify the judge function so that each time you click the game board, the height of a small square is dropped. Set the total number, start timing, and end timing.

Related Article

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.