Home  >  Article  >  Web Front-end  >  Javascript implements the "Don't step on the white block" mini-game program_javascript skills

Javascript implements the "Don't step on the white block" mini-game program_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:30:341542browse

Recently, a friend asked me to use JS to help me imitate a small game program called Don’t Step on White Blocks. However, the source code he gave me was cumbersome and had no comments, making it difficult to understand. So I made it myself based on my own ideas. This small game mainly uses JS to operate DOM and arrays.

Program idea: As shown in the figure: Set the CSS of the game area to relative positioning and overflow hiding; there are 24 squares arranged on the two "game boards", one black square is randomly generated in each row, and the "game board" faces Scroll down and display alternately, store the black block position of each operation panel into an array, and pop out the array for comparison every time you click (I think the highlight is here...).

Here is the GitHub address of the game. You can go there and click the Download ZIP button on the far right of the middle menu to download it to your desktop. It contains HTML and JS, no server required.

Download address

The following is the specific implementation, with comments on key parts.

HTML part:

<!DOCTYPE html>

<html>

<head><title>别踩白块</title></head>

<body>

<div id="gameZone"><div id="boardb" style="position: absolute;top: 0px;"></div></div>//初始化一个boardb,使ab同时存在

</body>

</html>

CSS part:

Copy code The code is as follows:
*{margin: 0px;padding: 0px;box-sizing: border -box;} //Simple reset, and use box-sizing to set the box size and calculate the border, which is convenient for calculating the position of the small box later

#gameZone{width: 302px;height: 602px;border: 1px solid green;margin: 20px auto;position: relative;overflow: hidden;} //Game area, two more pixels are to remove the border. Enough space of 300*600

.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 part:

Here is an introduction to the functions:

Global variable initialization

var loc=600;//黑块落地失败判定

var count=0;//初始化击中黑块总数

var locArr=[];//初始化游戏板上黑块位置的

var order=(function(){

    var ord="A";

    return function(){

    if(ord=='boarda')ord='boardb';

    else ord='boarda';

    return ord;

}

})()

//Use the closure function to make the IDs of the game boards created each time boarda and boardb. In fact, you can also use a global variable, but it is a bit more formal. . .

Function to determine the result of each click

function judge(){

    var num=this.id.substr(3)//获取元素的ID号

    if(num!=locArr.pop()){ //与位置数组pop出的对比

        clearTimeout(timer);

        alert("你的得分为:"+count+"分!");

        return; //失败清除定时器,结算分数。

    }else{

        loc+=100; 

        this.style.background="silver";

        count+=1;//成功将落地标志加方格的高度,将方格背景色改变一下,击中数+1

    }

    if(count!=0&&count%15==0){

        clearTimeout(timer);

        newtimer=50-count/15*5;

        timer=setInterval('fall()',newtimer);

    }//每击中15个后将速度加快一点,这个式子可自行定义。

}

Generate a random number for the position of the small black box in the big box. This function is called every time the game board is created, and the position of the small black box is defined based on the generated number

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 be scrolled down above the game area, and PUSHs the numbers in the black part into locArr

function drawBoard(){

    var temArr=generateRand();//这里应用一个临时的位置数组,为了防止两块游戏板之间的位置冲突。

    locArr=temArr.concat(locArr);//将临时数组相连到全局位置数组中

    var board=document.createElement('div');

    board.setAttribute('id',order());

    board.style.position="absolute";

    board.style.top='-600px';

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

        var ele=document.createElement('div');

        ele.setAttribute('id',"ele"+i);

        if(temArr.indexOf(i)>-1){  //判断当前创建的小方块的ID序列是否属于临时位置数组

            ele.setAttribute('class','squareBlack')

        }else{

            ele.setAttribute('class','square');

        }

        ele.addEventListener('click',judge,false); //给每一个小方格添加点击判定函数judge

        board.appendChild(ele);

    }

    var gameZone=document.getElementById('gameZone');

    gameZone.appendChild(board);

}

Find the two game boards that exist in the script and make them scroll down

function fall(){

    gameZone=document.getElementById('gameZone');

    var boarda=document.getElementById('boarda');//因为ab两个游戏板全局一直存在,所以不需要定义找不到时的逻辑

    var anowtop=parseInt(boarda.style.top);//因为获取到的top位置是xxxpx类型,所以用一个parseInt()将其转换为整数便于处理。

    if(anowtop==595){ //这里数目为595而不是600是因为在这一帧删除后,下一帧正好600px,刚好使两块游戏板衔接完好。

        gameZone.removeChild(boarda);

        drawBoard();//删除游戏区域的游戏板,并在最上方新生成一个。

    }

    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("你的得分为:"+count+"分!");

        return;

    } //每一帧将落地判定减5,当落地判定为0时表示落地,结算分数。

}

Write the main call in the window.onload function, so that the function can be called after the game area of ​​the page is loaded.

window.onload=function(){

    drawBoard();

    fall();

    var timer=setInterval('fall()',50);

}

Game Extensions:

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

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

Add scores, rankings, etc.: Use ajax to connect to the server, write the results to the database after the game is over, and reference the rankings in the data.

Change to arcade mode: remove the timing and modify the judge function so that it drops by a small square each time you click on the game board. Set the total number, start timing, and end timing.

Statement:
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