Meta Description" name="description" />
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Mini Battle Game</title>
<style>
body{
margin:0;
overflow:hidden;
background:#222;
}
canvas{
display:block;
margin:auto;
background:#5dbb63;
}
</style>
</head>
<body>
<canvas id="game" width="800" height="500"></canvas>
<script>
const canvas=document.getElementById("game");
const ctx=canvas.getContext("2d");
let player={
x:100,
y:250,
size:25,
color:"blue",
speed:5
};
let enemy={
x:650,
y:250,
size:25,
color:"red"
};
let bullets=[];
let keys={};
document.addEventListener("keydown",e=>keys[e.key]=true);
document.addEventListener("keyup",e=>keys[e.key]=false);
document.addEventListener("click",()=>{
bullets.push({
x:player.x,
y:player.y,
dx:8
});
});
function update(){
if(keys["ArrowUp"]) player.y-=player.speed;
if(keys["ArrowDown"]) player.y+=player.speed;
if(keys["ArrowLeft"]) player.x-=player.speed;
if(keys["ArrowRight"]) player.x+=player.speed;
bullets.forEach(b=>b.x+=b.dx);
bullets=bullets.filter(b=>b.x<canvas.width);
bullets.forEach((b,i)=>{
if(
b.x>enemy.x &&
b.x<enemy.x+enemy.size &&
b.y>enemy.y &&
b.y<enemy.y+enemy.size
){
enemy.x=Math.random()*700+50;
enemy.y=Math.random()*450+25;
bullets.splice(i,1);
}
});
}
function draw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle=player.color;
ctx.fillRect(player.x,player.y,player.size,player.size);
ctx.fillStyle=enemy.color;
ctx.fillRect(enemy.x,enemy.y,enemy.size,enemy.size);
ctx.fillStyle="yellow";
bullets.forEach(b=>{
ctx.beginPath();
ctx.arc(b.x,b.y,5,0,Math.PI*2);
ctx.fill();
});
}
function gameLoop(){
update();
draw();
requestAnimationFrame(gameLoop);
}
gameLoop();
</script>
</body>
</html>
1
1
2KB
2KB
100.0ms
112.0ms
100.0ms