<!
DOCTYPE html>
<html>
<head>
<title>Soccer Game</title>
<style>
#gameCanvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<div id="score">Player 1: 0 - Player 2: 0</div>
<script>
// Get the canvas element
var canvas = document.getElementById('gameCanvas');
var ctx = canvas.getContext('2d');
// Define the ball properties
var ball = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: 10,
speedX: 2,
speedY: 2
};
// Define the player properties
var player1 = {
x: 50,
y: canvas.height / 2,
width: 10,
height: 100,
score: 0
};
var player2 = {
x: canvas.width - 60,
y: canvas.height / 2,
width: 10,
height: 100,
score: 0
};
// Draw the game elements
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fillStyle = 'white';
ctx.fill();
ctx.closePath();
ctx.fillRect(player1.x, player1.y, player1.width,
player1.height);
ctx.fillRect(player2.x, player2.y, player2.width,
player2.height);
document.getElementById('score').innerHTML = 'Player 1: ' +
player1.score + ' - Player 2: ' + player2.score;
}
// Update the game state
function update() {
ball.x += ball.speedX;
ball.y += ball.speedY;
// Collision with walls
if (ball.x + ball.radius > canvas.width) {
player1.score++;
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
} else if (ball.x - ball.radius < 0) {
player2.score++;
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
}
if (ball.y + ball.radius > canvas.height || ball.y - ball.radius
< 0) {
ball.speedY = -ball.speedY;
}
// Collision with players
if (ball.x - ball.radius < player1.x + player1.width && ball.y >
player1.y && ball.y < player1.y + player1.height) {
ball.speedX = -ball.speedX;
}
if (ball.x + ball.radius > player2.x && ball.y > player2.y &&
ball.y < player2.y + player2.height) {
ball.speedX = -ball.speedX;
}
}
// Main game loop
setInterval(function() {
update();
draw();
}, 16);
// Add event listeners for player movement
document.addEventListener('keydown', function(event) {
if (event.key === 'w') {
player1.y -= 10;
} else if (event.key === 's') {
player1.y += 10;
} else if (event.key === 'ArrowUp') {
player2.y -= 10;
} else if (event.key === 'ArrowDown') {
player2.y += 10;
}
});
</script>
</body>
</html>