HTML文件:
JavaScript文件:
/*
* @Author: Administrator
* @Date: 2016-11-24 21:00:25
* @Last Modified by: Administrator
* @Last Modified time: 2016-11-25 11:27:40
*/
'use strict';
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var bgcolor = "black";
var score;
var highScore;
var fps = 30;
var player;
var bullets = [];
var enemies = [];
// 重置
function reset(){
if(score > highScore) highScore = score;
score = 0;
}
// 背景画布
function drawBackground(){
ctx.fillStyle = bgcolor;
ctx.fillRect(0,0,canvas.width,canvas.height);
}
//分数画布
function drawScore(){
ctx.fillStyle = "#CCFF99";
ctx.font ="24px sans-serif";
ctx.fillText("Score:" + score,10,24);
ctx.font ="16px sans-serif";
ctx.fillText("HighScore:" + highScore,10,48);
}
// Ready画布
function drawReady(){
drawBackground();
drawScore();
ctx.fillStyle = "white";
ctx.font = "72px sans-serif";
ctx.fillText("Ready?",canvas.width/2 - 140,canvas.height/2);
}
setInterval(function(){
update();
draw();
},1000/fps);
$(document).bind("keydown","left",function(){});
function update(){
if(keydown.left){
player.x -= 1;
}
if(keydown.right){
player.x += 1;
}
if(keydown.space){
player.shoot();
}
player.x = player.x.clamp(0,canvas.width-player.width);
bullets.forEach(function(bullet){
bullet.update();
});
bullets = bullets.filter(function(bullet){
return bullet.active;
});
enemies.forEach(function(enemy){
enemy.update();
};
enemies = enemies.filter(function(enemy){
returnenemy.active;
});
handleCollisions();
}
function draw(){
canvas.clearRect(0,0,canvas.width,canvas.height);
player.draw();
bullets.forEach(function(bullet){
bullet.draw();
});
enemies.forEach(function(enemy){
enemy.draw();
});
}
var player ={
color:"#0000AA",
x:220,
y:270,
width:32,
height:32,
draw:function(){
canvas.fillStyle=this.color;
canvas.fillRect(this.x,this.y,this.width,this.height);
}
};
// 创建炮弹
function bullet(p){
p.active = true;
p.xVelocity = 0;
p.yVelocity = speed;
p.color = "#FFFFFF";
p.width = 3px;
p.width = 3px;
p.inBounds = function(){
return p.x >= 0 && p.x = 0 && p.y = 0 && e.x = 0 && e.y b.x && a.y < b.y + b.height && a.y + a.height > b.y;
}
// 碰撞处理
function handleCollisions(){
bullets.forEach(function(bullet){
enemies.forEach(function(enemy){
if(collides(bullet,enemy)){
enemy.explode();
bullet.active=false;
}
})
});
}
document.addEventListener('DOMContentLoaded',reset()); |