JS implements a simple brick-breaking pinball game

JS implements a simple brick-breaking pinball game

This article shares the specific code of JS to implement the brick-breaking pinball game for your reference. The specific content is as follows

Written in native JS, there are still some flaws. The code can be used directly by copying it into HTML

The speed is random because it involves horizontal and vertical speeds, so the speed value of the ball displayed is their sum (cube and square root).
Press Enter or left-click on the slider to start the game. Use the mouse to slide or keyboard A (left) or D (right) to control the direction of the slider to catch the ball.
The purpose of this small demo is mainly to exercise logical ability:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>document</title>
<style>
.container{
    width: 500px;
    height: 500px;
    border:1px solid #000;
    margin:auto;
    position:relative;
}
.brickBox{
    width: 500px;
    height: 300px;
    /* background-color: yellowgreen; */
    position:absolute;
    left: 0;
    top: 0;
}
.ball{
    width: 15px;
    height: 15px;
    background-color:purple;
    border-radius:50%;
    position:absolute;
    bottom:30px;
    left:235px;
    /* margin-left:-15px; */
}
.slider{
    width: 150px;
    height: 30px;
    background-color: #00f;
    position:absolute;
    /* left:50%; */
    left:175px;
    /* margin-left:-75px; */
    bottom:0;
}
</style>
</head>
<body>
<div class="container">
    <div class="brickBox"></div>
    <div class="ball"></div>
    <div class="slider"></div>
</div>
<div style="margin-left: 40%;font-size: 25px;">Current speed: <span id="speed"></span> </div>
<div style="margin-left: 40% ;font-size: 25px;">Current number of blocks destroyed: <span id="count"></span> </div>

</body>
<script>
// Get all current tags var container = document.querySelector('.container')
var brickBox = container.querySelector('.brickBox')
var ball = container.querySelector('.ball')
var slider = container.querySelector('.slider')
// Dynamically create bricks // Define brick size var brickWidth = 50;
var brickHeight = 15;
// Calculate the number of bricks var brickNum = brickBox.clientWidth * brickBox.clientHeight / (brickWidth * brickHeight)
// console.log(brickNum);
var brickColNum = brickBox.clientWidth / brickWidth
// Create according to quantity for(var i=0;i<brickNum;i++){
    var div = document.createElement('div')
    setStyle(div,{
        width:brickWidth + "px",
        height:brickHeight + "px",
        backgroundColor:getColor(true),
        position:'absolute',
        top:parseInt(i/brickColNum)*brickHeight + 'px',
        left:(i%brickColNum)*brickWidth + 'px'
    })
    brickBox.appendChild(div)
}


// Click the slider to make the ball start moving // Define the horizontal and vertical movement values ​​var speedX = getRandom(1,8);
var speedY = getRandom(1,8);
document.querySelector("#speed").innerHTML = Math.sqrt(Math.pow(speedX,2)+Math.pow(speedY,2))
var timer;
//Click to move slider.onclick = move;
//Enter key starts the pop-up function move(){
    var count=0;
    clearInterval(timer)
    timer = setInterval(function(){
        // Start moving // Get the left and top of the ball
        let left = ball.offsetLeft;
        let top = ball.offsetTop;
       
        // Let left and top increase speed // The ball collides with the slider if (boom (slider, ball)) {
            speedY = -speedY
        }
        // The small ball collides with the big box if(left<=0 || left>=container.clientWidth - ball.offsetWidth){
            speedX = -speedX
        }
        if(top<=0){
            speedY = -speedY
        }
        // Check if all bricks and balls collide for(let i=0;i<brickBox.children.length;i++){
            if(boom(brickBox.children[i],ball)){
                
                speedY = -speedY
                brickBox.removeChild(brickBox.children[i]);
                count++;
            }
           
            
        }
        console.log(count)
        document.querySelector("#count").innerHTML=count
        // GAME OVER
        if(top>=container.clientHeight-ball.offsetHeight){
            clearInterval(timer)
            if(confirm("GAME OVER, whether to play again")){
   location.reload();
  }else{alert('your final score'+count)}
        }
        left += speedX
        top += speedY
        // Set the left and top of the ball
        ball.style.left = left + "px"
        ball.style.top = top + "px"
    },20)
}

// Let the slider follow the mouse movement slider.onmouseover = function(){
    document.onmousemove = function(e){
        var e = e || window.event;
        var x = e.pageX;
        var l = x - container.offsetLeft - 1 - slider.offsetWidth / 2
        if(l<0){
            l = 0
        }
        if (l > container.clientWidth - slider.offsetWidth) {
            l = container.clientWidth - slider.offsetWidth
        }
        slider.style.left = l + "px"
    }
}
//Let the slider move with the left and right keyboards window.onload = function(){
    document.onkeydown = e=>{
        var e = e || window.event;
        var keycode = e.keyCode || e.which;
        var keyword = String.fromCharCode(keycode).toLowerCase();
        if(keycode==13){
            move();
        }
       if(keyword=='a'){
           console.log("1111")
        slider.style.left = slider.offsetLeft-15+"px"
       }else if(keyword=='d'){
        console.log("222")
           slider.style.left=slider.offsetLeft+15+"px"
       }
       console.log(slider.offsetLeft)
        
        
    }
    
}
// Encapsulate the collision detection function function boom(node1,node2){
    // There are only 4 possibilities for not colliding if(node1.offsetLeft+node1.offsetWidth<node2.offsetLeft || node1.offsetTop+node1.offsetHeight<node2.offsetTop || node2.offsetLeft+node2.offsetWidth<node1.offsetLeft || node2.offsetTop+node2.offsetHeight<node1.offsetTop){
        return false;
    }else{
        return true;
    }
}
// Encapsulate the function of getting random color function getColor(hex=true){
    if(hex){
        var color = '#'
        for(var i=0;i<3;i++){
            var rgb = getRandom(256).toString(16);
            rgb = rgb.length===1?'0'+rgb:rgb;
            color += rgb
        }
        return color;
    }
    return `rgb(${getRandom(256)},${getRandom(256)},${getRandom(256)})`
}
// Encapsulate the function of setting style function setStyle(ele,styleObj){
    for(var attr in styleObj){
            ele.style[attr] = styleObj[attr]
    }
}
// Encapsulate the function of getting random numbers function getRandom(a,b=0){
    var max = Math.max(a,b);
    var min = Math.min(a,b)
    return Math.floor(Math.random() * (max-min)) + min
}
</script>
</html>

The effect diagram is shown in the figure

The style is a little ugly without the plug-in.
Then there is a bug that the left and right arrow keys do not have an end value set. Occasionally there will be a loss of positional precision causing the ball to twitch on the slider.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • javascript implements web version of pinball game
  • js implements a small pinball game with points
  • Example of using native JS to achieve the effect of multiple balls colliding and rebounding
  • JS realizes the elastic collision effect of the ball
  • Non-html5 implementation of js version of pinball game sample code
  • Native js to realize bouncing ball

<<:  Detailed steps for Python script self-start and scheduled start under Linux

>>:  Unzipped version of MYSQL installation and encountered errors and solutions

Recommend

vue+element custom query component

This article mainly introduces the Vue project. O...

MySQL log trigger implementation code

SQL statement DROP TRIGGER IF EXISTS sys_menu_edi...

Win32 MySQL 5.7.27 installation and configuration method graphic tutorial

The installation tutorial of MySQL 5.7.27 is reco...

Implementation of mysql backup strategy (full backup + incremental backup)

Table of contents Design scenario Technical Point...

Implementation example of video player based on Vue

When the existing video player cannot meet the ne...

How to modify the default encoding of mysql in Linux

During the development process, if garbled charac...

MySQL REVOKE to delete user permissions

In MySQL, you can use the REVOKE statement to rem...

How to debug loader plugin in webpack project

Recently, when I was learning how to use webpack,...

The process of SSH service based on key authentication in Linux system

As we all know, SSH is currently the most reliabl...

A brief analysis of MySQL's lru linked list

1. Briefly describe the traditional LRU linked li...

How to use squid to build a proxy server for http and https

When we introduced nginx, we also used nginx to s...

How to use mysqldump to backup MySQL data

1. Introduction to mysqldump mysqldump is a logic...

A simple example of using Vue3 routing VueRouter4

routing vue-router4 keeps most of the API unchang...