Untitled
unknown
plain_text
3 months ago
2.8 kB
8
Indexable
<!DOCTYPE html>
<html>
<head>
<title>Mini Dash</title>
<style>
body{
margin:0;
background:#111;
overflow:hidden;
font-family:Arial;
}
canvas{
display:block;
margin:auto;
background:#222;
}
#score{
position:absolute;
color:white;
top:10px;
left:50%;
transform:translateX(-50%);
font-size:24px;
}
</style>
</head>
<body>
<div id="score">0</div>
<canvas id="game" width="800" height="300"></canvas>
<script>
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
let player = {
x:80,
y:220,
width:30,
height:30,
vy:0,
gravity:0.7,
jump: -12,
grounded:true
};
let obstacles = [];
let frame = 0;
let score = 0;
let gameOver = false;
document.addEventListener("keydown", e=>{
if(e.code === "Space" && player.grounded && !gameOver){
player.vy = player.jump;
player.grounded = false;
}
if(e.code === "Space" && gameOver){
restart();
}
});
function spawnObstacle(){
obstacles.push({
x:800,
y:240,
width:30,
height:30
});
}
function restart(){
obstacles=[];
frame=0;
score=0;
gameOver=false;
player.y=220;
}
function update(){
if(gameOver) return;
frame++;
score++;
document.getElementById("score").innerText = score;
if(frame % 90 === 0){
spawnObstacle();
}
player.vy += player.gravity;
player.y += player.vy;
if(player.y >= 220){
player.y = 220;
player.vy = 0;
player.grounded = true;
}
obstacles.forEach(o=>{
o.x -= 6;
if(
player.x < o.x + o.width &&
player.x + player.width > o.x &&
player.y < o.y + o.height &&
player.y + player.height > o.y
){
gameOver = true;
}
});
obstacles = obstacles.filter(o => o.x > -50);
}
function draw(){
ctx.clearRect(0,0,800,300);
ctx.fillStyle="#00ffcc";
ctx.fillRect(player.x, player.y, player.width, player.height);
ctx.fillStyle="#ff3366";
obstacles.forEach(o=>{
ctx.beginPath();
ctx.moveTo(o.x, o.y+30);
ctx.lineTo(o.x+15, o.y);
ctx.lineTo(o.x+30, o.y+30);
ctx.fill();
});
ctx.fillStyle="#555";
ctx.fillRect(0,250,800,5);
if(gameOver){
ctx.fillStyle="white";
ctx.font="40px Arial";
ctx.fillText("Game Over",300,140);
ctx.font="20px Arial";
ctx.fillText("Press SPACE to restart",290,180);
}
}
function gameLoop(){
update();
draw();
requestAnimationFrame(gameLoop);
}
gameLoop();
</script>
</body>
</html>Editor is loading...
Leave a Comment