文章目录

  • 一、效果演示
    • 设计思路
  • 二、鼠标版飞机大战代码展示
    • 1.HTML结构代码
    • 2.CSS样式代码
    • 3.JavaScript代码
      • js.js文件
      • plane.js文件
  • 三、键盘版飞机大战代码展示
    • 1.HTML结构代码
    • 2.CSS样式代码
    • 3.JavaScript代码
  • 四、代码资源分享

一、效果演示

利用html,css,js制作出飞机大战的简易版
需要代码的小伙伴可以在文章末尾资源自行下载,下载打开运行在浏览器即可游戏,本篇资源分享分为两个版本,一个是键盘版本(awsd移动和k攻击),一个是鼠标移动版

设计思路

  1. 在游戏进行界面中,通过鼠标操控自己方飞机(仅一架),在初始化时就进行无限制的匀速发射子弹。

  2. 在游戏进行界面中,左上方有得到的分数显示,敌方飞机有三种类型(小,中,大),他们的形状,大小,击落的分数各不同,以合适的速度控制它们的数量,以及运动的速度。

  3. 在进行游戏的过程中点击鼠标左键会进入游戏暂停界面,有重新开始,回到主页,继续三个选项。当游戏结束时,会弹出游戏分数框,有继续按钮,点击回到主页。

二、鼠标版飞机大战代码展示

1.HTML结构代码

<body><div id="plane"><span>分数:<strong style="font-weight: normal;">0</strong></span></div><script type="text/javascript" src="js.js"></script><script type="text/javascript" src="plane.js"></script>
</body>

2.CSS样式代码

<style type="text/css">*{padding:0px;margin:0px;}#plane{width: 320px;height: 568px;background: url(img/background.png);position: relative;margin:50px auto 0;cursor: none;overflow: hidden;}#plane span{position: absolute;right:10px;top:5px;}</style>

3.JavaScript代码

js.js文件

//缓冲运动
function getStyle(obj, attr) {if (obj.currentStyle) {return obj.currentStyle[attr];} else {return getComputedStyle(obj)[attr];}
}function startMove(obj, json, fn) {var cur = 0;var timer = null;var speed = null;clearInterval(obj.timer)obj.timer = setInterval(function() {var bstop = true;for (var attr in json) {if (attr == 'opacity') {//求初始值cur = Math.round(getStyle(obj, attr) * 100);} else {cur = parseInt(getStyle(obj, attr));}speed = (json[attr] - cur) / 8;speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed); if (cur != json[attr]) {bstop = false;if (attr == 'opacity') {obj.style[attr] = (cur + speed) / 100;obj.style.filter = 'alpha(opacity=' + (cur + speed) + ')';} else {obj.style[attr] = cur + speed + 'px';}}}if (bstop) {clearInterval(obj.timer);fn && fn();}}, 30);
}//通过类名获取元素
function getClass(oClass, oParent) {var oP = oParent || document;var arr = [];var aEle = oP.getElementsByTagName('*');var reg = new RegExp('\\b' + oClass + '\\b');for (var i = 0; i < aEle.length; i++) {if (reg.test(aEle[i].className)) {arr.push(aEle[i]);}}return arr;
}//取任意的随机数,范围是min-max之间
function getrandom(min,max){return Math.floor(Math.random()*(max-min+1))+min;
}

plane.js文件

//我方飞机构造函数
var planeBox = document.getElementById('plane');
var planescore = document.getElementsByTagName('strong')[0];
var zscore = 0;function Myplane(w, h, imgsrc, boomsrc) {this.w = w;this.h = h;this.imgsrc = imgsrc;this.boomsrc = boomsrc;this.createMyplane();
}//创建我方飞机
Myplane.prototype.createMyplane = function() {this.plane = document.createElement('img');this.plane.src = this.imgsrc;this.plane.style.cssText = 'width:' + this.w + 'px;height:' + this.h + 'px;position:absolute;left:' + (planeBox.offsetWidth - this.w) / 2 + 'px;top:' + (planeBox.offsetHeight - this.h) + 'px;';planeBox.appendChild(this.plane);this.move();this.shoot();
};//我方飞机移动
Myplane.prototype.move = function() {var that = this;document.onmousemove = function(ev) {var ev = ev || window.event;that.oLeft = ev.clientX - plane.offsetLeft - that.w / 2;that.oTop = ev.clientY - plane.offsetTop - that.h / 2;if (that.oLeft < 0) {that.oLeft = 0;} else if (that.oLeft >= plane.offsetWidth - that.w) {that.oLeft = plane.offsetWidth - that.w}if (that.oTop < 0) {that.oTop = 0;} else if (that.oTop >= plane.offsetHeight - that.h) {that.oTop = plane.offsetHeight - that.h;}that.plane.style.left = that.oLeft + 'px';that.plane.style.top = that.oTop + 'px';return false;}
};
//我方飞机发射子弹
Myplane.prototype.shoot = function() {var that = this;document.onmousedown = function(ev) {var ev = ev || window.event;if (ev.which == 1) {bulletshoot();that.timer = setInterval(bulletshoot, 200);function bulletshoot() {var bullet = new Bullet(that.plane.offsetLeft + that.w / 2 - 3, that.plane.offsetTop - 14, 6, 14, 'img/bullet.png');}}return false;}document.onmouseup = function(ev) {var ev = ev || window.event;if (ev.which == 1) {clearInterval(that.timer);}}document.oncontextmenu = function() {return false;}
};//子弹的构造函数
function Bullet(x, y, w, h, imgsrc) {this.x = x; //位置this.y = y;this.w = w; //尺寸this.h = h;this.imgsrc = imgsrc;this.createBullet();
}//创建子弹
Bullet.prototype.createBullet = function() {this.bullet = document.createElement('img');this.bullet.src = this.imgsrc;this.bullet.style.cssText = 'width:' + this.w + 'px;height:' + this.h + 'px;position:absolute;left:' + this.x + 'px;top:' + this.y + 'px;';planeBox.appendChild(this.bullet);this.move();
}//子弹移动
Bullet.prototype.move = function() {var that = this;this.timer = setInterval(function() {that.y -= 5;if (that.y <= -that.h) {clearInterval(that.timer);planeBox.removeChild(that.bullet);}that.bullet.style.top = that.y + 'px';that.hit();}, 20);
};Bullet.prototype.hit = function() {var allEnemy = document.getElementsByClassName('planeEnemy');for (var i = 0; i < allEnemy.length; i++) {if ((this.x + this.w) >= allEnemy[i].offsetLeft && this.x <= (allEnemy[i].offsetLeft + allEnemy[i].offsetWidth) && this.y <= (allEnemy[i].offsetTop + allEnemy[i].offsetHeight)) {clearInterval(this.timer);try{planeBox.removeChild(this.bullet);}catch(e){}allEnemy[i].hp--;allEnemy[i].checkhp();}}
};//敌方飞机的构造函数
function Enemyplane(x, y, w, h, imgsrc, boomsrc, speed, hp, score) {this.x = x; //位置this.y = y;this.w = w; //尺寸this.h = h;this.imgsrc = imgsrc;this.boomsrc = boomsrc;this.speed = speed;this.hp = hp;this.score = score;this.createEnemy();
}//创建敌机
Enemyplane.prototype.createEnemy = function() {var that = this;this.enemy = document.createElement('img');this.enemy.src = this.imgsrc;this.enemy.className = 'planeEnemy'; //通过设置类名,方便后面获取this.enemy.style.cssText = 'width:' + this.w + 'px;height:' + this.h + 'px;position:absolute;left:' + this.x + 'px;top:' + this.y + 'px;';planeBox.appendChild(this.enemy);this.enemy.hp = this.hp; //变化的this.enemy.score = this.score; //变化的this.enemy.checkhp = function() { //this==this.enemy if (this.hp <= 0) {clearInterval(this.timer);this.className = '';this.src = that.boomsrc;setTimeout(function() {planeBox.removeChild(that.enemy);}, 1000);zscore += this.scoreplanescore.innerHTML = zscore;}}this.move();
}Enemyplane.prototype.move = function() {var that = this;this.enemy.timer = setInterval(function() {that.y += that.speed;if (that.y >= planeBox.offsetHeight) {clearInterval(that.enemy.timer);planeBox.removeChild(that.enemy);}that.enemy.style.top = that.y + 'px';that.enemyhit();}, 50);
}Enemyplane.prototype.enemyhit = function() {if ((this.y + this.h) >= myplane.oTop && this.y <= (myplane.oTop + myplane.h) && (this.x + this.w) > myplane.oLeft && this.x <= (myplane.oLeft + myplane.w)) {var allEnemy = document.getElementsByClassName('planeEnemy');for (var i = 0; i < allEnemy.length; i++) {clearInterval(allEnemy[i].timer);}clearInterval(timer);document.onmousedown = null;document.onmousemove = null;myplane.plane.src = myplane.boomsrc;setTimeout(function() {alert('game over!!');window.location.reload(); //重刷新}, 3000);}
}var myplane = new Myplane(66, 80, 'img/myplane.gif', 'img/myplaneBoom.gif');for (var i = 0; i < getrandom(1, 2); i++) { //随机创建各类飞机var timer = setInterval(function() {var num = getrandom(1, 20); //1-15 小飞机  16-20 中飞机  20打飞机if (num >= 1 && num < 15) {var enemy = new Enemyplane(getrandom(0, planeBox.offsetWidth - 34), -24, 34, 24, 'img/smallplane.png', 'img/smallplaneboom.gif', getrandom(3, 5), 1, 1);} else if (num >= 15 && num < 20) {var enemy = new Enemyplane(getrandom(0, planeBox.offsetWidth - 46), -60, 46, 60, 'img/midplane.png', 'img/midplaneboom.gif', getrandom(2, 4), 3, 5);} else if (num == 20) {var enemy = new Enemyplane(getrandom(0, planeBox.offsetWidth - 110), -164, 110, 164, 'img/bigplane.png', 'img/bigplaneboom.gif', getrandom(1, 2), 10, 10);}}, 1000)
}

三、键盘版飞机大战代码展示

1.HTML结构代码

<body><div class="gamebox"><span>分数:<em>0</em></span></div><script type="text/javascript" src="plane.js"></script>
</body>

2.CSS样式代码

 <style type="text/css">* {padding: 0px;margin: 0px;    }.gamebox{width: 320px;height:568px;background: url(img/background.png) repeat-y;margin:20px auto;position: relative;cursor: none;overflow: hidden;}.gamebox span{position: absolute;right:10px;top:10px;}.gamebox span em{font-style: normal;}</style>

3.JavaScript代码

;
(function() {var gamebox = document.querySelector('.gamebox');var oEm = document.querySelector('em');var zscore = 0;//1.让背景运动起来var bgposition = 0;var bgtimer = setInterval(function() {bgposition += 2;gamebox.style.backgroundPosition = '0 ' + bgposition + 'px';}, 30);//2.我方飞机的构造函数function Myplane(w, h, x, y, imgurl, boomurl) { //w,h宽高 x,y位置  imgurl和boomurl我方飞机的图片路径this.w = w;this.h = h;this.x = x;this.y = y;this.imgurl = imgurl;this.boomurl = boomurl;this.createmyplane()}//2.1创建我方飞机Myplane.prototype.createmyplane = function() {this.myplaneimg = document.createElement('img');this.myplaneimg.src = this.imgurl;this.myplaneimg.style.cssText = `width:${this.w}px;height:${this.h}px;position:absolute;left:${this.x}px;top:${this.y}px;`;gamebox.appendChild(this.myplaneimg);//飞机创建完成,执行运动和发射子弹this.myplanemove();this.myplaneshoot();}//2.2键盘控制我方飞机移动Myplane.prototype.myplanemove = function() {var that = this;//方向定时器var uptimer = null,downtimer = null,lefttimer = null,righttimer = null;var uplock = true,downlock = true,leftlock = true,rightlock = true;document.addEventListener('keydown', movekey, false); //movekey:事件处理函数function movekey(ev) { //W:87 A:65 S:83 D:68  K:75var ev = ev || window.event;switch (ev.keyCode) {case 87:moveup(); // 上break;case 83:movedown(); // 下break;case 65:moveleft(); // 左break;case 68:moveright(); // 右break;}function moveup() {if (uplock) {uplock = false;clearInterval(downtimer);uptimer = setInterval(function() {that.y -= 4;if (that.y <= 0) {that.y = 0;}that.myplaneimg.style.top = that.y + 'px';}, 30);}}function movedown() {if (downlock) {downlock = false;clearInterval(uptimer);downtimer = setInterval(function() {that.y += 4;if (that.y >= gamebox.offsetHeight - that.h) {that.y = gamebox.offsetHeight - that.h;}that.myplaneimg.style.top = that.y + 'px';}, 30);}}function moveleft() {if (leftlock) {leftlock = false;clearInterval(righttimer);lefttimer = setInterval(function() {that.x -= 4;if (that.x <= 0) {that.x = 0;}that.myplaneimg.style.left = that.x + 'px';}, 30);}}function moveright() {if (rightlock) {rightlock = false;clearInterval(lefttimer);righttimer = setInterval(function() {that.x += 4;if (that.x >= gamebox.offsetWidth - that.w) {that.x = gamebox.offsetWidth - that.w;}that.myplaneimg.style.left = that.x + 'px';}, 30);}}}document.addEventListener('keyup', function(ev) {var ev = ev || window.event;if (ev.keyCode == 87) {clearInterval(uptimer);uplock=true;}if (ev.keyCode == 83) {clearInterval(downtimer);downlock=true;}if (ev.keyCode == 65) {clearInterval(lefttimer);leftlock=true;}if (ev.keyCode == 68) {clearInterval(righttimer);rightlock=true;}}, false);}//2.3我方飞机发射子弹Myplane.prototype.myplaneshoot = function() {var that = this;var shoottimer = null;var shootlock = true;document.addEventListener('keydown', shootbullet, false);function shootbullet(ev) {var ev = ev || window.event;if (ev.keyCode == 75) {if (shootlock) {shootlock = false;function shoot() {new Bullet(6, 14, that.x + that.w / 2 - 3, that.y - 14, 'img/bullet.png');}shoot();shoottimer = setInterval(shoot, 200);}}}document.addEventListener('keyup', function(ev) {var ev = ev || window.event;if (ev.keyCode == 75) {clearInterval(shoottimer);shootlock = true;}}, false);}//3.子弹的构造函数function Bullet(w, h, x, y, imgurl) { //w,h宽高 x,y位置  imgurl图片路径this.w = w;this.h = h;this.x = x;this.y = y;this.imgurl = imgurl;//创建子弹this.createbullet();}//3.1创建子弹Bullet.prototype.createbullet = function() {this.bulletimg = document.createElement('img');this.bulletimg.src = this.imgurl;this.bulletimg.style.cssText = `width:${this.w}px;height:${this.h}px;position:absolute;left:${this.x}px;top:${this.y}px;`;gamebox.appendChild(this.bulletimg);//子弹创建完成,执行运动。this.bulletmove();}//3.2子弹运动Bullet.prototype.bulletmove = function() {var that = this;this.timer = setInterval(function() {that.y -= 4;if (that.y <= -that.h) { //让子弹消失clearInterval(that.timer);gamebox.removeChild(that.bulletimg);}that.bulletimg.style.top = that.y + 'px';that.bullethit();}, 30)}Bullet.prototype.bullethit = function() {var enemys = document.querySelectorAll('.enemy');for (var i = 0; i < enemys.length; i++) {if (this.x + this.w >= enemys[i].offsetLeft && this.x <= enemys[i].offsetLeft + enemys[i].offsetWidth && this.y + this.h >= enemys[i].offsetTop && this.y <= enemys[i].offsetTop + enemys[i].offsetHeight) {clearInterval(this.timer);try {gamebox.removeChild(this.bulletimg);} catch (e) {return;}//血量减1enemys[i].blood--;//监听敌机的血量(给敌机添加方法)enemys[i].checkblood();}}}//4.敌机的构造函数function Enemy(w, h, x, y, imgurl, boomurl, blood, score, speed) {this.w = w;this.h = h;this.x = x;this.y = y;this.imgurl = imgurl;this.boomurl = boomurl;this.blood = blood;this.score = score;this.speed = speed;this.createenemy();}//4.1创建敌机图片Enemy.prototype.createenemy = function() {var that = this;this.enemyimg = document.createElement('img');this.enemyimg.src = this.imgurl;this.enemyimg.style.cssText = `width:${this.w}px;height:${this.h}px;position:absolute;left:${this.x}px;top:${this.y}px;`;gamebox.appendChild(this.enemyimg);this.enemyimg.className = 'enemy'; //给每一架创建的敌机添加类this.enemyimg.score = this.score; //给每一架创建的敌机添加分数this.enemyimg.blood = this.blood; //给每一架创建的敌机添加自定义的属性--血量this.enemyimg.checkblood = function() {//this==>this.enemyimgif (this.blood <= 0) { //敌机消失爆炸。this.className = ''; //去掉类名。this.src = that.boomurl;clearInterval(that.enemyimg.timer);setTimeout(function() {gamebox.removeChild(that.enemyimg);}, 300);zscore += this.score;oEm.innerHTML = zscore;}}//子弹创建完成,执行运动。this.enemymove();}//4.2敌机运动Enemy.prototype.enemymove = function() {var that = this;this.enemyimg.timer = setInterval(function() {that.y += that.speed;if (that.y >= gamebox.offsetHeight) {clearInterval(that.enemyimg.timer);gamebox.removeChild(that.enemyimg);}that.enemyimg.style.top = that.y + 'px';that.enemyhit();}, 30);}//4.3敌机碰撞我方飞机Enemy.prototype.enemyhit = function() {if (!(this.x + this.w < ourplane.x || this.x > ourplane.x + ourplane.w || this.y + this.h < ourplane.y || this.y > ourplane.y + ourplane.h)) {var enemys=document.querySelectorAll('.enemy');for (var i = 0; i < enemys.length; i++) {clearInterval(enemys[i].timer);}clearInterval(enemytimer);clearInterval(bgtimer);ourplane.myplaneimg.src = ourplane.boomurl;setTimeout(function() {gamebox.removeChild(ourplane.myplaneimg);alert('game over!!');location.reload();}, 300)}}var enemytimer = setInterval(function() {for (var i = 0; i < ranNum(1, 3); i++) {var num = ranNum(1, 20); //1-20if (num < 15) { //小飞机new Enemy(34, 24, ranNum(0, gamebox.offsetWidth - 34), -24, 'img/smallplane.png', 'img/smallplaneboom.gif', 1, 1, ranNum(2, 4));} else if (num >= 15 && num < 20) {new Enemy(46, 60, ranNum(0, gamebox.offsetWidth - 46), -60, 'img/midplane.png', 'img/midplaneboom.gif', 3, 5, ranNum(1, 3));} else if (num == 20) {new Enemy(110, 164, ranNum(0, gamebox.offsetWidth - 110), -164, 'img/bigplane.png', 'img/bigplaneboom.gif', 10, 10, 1);}}}, 3000);function ranNum(min, max) {return Math.round(Math.random() * (max - min)) + min;}//实例化我方飞机var ourplane = new Myplane(66, 80, (gamebox.offsetWidth - 66) / 2, gamebox.offsetHeight - 80, 'img/myplane.gif', 'img/myplaneBoom.gif');
})();

四、代码资源分享

HTML+CSS+JS制作【飞机大战】小游戏(键盘版和鼠标版)相关推荐

  1. html+css+js实现飞机大战小游戏

    前言 废话不多说,直接上源码 一.requestAnimationFrame是什么? ​ 在Web应用中,实现动画效果的方法比较多,Javascript 中可以通过定时器 setTimeout/ se ...

  2. jq制作飞机大战小游戏

    飞机大战小游戏 页面布局: <h1 class="score">0</h1><div class="contain">< ...

  3. js实现飞机大战小游戏

    用JavaScript来实现一个鼠标指针控制的飞机大战小程序,效果图如下. 1.进入页面阶段 2.第二载入阶段效果图 3.第三核心阶段 4.第四暂停阶段 5.第五结束阶段 实现这个项目的HTML代码只 ...

  4. JS实现飞机大战小游戏 超详细 附源码和原图

    目录 效果展示 源码 HTML CSS JS 原图 效果展示 HTML+CSS+JS做打飞机小游戏 开始界面 选择你喜欢的飞机开始游戏 按下空格键 开始/暂停  有三种敌机 可以设置飞机生命值,生命值 ...

  5. pygame为游戏添加背景_用 Python 制作飞机大战小游戏

    这这次用Python中的pygame模块来完成一个飞机大战的小游戏:基本思路是通过方向键来控制飞机的左右移动射击飞船.先来看下最后的效果为了新手也能完成,本文记录了编写的全部流程,也就是每次修改的代码 ...

  6. 手把手教你使用Pygame制作飞机大战小游戏,4万字超详细讲解!

    点击上方"早起Python",关注并"星标" 每日接收原创Python干货! 大家好,偷学Python系列是由小甜同学从初学者的角度学习Python的笔记,其特 ...

  7. 拾起童年的回忆 - 手把手教你制作飞机大战小游戏

    拾起童年的回忆 最记得小学时,每逢放学便会打开电视机,接上红白机/小霸王,插上一张游戏卡带,魂斗罗.超级玛丽.冒险岛.足球小将,拳王.飞机大战.雪人兄弟--,这些游戏到现在还是如数家珍,一张游戏卡可以 ...

  8. 自己制作飞机大战小游戏 canvas应用实例

    图片只能打包上传 百度云链接:https://pan.baidu.com/s/1bxHZYtsZxTzPFis4Fq4AvA 密码:xshc <!DOCTYPE html> <htm ...

  9. HTML5用canvas制作飞机大战小游戏

    css样式: <!DOCTYPE html> <html lang="en"><head><meta charset="UTF- ...

  10. 使用小程序制作一个飞机大战小游戏

    此文主要基于微信小程序制作一个飞机大战小游戏,上手即用,操作简单. 一.创建小程序 二.页面实现 三.代码块 一.创建小程序 访问微信公众平台,点击账号注册. 选择小程序,并在表单填写所需的各项信息进 ...

最新文章

  1. 子路由里嵌套子路由、嵌套多重子路由
  2. Springboot注册Servlet
  3. 20170822L08-04老男孩linux实战运维培训-Lamp系列之-Apache服务生产实战应用指南01
  4. JMeter性能测试中如何使用“用户参数”实现参数化
  5. 1019. 数字黑洞 (20)-PAT乙级真题
  6. 谈360下拉词360下拉框的优势及360搜索推广方法有哪些?
  7. m3u8 video ios h5_移动端H5页面踩坑记
  8. android打造一个简单的欢迎界面
  9. 拓端tecdat|Python用PyMC3实现贝叶斯线性回归模型
  10. 企业运用通兑吧数字会员卡进行营销的优势
  11. RAR压缩包有密码怎么办
  12. 使用iptables-persistent永久保存iptables规则
  13. 读【选修计算机专业的伤与痛】
  14. 买极米NEW Z8X的我后悔了,换成当贝F3 Air可真香
  15. 嵌入式软件是怎么分类的?
  16. 格理论与密码学(二)
  17. 认证授权中解决AuthenticationManager 无法注入
  18. OA系统中 流程审批数据库的设计
  19. 对 c\c++ char类型的理解
  20. Day21-30 - Web前端概述

热门文章

  1. iOS和Android的app界面设计规范
  2. vue 父传子props
  3. 微软打字/拼音不出现汉字
  4. JS 区分+0和-0
  5. URAL1671 Anansi's Cobweb(离线做 + 并查集)
  6. sakila数仓实战案例
  7. C++STL算法 search你是我的半截的诗
  8. Mysql免安装版下载以及配置
  9. 夺宝奇兵 (优先队列 + 贪心 + 暴力枚举)
  10. 反相放大电路反馈电阻上并联电容的作用 [转载]