1.游戏背景
首先,这是一个采用原生js写的一个demo。用ES6的模块化和class进行构建。如果课设或者什么需要的小伙伴。直接复制代码到html文件就行了。至于图片文件 ,我会把图片放到码云上。直接拉下来就行了。
2.运行截图
3.HTML和CSS源码
<!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>
* {
padding: 0px;
margin: 0px;
}
.gamebox {
width: 320px;
height: 568px;
background: url(img/background.png) repeat-y 0 0;
margin: 50px auto;
position: relative;
cursor: none;
overflow: hidden;
}
.gamebox span {
position: absolute;
right: 5px;
top: 5px;
}
.gamebox strong {
font-weight: normal;
}
</style>
</head>
<body>
<div class="gamebox">
<span>
分数:<strong>0</strong>
</span>
</div>
</body>
</html>
4.JS源码
! function() {
//1.获取元素
//外部暴露变量
const gamebox = document.querySelector('.gamebox');
const score = document.querySelector('.gamebox strong');
let allscore = 0;
//随机数设定范围
//2.背景运动起来
let speed = 0;
let bgtimer = setInterval(() => {
speed += 3;
gamebox.style.backgroundPosition = `0 ${
speed}px`;
}, 1000 / 60);
//3.飞机和子弹图片类,被继承的类
class Role {
constructor(w, h, x, y, imgurl, boomurl) {
//w宽h高x水平位置y垂直位置imgurl图片路径boourl爆炸图片路径
this.w = w;
this.h = h;
this.x = x;
this.y = y;
this.imgurl = imgurl;
this.boomurl = boomurl;
}
createRole() {
this.roleImg = document.createElement('img');
this.roleImg.src = this.imgurl;
this.roleImg.style.cssText = `
width:${
this.w}px;
height:${
this.h}px;
position:absolute;
left:${
this.x}px;
top:${
this.y}px;
`;
gamebox.appendChild(this.roleImg);
}
}
//4.我方飞机的类
class Myplane extends Role {
constructor(w, h, x, y