前几天闲着没事写了个飞机大战,源码奉上
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>飞机大战</title>
<link rel="stylesheet" href="./css/main.css">
</head>
<body>
<div class="w">
<canvas id="canvas"></canvas>
<div>
<img src="./img/again.png" alt="">
</div>
</div>
<script src="./js/main.js"></script>
</body>
</html>
CSS
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #222;
}
.w {
position: relative;
content: '';
display: block;
width: 480px;
height: 650px;
margin: 30px auto;
}
JS
/*
* 这里是Knull~,这个飞机大战是面向对象写的
* 我也是一个正在学习的小白~~
* 还有一个升级版 github链接 https://github.com/K-null/Aircraft-war
*/
const canvas = document.querySelector('#canvas')
// 创建画布的大小
canvas.width = 480
canvas.height = 650
// 创建 2d 画布
const ctx = canvas.getContext('2d')
// 初始生命
let life = 1
// 初始分数
let fen = 0
// 定义游戏的状态
const START = 0 // 开始
const STRARING = 1 // 开始时(加载)
const RUNNING = 2 // 运行
const PAUSE = 3 // 暂停
const GAMEOVER = 4 // 结束
// 创建一个实时的游戏状态
let game = START
// 开始游戏改变游戏状态
canvas.addEventListener('click', () => {
if (game == START) {
game = STRARING
}
})
// 鼠标移动事件
canvas.addEventListener('mousemove', e => {
// 通过鼠标移动改变飞机方向
hexo.x = e.offsetX - 50
hexo.y = e.offsetY - 63
})
// 鼠标离开事件
canvas.addEventListener('mouseleave', e => {
if (game == RUNNING) {
game = PAUSE
}
})
// 鼠标离开事件
canvas.addEventListener('mouseenter', e => {
if (game == PAUSE) {
game = RUNNING
}
})
// 创建背景对象 (异步!)
const bg = new Image()
bg.src = './img/background.png'
// 创建开始 logo
const logoImage = new Image()
logoImage.src = './img/logo.png'
// 创建加载开始图片
const loadingImage = []
loadingImage[0] = new Image()
loadingImage[1] = new Image()
loadingImage[2] = new Image()
loadingImage[0].src = './img/load0.png'
loadingImage[1].src = './img/load0.png'
loadingImage[2].src = './img/load0.png'
// 创建飞机的图片
const hexoImage = {
// 飞机活的状态
hexoLive: [],
// 飞机死的状态
hexoDeath: []
}
// 飞机活
hexoImage.hexoLive[0] = new Image()
hexoImage.hexoLive[1] = new Image()
hexoImage.hexoLive[0].src = './img/me1.png'
hexoImage.hexoLive[1].src = './img/me2.png'
// 飞机死
hexoImage.hexoDeath[0] = new Image()
hexoImage.hexoDeath[1] = new Image()
hexoImage.hexoDeath[2] = new Image()
hexoImage.hexoDeath[3] = new Image()
hexoImage.hexoDeath[0].src = './img/me_destroy_1.png'
hexoImage.hexoDeath[1].src = './img/me_destroy_2.png'
hexoImage.hexoDeath[2].src = './img/me_destroy_3.png'
hexoI