原生JS面向对象实现打砖块游戏

作者:异步漫步

时间:2026-10-25

浏览:393

本文介绍如何使用原生JavaScript面向对象编程思想实现一个打砖块小游戏。通过封装组件类,利用随机数控制小球反弹速度与方向,并在碰撞时隐藏砖块元素。代码包含HTML结构、基础组件类及游戏逻辑类,适合学习JS面向对象编程与简单游戏开发。

文章目录

原生JS面向对象实现打砖块游戏

本文分享了一段使用JavaScript实现打砖块小游戏的完整代码示例,供读者参考学习。

该实现采用面向对象编程模式,通过调整JS调用次数即可控制游戏中打砖块的数量。

小球的反弹速度和方向均被赋予随机值。当小球与砖块发生碰撞时,会将砖块的display属性设置为none,从而实现砖块消失的效果。

HTML代码部分如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <script type="module">
        import Brick from "./js/Brick.js";
        //可以通过循环创建多个打砖块游戏模块
        var brick = new Brick();
        brick.appendTo("body");
    </script>
</body>
</html>

JS代码第一部分如下:

export default class Component extends EventTarget{
    elem;
    constructor(){
        super();
        this.elem=this.createElem();
    }
    createElem(){
        if(this.elem) return this.elem;
        let div=document.createElement("div");
        return div;
    }
    appendTo(parent){
        if(typeof parent==="string")parent=document.querySelector(parent);
        parent.appendChild(this.elem);
    }
}

JS代码第二部分如下:

import Component from "./Component.js";

export default class Brick extends Component{
    box;
    ul;
    li;
    fra;//碎片容器
    bubble;//球
    board;//木板
    start;
    lis=[];
    boxWidth=680;
    liWidth=66;
    liHeight=15;
    fy=-1;
    fx=1;
    static NUM=130;
    static ZHENG=1;
    static FU=-1;
    constructor(){
        super();
        Object.assign(this.elem.style,{
            width:"800px",
            height:"500px",
            border:"orange solid 1px",
            margin:"40px 0 0 200px",
            background:"url('./img/2.jpg')",
            // backgroundSize:"contain",
        });
        this.creatCon();
        // this.sortLi();
        this.creatButton();
        this.creatBoardAndBubble();
        document.body.appendChild(this.elem);
        this.sortLi();
        // this.move();
        this.start.addEventListener("click",e=>this.clickHandler(e))
        // document.addEventListener("keydown",e=>this.keyHandler(e));
    }
    //游戏区域box盒子
    creatCon(){
        this.box=document.createElement("div");
        Object.assign(this.box.style,{
            width:"680px",
            fontSize:"55px",
            textAlign:"center",
            lineHeight:"400px",
            height:"400px",
            position:"relative",
            border:"orangered solid 1px",
            margin:"20px 60px",
            // background:"url('./img/0.jpg') ",
            // backgroundSize:"contain",
        })
        this.creatUl();
        this.creatLi();
        this.elem.appendChild(this.box);
    }
    creatUl(){
        this.ul=document.createElement("ul");
        Object.assign(this.ul.style,{
            listStyle:"none",
        })
    }
    //创建所有li
    creatLi(){
        this.fra=document.createDocumentFragment("div");//碎片容器
        for(var i=0;i<Brick.NUM;i++){
            this.li=document.createElement("li");
            Object.assign(this.li.style,{
                width:"66px",
                height:"15px",
                border:"solid 1px #ccc",
                position:"absolute"
            })
            var r=Math.floor(Math.random()*255);
            var g=Math.floor(Math.random()*255);
            var b=Math.floor(Math.random()*255);
            this.li.style.backgroundColor="rgb("+r+","+g+","+b+")";
            this.fra.appendChild(this.li);
            this.lis.push(this.li)
        }
        this.ul.appendChild(this.fra);
        this.box.appendChild(this.ul);
    }
    //创建滑板和小球
    creatBoardAndBubble(){
        this.bubble=document.createElement("div");
        this.board=document.createElement("div");
        Object.assign(this.bubble.style,{
            width:"15px",
            height:"15px",
            backgroundColor: "red",
            borderRadius:"50%",
            position:"absolute",
            bottom: "10px",
            left:"180px",
        })
        Object.assign(this.board.style,{
            width:"150px",
            height:"10px",
            backgroundColor: "orange",
            borderRadius:"5px",
            position:"absolute",
            bottom:"0",
            left:"160px",
        })
        this.box.appendChild(this.bubble);
        this.box.appendChild(this.board);
        // document.addEventListener("keydown",e=>this.keyHandler(e));
    }
    //创建游戏开始按钮
    creatButton(){
        this.start=document.createElement("button");
        Object.assign(this.start.style,{
            marginLeft:"50px",
            width:"100px",
        })
        this.start.textContent="开始游戏";
        this.elem.appendChild(this.start);
    }
    //摆放li
    sortLi(){
        var leftInit = 0; 
        var topInit = 0; 
        this.cols = parseInt(this.boxWidth / (this.liWidth+2));
        for(var i = 0 ; i < Brick.NUM ; i++){
            var x = leftInit * (this.liWidth+2);
            var y = topInit;
            this.lis[i].style.left = x + "px";
            this.lis[i].style.top = y + "px";
            leftInit++;
            //换行
            if ((i+1)%this.cols==0) {
                leftInit = 0;
                topInit = topInit + this.liHeight;
            }
        }
    }
    clickHandler(e){
        document.addEventListener("keydown",e=>this.keyHandler(e));
        this.move();
    }
    keyHandler(e){
            //左键
            if( e.keyCode === 37 ){
                this.board.style.left = this.board.offsetLeft - 15 + "px";
                if (this.board.offsetLeft<=0) {
                    this.board.style.left = 0;
                }
            }
            //右键
            if( e.keyCode === 39 ){
                this.board.style.left = this.board.offsetLeft + 15 + "px";
                if(this.board.offsetLeft>=this.box.offsetWidth-this.board.offsetWidth){
                    this.board.style.left = this.box.offsetWidth-this.board.offsetWidth +"px";
                }
            }
    }
    move(){
        var timer = setInterval(()=>{
            this.bubble.style.left = this.bubble.offsetLeft + this.fx + "px";
            this.bubble.style.top = this.bubble.offsetTop + this.fy + "px";
            //上边界
            if(this.bubble.offsetTop<=0){
                this.fy = 1;
            }
            //左边界
            if(this.bubble.offsetLeft<=0){
                this.fx = 1;
            }
            //右边界
            if(this.bubble.offsetLeft>=this.box.offsetWidth-this.bubble.offsetWidth){
                this.fx = -1;
            }
            //小球 反弹
            if( this.bubble.offsetTop+this.bubble.offsetHeight >= this.board.offsetTop&&this.bubble.offsetLeft>=this.board.offsetLeft ){
                if(this.bubble.offsetLeft+this.bubble.offsetWidth<=this.board.offsetLeft+this.board.offsetWidth){
                    this.fy = -1;
                }
            if(this.bubble.offsetTop >= this.box.offsetHeight-this.bubble.offsetHeight){
                this.box.appendChild(document.createTextNode("GAME OVER!"));
                clearInterval(timer);
            }
            //小球和砖块的碰撞   以小球为基准  遍历所有砖块
            for( var i =0; i < Brick.NUM ; i++){
                if(this.bubble.offsetTop<=this.lis[i].offsetTop+this.lis[i].offsetHeight&&this.bubble.offsetLeft>=this.lis[i].offsetLeft&&this.bubble.offsetLeft+this.bubble.offsetWidth<=this.lis[i].offsetLeft+this.lis[i].offsetWidth){
                            // this.fy = 3;
                            this.fx=Math.floor(Math.random()*6-3);//
                            this.fy=Math.floor(Math.random()*5+1);
                            console.log(this.fy)
                            this.lis[i].style.display = "none";
                }
            }
        },8);
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章