basketball.html

basketball.html

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Basketball Game</title>
<style>
body {
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #2c3e50;
}

canvas {
border: 2px solid #ecf0f1;
}

#score {
position: absolute;
top: 20px;
color: #ecf0f1;
font-size: 24px;
font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<div id=”score”>Score: 0</div>
<canvas id=”gameCanvas” width=”800″ height=”600″></canvas>
<script>
const canvas = document.getElementById(‘gameCanvas’);
const ctx = canvas.getContext(‘2d’);
const scoreElement = document.getElementById(‘score’);

let ball = { x: 400, y: 500, radius: 15, dx: 0, dy: 0, isMoving: false };
let hoop = { x: 300, y: 100, width: 100, height: 10 };
let score = 0;

function drawBall() {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fillStyle = ‘orange’;
ctx.fill();
ctx.closePath();
}

function drawHoop() {
ctx.beginPath();
ctx.rect(hoop.x, hoop.y, hoop.width, hoop.height);
ctx.fillStyle = ‘red’;
ctx.fill();
ctx.closePath();
}

function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawHoop();
}

function update() {
if (ball.isMoving) {
ball.x += ball.dx;
ball.y += ball.dy;
ball.dy += 0.2; // Gravity

// Check for hoop collision
if (
ball.x > hoop.x &&
ball.x < hoop.x + hoop.width &&
ball.y + ball.radius > hoop.y &&
ball.y + ball.radius < hoop.y + hoop.height
) {
score++;
scoreElement.textContent = `Score: ${score}`;
resetBall();
}

// Reset if ball goes off-screen
if (ball.y > canvas.height) {
resetBall();
}
}
}

function resetBall() {
ball.x = 400;
ball.y = 500;
ball.dx = 0;
ball.dy = 0;
ball.isMoving = false;
}

canvas.addEventListener(‘click’, (event) => {
if (!ball.isMoving) {
const rect = canvas.getBoundingClientRect();
const mouseX = event.clientX – rect.left;
const mouseY = event.clientY – rect.top;

const angle = Math.atan2(mouseY – ball.y, mouseX – ball.x);
ball.dx = Math.cos(angle) * 8;
ball.dy = Math.sin(angle) * 8;
ball.isMoving = true;
}
});

function gameLoop() {
draw();
update();
requestAnimationFrame(gameLoop);
}

gameLoop();
</script>
</body>
</html>

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です