HTML+CSS+JS to implement the Don't Step on the Whiteboard game

HTML+CSS+JS to implement the Don't Step on the Whiteboard game

Background

I believe everyone has played the game Don't Step on the Whiteboard. This is a simple game built based on HTML5. It can run on both PC and mobile terminals and is adaptable to multiple platforms. Today we use native JS with JQuery to build this game - Don't Step on the Whiteboard.

1. Thought Analysis

The whole page is a large rectangle with a length-to-width ratio of about 3:2. When the game starts, white boards keep falling. Then there are 4 boards in a row, one black board and the other three white boards. The board's click event is bound, and then the color is determined. If it is white, the game ends (Game Over), otherwise the player's points increase by 1.

2. Page Construction

2.1 HTML layer

<div class="wrapper">
        <div id="go">
            <a href="javaScript:void(0)" id="go">Game Start</a>
        </div>
        <div id="main">
</div></div>

2.2 CSS Layer

Before setting the style, you should first understand the general structure, as shown below:

A Don't Step on the Whiteboard Game Based on HTML5_yyds Dry Goods Inventory_02

Global style settings

*{
    margin:0;
    padding:0;
}

Wrapper style settings

.wrapper{
    margin:150px auto;
    width:400px;
    height:600px;
    border:1px solid #ccc;
    position: relative;
    overflow: hidden;
}

Go settings under wrapper

#go{
    width:100%;
    position: absolute;
    top:0;
    text-align: center;
    z-index:99;
}

Start game button style

#go a{
    display:block;
    height:100px;
    width:400px;
    color:cyan;
    background-color: #000000;
    text-decoration: none;
    border-bottom:3px dashed #eee;
    font-size:60px;
    font-weight:600;
}

main(block) style

#main{
    width:400px;
    height:600px;
    position: relative;
    top:-150px;
    /* border:1px solid black; */
}

Set the style for each row of blocks created

.row{
    width:400px;
    height:150px;
}

The style of four small squares in a row

.row div{
   width:99px;
   height:149px;
   border-left:1px solid #222;
   border-bottom:1px solid #222;
   float: left;
   cursor: pointer;
}

After setting the style, the approximate interface is as follows:

A small game based on HTML5 called "Don't step on the whiteboard"

You can see that the interface style is relatively simple. Our idea is that the blocks will automatically land after clicking the Start Game button, so the screen is relatively empty (temporarily).

2.3 JS layer

The js layer is mainly used to control the page to produce dynamic effects, such as generating blocks and moving blocks, etc.

2.3.1 Get Elements

var main = document.getElementById('main'); // Get DOM element var go = document.getElementById('go'); 
var speed = 5, num = 0, timer, flag = true; // Set initial variables var colors = ['red', 'green', 'black', 'blue']; // Set the array to store colors

The array storing colors here does not need to be white. Each initialized block does not set the background color, and it defaults to white.

2.3.2 Create each row of div elements

As we said before, a row consists of four blocks, and the ratio is the same as the large block (3:2). Its length and width are: {width: 100px; height: 150px};

function cDiv() {
    var oDiv = document.createElement('div'); // Get a random number and find a random div for each row and set its color var index = Math.floor(Math.random() * 4);
    
    oDiv.setAttribute('class', 'row'); // Set the row class name for (var j = 0; j < 4; j++) { // for loop generates a row of four divs
        var iDiv = document.createElement('div');
        oDiv.appendChild(iDiv); //Insert each small div into each row}
    
    if (main.childNodes.length == 0) { // Insert the newly generated row based on whether there are child elements in the parent main.appendChild(oDiv); // If the parent is empty, insert directly } else {
        main.insertBefore(oDiv, main.childNodes[0]); // If the parent has elements, insert the newly generated row to the front of the existing number of rows} 
    var clickDiv = main.childNodes[0].childNodes[index]; // Set the colored div in a row according to the random number
    clickDiv.setAttribute('class', 'i'); // Set the class name of this element as the mark to be clicked clickDiv.style.backgroundColor = colors[index]; // Set the background color at the same time}

2.3.3 Click event function encapsulation

function bindEvent() {
    main.addEventListener('click', function (event) { // Add a click event to mainif (flag) { // Determine whether it is clickable based on the flag valuevar tar = event.target; // Get the source event of the clickif (tar.className == 'i') { // Determine whether the clicked block is coloredtar.style.backgroundColor = '#bbb'; // Change the background colortar.classList.remove('i'); // Remove the class namenum++; // Count++
            } else {                
                alert('Game over, score: ' + num); // If you click on the white block, the game is over clearInterval(timer);
                flag = false;
            }            
            if (num % 10 == 0) { // If the current score is a multiple of 10, speed++
                speed++;
            }
        }
    })
}

2.3.4 Block movement function encapsulation

function move() {
    clearInterval(timer); 
    timer = setInterval(function () { // Set the timer var step = parseInt(main.offsetTop) + speed; // Use the top value to move the main area main.style.top = step + 'px';
        if (parseInt(main.offsetTop) >= 0) { // If the main area moves to the visible area, create a new row of elements cDiv();
            main.style.top = '-150px'; // Also move the main area above the visible area}
        var len = main.childNodes.length; // Get the number of rows in the main area if (len == 6) { // If the number of rows in the main area is 6, a new row is generated above and below the four rows in the display area for (var i = 0; i < 4; i++) { // Traverse each div in the last row
                
                if (main.childNodes[len - 1].children[i].classList.contains('i')) { // If there is one that contains the game over that has not been clicked alert('Game over, score: ' + num);
                    clearInterval(timer);
                    flag = false; // You can't click again after the game ends}
            }
            
            main.removeChild(main.childNodes[len - 1]); // Remove each row after display}
    }, 20)
    bindEvent(); // click event}

The first sentence in the function is clearInterval(timer); to prevent multiple timers from being opened;

A Don't Step on the Whiteboard Game Based on HTML5_yyds Dry Goods Inventory_04

2.3.5 Game Start

// Click the start button to start moving and creating each row of elements function clickStart() {
    go.addEventListener('click', function () {
        go.style.display = 'none';
        move();
    });
}
clickStart();

The general effect is shown in the figure:

A don't step on the whiteboard game based on HTML5_native js_05

This is the interface using the built-in browser in HbuilderX. The game ending effect is shown in the figure above;

Conclusion

In this article, we use native js to create a simple touch screen game - don't step on the whiteboard, and make some simple changes to the game. In general, we first need to set up the general structure and style of the game interface, and then use native js to control the movement and clicks of the blocks, and finally present a suitable and complete interface effect; those who are interested can try it.

This is the end of this article about how to use html+css+js to implement the "Don't Step on the Whiteboard" game. For more related html+css+js "Don't Step on the Whiteboard" game content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • js html5 css Tetris game reappearance
  • JavaScript HTML5 canvas to realize brick-breaking game

<<:  Teach you how to quickly install Nginx in CentOS7

>>:  Div nested html without iframe

Recommend

Share the pitfalls of MySQL's current_timestamp and their solutions

Table of contents MySQL's current_timestamp p...

MySQL 5.7.18 Installer installation download graphic tutorial

This article records the detailed installation tu...

How to generate PDF and download it in Vue front-end

Table of contents 1. Installation and introductio...

MySQL 5.7.20 free installation version configuration method graphic tutorial

I have seen many relevant tutorials on the Intern...

Detailed explanation of the implementation of shared modules in Angular projects

Table of contents 1. Shared CommonModule 2. Share...

js to implement web calculator

How to make a simple web calculator using HTML, C...

Detailed explanation of several methods of deduplication in Javascript array

Table of contents Array deduplication 1 Double-la...

3 Tips You Must Know When Learning JavaScript

Table of contents 1. The magical extension operat...

Simple usage examples of MySQL custom functions

This article uses examples to illustrate the usag...

JavaScript navigator.userAgent obtains browser information case explanation

The browser is probably the most familiar tool fo...

js to call the network camera and handle common errors

Recently, due to business reasons, I need to acce...

VMware virtualization kvm installation and deployment tutorial summary

Virtualization 1. Environment Centos7.3 Disable s...

A brief discussion on React Component life cycle functions

What are the lifecycle functions of React compone...

Analysis of idea compiler vue indentation error problem scenario

Project scenario: When running the Vue project, t...