Write a 3D pong game with a player against an AI in a single HTML file
- User
Write a 3D pong game with a player against an AI in a single HTML file
- Assistant
Write a 3D pong game with a player against an AI in a single HTML file
Creating a 3D Pong game in a single HTML file is an exciting project that leverages WebGL through the Three.js library. Below is a comprehensive guide accompanied by the complete code to help you build a player-versus-AI 3D Pong game.
The game consists of:
Below is the complete HTML code for the 3D Pong game. Simply save this code in an .html file and open it in your web browser to play.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>3D Pong Game</title>
<style>
body { margin: 0; overflow: hidden; background-color: #000; }
#score {
position: absolute;
top: 20px;
width: 100%;
text-align: center;
color: #fff;
font-family: Arial, sans-serif;
font-size: 24px;
z-index: 1;
}
</style>
</head>
<body>
<div id="score">Player: 0 | AI: 0</div>
<!-- Include Three.js from CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
// Set up scene, camera, and renderer
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Add lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight.position.set(0, 1, 1).normalize();
scene.add(directionalLight);
// Create paddles and ball
const paddleWidth = 1, paddleHeight = 0.2, paddleDepth = 4;
const paddleGeometry = new THREE.BoxGeometry(paddleWidth, paddleHeight, paddleDepth);
const paddleMaterial = new THREE.MeshPhongMaterial({ color: 0xffffff });
const playerPaddle = new THREE.Mesh(paddleGeometry, paddleMaterial);
playerPaddle.position.x = -15;
scene.add(playerPaddle);
const aiPaddle = new THREE.Mesh(paddleGeometry, paddleMaterial);
aiPaddle.position.x = 15;
scene.add(aiPaddle);
const ballRadius = 0.5;
const ballGeometry = new THREE.SphereGeometry(ballRadius, 32, 32);
const ballMaterial = new THREE.MeshPhongMaterial({ color: 0xff0000 });
const ball = new THREE.Mesh(ballGeometry, ballMaterial);
ball.position.set(0, 0, 0);
scene.add(ball);
// Position camera
camera.position.z = 30;
camera.position.y = 0;
camera.lookAt(0, 0, 0);
// Game variables
let ballVelocity = new THREE.Vector3(0.2, 0, 0.2);
let playerScore = 0, aiScore = 0;
const scoreDiv = document.getElementById('score');
// Player controls
const keysPressed = {};
document.addEventListener('keydown', (event) => {
keysPressed[event.key.toLowerCase()] = true;
});
document.addEventListener('keyup', (event) => {
keysPressed[event.key.toLowerCase()] = false;
});
// AI movement variables
const aiSpeed = 0.15;
// Resize handling
window.addEventListener('resize', () => {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
});
// Animation loop
function animate() {
requestAnimationFrame(animate);
// Update player paddle position
if (keysPressed['w']) {
playerPaddle.position.y += 0.3;
if (playerPaddle.position.y > 8) playerPaddle.position.y = 8;
}
if (keysPressed['s']) {
playerPaddle.position.y -= 0.3;
if (playerPaddle.position.y < -8) playerPaddle.position.y = -8;
}
// Update AI paddle position
if (aiPaddle.position.y < ball.position.y) {
aiPaddle.position.y += aiSpeed;
} else if (aiPaddle.position.y > ball.position.y) {
aiPaddle.position.y -= aiSpeed;
}
// Limit AI paddle movement
if (aiPaddle.position.y > 8) aiPaddle.position.y = 8;
if (aiPaddle.position.y < -8) aiPaddle.position.y = -8;
// Update ball position
ball.position.add(ballVelocity);
// Ball collision with top and bottom walls
if (ball.position.y > 10 - ballRadius || ball.position.y < -10 + ballRadius) {
ballVelocity.y = -ballVelocity.y;
}
// Ball collision with player paddle
if (ball.position.x - ballRadius < playerPaddle.position.x + paddleWidth/2 &&
ball.position.y < playerPaddle.position.y + paddleHeight/2 &&
ball.position.y > playerPaddle.position.y - paddleHeight/2 &&
ball.position.z < paddleDepth/2 && ball.position.z > -paddleDepth/2) {
ballVelocity.x = -ballVelocity.x;
// Optional: Add some variation based on where it hits the paddle
ballVelocity.y += (ball.position.y - playerPaddle.position.y) * 0.05;
}
// Ball collision with AI paddle
if (ball.position.x + ballRadius > aiPaddle.position.x - paddleWidth/2 &&
ball.position.y < aiPaddle.position.y + paddleHeight/2 &&
ball.position.y > aiPaddle.position.y - paddleHeight/2 &&
ball.position.z < paddleDepth/2 && ball.position.z > -paddleDepth/2) {
ballVelocity.x = -ballVelocity.x;
// Optional: Add some variation based on where it hits the paddle
ballVelocity.y += (ball.position.y - aiPaddle.position.y) * 0.05;
}
// Ball goes out of bounds - scoring
if (ball.position.x < -20) {
aiScore += 1;
resetBall();
}
if (ball.position.x > 20) {
playerScore += 1;
resetBall();
}
// Update score display
scoreDiv.innerText = `Player: ${playerScore} | AI: ${aiScore}`;
renderer.render(scene, camera);
}
// Reset ball to center with initial velocity
function resetBall() {
ball.position.set(0, 0, 0);
// Randomize initial direction
ballVelocity.x = (Math.random() > 0.5 ? 0.2 : -0.2);
ballVelocity.y = (Math.random() - 0.5) * 0.4;
ballVelocity.z = (Math.random() - 0.5) * 0.4;
}
animate();
</script>
</body>
</html>
3d_pong.html.W key.S key.Feel free to modify the following aspects to enhance the game:
paddleWidth, paddleHeight, paddleDepth, and ballRadius to change the sizes.ballVelocity and aiSpeed for different game speeds.color property in materials for different aesthetics.This 3D Pong game serves as a foundational project to explore WebGL and Three.js for creating interactive 3D games in the browser. By understanding and modifying this code, you can expand its features and develop more sophisticated games.
Enjoy playing and customizing your 3D Pong game!
Not yet included in a published release.