js 面向对象 打气球小游戏
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>无标题文档</title> <style> * { margin:0; padding:0; } html,body { height:100%; background-color:#ccc; } div { width:250px; height:333px; position:absolute; background: url(img/ballons.png) no-repeat 0px 0; } </style> </head> <body> <!--<div></div>--> <h2></h2> <h2></h2> <script> var balloons = []; var allScore = 0; /*面向对象创建气球的构造函数*/ function Balloon(){ this.dom = null; this.x = 0; this.y = 0; this.score = 0; this.init(); balloons.push(this); this.bindEvent(); } Balloon.prototype.init = function(){ this.dom = document.createElement('div'); document.body.appendChild(this.dom); this.x = parseInt(Math.random()*(document.documentElement.clientWidth-250)); this.y = document.documentElement.clientHeight; this.score = parseInt(Math.random()*12)+1; //[1~13); this.dom.style.left = this.x+"px"; this.dom.style.top = this.y+"px"; var curX = -((this.score-1)%4)*250; var curY = -parseInt(((this.score-1)/4))*333; this.dom.style.backgroundPosition = curX+"px "+curY+"px"; /* 1 2 3 4 (0 -250 -250*2 250*3) 0 5 6 7 8 (0 -250 -250*2 250*3) -333 9 10 11 12 (0 -250 -250*2 250*3) -333*2 */ }; Balloon.prototype.bindEvent = function(){ var _this = this; this.dom.onclick = function(){ /*每次点击计算分数,下树,从数组中下线*/ allScore += _this.score; _this.goDied(); }; } Balloon.prototype.update = function(){ this.y -= this.score*3; if(this.y < -333){ this.goDied(); } this.dom.style.top = this.y+"px"; }; Balloon.prototype.goDied = function(){ document.body.removeChild(this.dom); for(var i=0;i<balloons.length;i++){ if(balloons[i] == this){ balloons.splice(i,1); } } }; var allTime = 20; var iframe = 0; /*给new 出来的每一个this对象添加对应的属性 每秒创建4个气球 */ var timer = setInterval(function(){ iframe++; if(iframe %10 == 0){ allTime--; for(var i=0;i<4;i++){ new Balloon(); } } for(var i=0;i<balloons.length;i++){ balloons[i]&&balloons[i].update(); } document.getElementsByTagName('h2')[0].innerHTML = "你剩余的时间为:"+allTime+"秒"; document.getElementsByTagName('h2')[1].innerHTML = "你目前的分数:"+allScore+"分"; if(!allTime){ alert("Game over ,你的总分数为:"+allScore+"分"); clearInterval(timer); } },100); </script> </body> </html>
图片见文件中
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业