105 lines
2.6 KiB
HTML
105 lines
2.6 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="de">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<title>Pong in JS</title>
|
|
<style>
|
|
canvas {
|
|
display: block;
|
|
margin: 0 auto;
|
|
background: #000;
|
|
}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<canvas id="pong" width="800" height="600"></canvas>
|
|
<script>
|
|
const canvas = document.getElementById("pong");
|
|
const ctx = canvas.getContext("2d");
|
|
|
|
// 🏓 Spieleinstellungen
|
|
const paddleWidth = 10, paddleHeight = 100, ballSize = 10;
|
|
let leftY = 150, rightY = 150;
|
|
let ballX = 300, ballY = 200;
|
|
let ballDX = 3, ballDY = 3;
|
|
|
|
// 🎯 Framerate-Begrenzung
|
|
let lastTime = 0;
|
|
const fps = 60;
|
|
const interval = 1000 / fps;
|
|
|
|
// 🧍 Linkes Paddle per Tastatur
|
|
document.addEventListener("keydown", (e) => {
|
|
if (e.key === "ArrowUp") leftY -= 20;
|
|
if (e.key === "ArrowDown") leftY += 20;
|
|
|
|
// Grenzen setzen
|
|
leftY = Math.max(0, Math.min(canvas.height - paddleHeight, leftY));
|
|
});
|
|
|
|
function gameLoop(now) {
|
|
requestAnimationFrame(gameLoop);
|
|
|
|
// ⏱ FPS-Begrenzung
|
|
const delta = now - lastTime;
|
|
if (delta < interval) return;
|
|
lastTime = now;
|
|
|
|
// 🧼 Hintergrund zeichnen
|
|
ctx.fillStyle = "black";
|
|
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
|
|
|
// 🎮 Paddles zeichnen
|
|
ctx.fillStyle = "white";
|
|
ctx.fillRect(0, leftY, paddleWidth, paddleHeight); // Linkes Paddle
|
|
ctx.fillRect(canvas.width - paddleWidth, rightY, paddleWidth, paddleHeight); // Rechtes Paddle
|
|
|
|
// ⚽ Ball zeichnen
|
|
ctx.fillRect(ballX, ballY, ballSize, ballSize);
|
|
|
|
// 🚀 Ballbewegung
|
|
ballX += ballDX;
|
|
ballY += ballDY;
|
|
|
|
// 🔁 Kollision mit oben/unten
|
|
if (ballY <= 0 || ballY + ballSize >= canvas.height) {
|
|
ballDY = -ballDY;
|
|
}
|
|
|
|
// 🛡 Kollision mit Paddle links
|
|
if (
|
|
ballX <= paddleWidth &&
|
|
ballY >= leftY &&
|
|
ballY <= leftY + paddleHeight
|
|
) {
|
|
ballDX = -ballDX;
|
|
}
|
|
|
|
// 🛡 Kollision mit Paddle rechts
|
|
if (
|
|
ballX + ballSize >= canvas.width - paddleWidth &&
|
|
ballY >= rightY &&
|
|
ballY <= rightY + paddleHeight
|
|
) {
|
|
ballDX = -ballDX;
|
|
}
|
|
|
|
// ♻️ Ball zurücksetzen bei Punktverlust
|
|
if (ballX < 0 || ballX > canvas.width) {
|
|
ballX = canvas.width / 2;
|
|
ballY = canvas.height / 2;
|
|
ballDX = -ballDX;
|
|
ballDY = 3 * (Math.random() > 0.5 ? 1 : -1); // Zufällige Richtung
|
|
}
|
|
|
|
// 🤖 Einfache KI für rechtes Paddle
|
|
rightY += (ballY - rightY - paddleHeight / 2) * 0.1;
|
|
|
|
}
|
|
|
|
// 🔁 Spiel starten
|
|
requestAnimationFrame(gameLoop);
|
|
</script>
|
|
</body>
|
|
</html>
|