const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
canvas.width = 800;
canvas.height = 400;
const ctx = canvas.getContext("2d");
const player = {
x: 50,
y: canvas.height / 2 - 15,
width: 30,
height: 30,
speed: 5
};
const endZone = {
x: canvas.width - 50,
y: 0,
width: 20,
height: canvas.height,
color: "red"
};
let keys = {};
document.addEventListener("keydown", (e) => keys[e.key] = true);
document.addEventListener("keyup", (e) => keys[e.key] = false);
function update() {
if (keys["ArrowUp"] && player.y > 0) player.y -= player.speed;
if (keys["ArrowDown"] && player.y < canvas.height - player.height) player.y += player.speed;
if (keys["ArrowLeft"] && player.x > 0) player.x -= player.speed;
if (keys["ArrowRight"] && player.x < canvas.width - player.width) player.x += player.speed;
if (player.x + player.width >= endZone.x) {
alert("Touchdown! 🏈");
player.x = 50;
player.y = canvas.height / 2 - 15;
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "green";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = endZone.color;
ctx.fillRect(endZone.x, endZone.y, endZone.width, endZone.height);
ctx.fillStyle = "blue";
ctx.fillRect(player.x, player.y, player.width, player.height);
}
function gameLoop() {
update();
draw();
requestAnimationFrame(gameLoop);
}
gameLoop();