Can you make a pong game in HTML, CSS and JS?
- User
Can you make a pong game in HTML, CSS and JS?
- Assistant
Can you make a pong game in HTML, CSS and JS?
Sure! Creating a simple Pong game using HTML, CSS, and JavaScript is a fun project that can help you understand the basics of game development on the web. Below is a step-by-step guide along with the complete code to create your own Pong game.
<canvas> element.Create an index.html file and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pong Game</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script src="script.js"></script>
</body>
</html>
Explanation:
<canvas> element is where the game will be drawn. It's set to 800x600 pixels.styles.css) and JavaScript (script.js) files are linked.Create a styles.css file and add the following code:
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #000; /* Black background for better contrast */
margin: 0;
}
#gameCanvas {
border: 2px solid #fff; /* White border around the canvas */
background-color: #000; /* Ensures the canvas background is black */
}
Explanation:
body is styled to center the canvas both vertically and horizontally.#gameCanvas has a white border and a black background to resemble the classic Pong aesthetic.Create a script.js file and add the following code:
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Paddle properties
const paddleWidth = 10;
const paddleHeight = 100;
const paddleSpeed = 6;
// Ball properties
const ballRadius = 10;
let ballSpeed = 5;
// Scores
let playerScore = 0;
let computerScore = 0;
// Define the left (player) paddle
const playerPaddle = {
x: 10,
y: (canvas.height - paddleHeight) / 2,
width: paddleWidth,
height: paddleHeight,
dy: 0
};
// Define the right (computer) paddle
const computerPaddle = {
x: canvas.width - paddleWidth - 10,
y: (canvas.height - paddleHeight) / 2,
width: paddleWidth,
height: paddleHeight,
dy: 0
};
// Define the ball
const ball = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: ballRadius,
dx: ballSpeed,
dy: ballSpeed
};
// Draw Paddle
function drawPaddle(paddle) {
ctx.fillStyle = '#fff';
ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
}
// Draw Ball
function drawBall() {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fillStyle = '#fff';
ctx.fill();
ctx.closePath();
}
// Draw Scores
function drawScore() {
ctx.font = '32px Arial';
ctx.fillText(playerScore, canvas.width / 4, 50);
ctx.fillText(computerScore, 3 * canvas.width / 4, 50);
}
// Move Paddle
function movePaddle(paddle) {
paddle.y += paddle.dy;
// Prevent paddle from going out of bounds
if (paddle.y < 0) {
paddle.y = 0;
} else if (paddle.y + paddle.height > canvas.height) {
paddle.y = canvas.height - paddle.height;
}
}
// Move Ball
function moveBall() {
ball.x += ball.dx;
ball.y += ball.dy;
// Collision with top and bottom walls
if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
ball.dy = -ball.dy;
}
// Collision with player paddle
if (ball.x - ball.radius < playerPaddle.x + playerPaddle.width &&
ball.y > playerPaddle.y &&
ball.y < playerPaddle.y + playerPaddle.height) {
ball.dx = -ball.dx;
}
// Collision with computer paddle
if (ball.x + ball.radius > computerPaddle.x &&
ball.y > computerPaddle.y &&
ball.y < computerPaddle.y + computerPaddle.height) {
ball.dx = -ball.dx;
}
// If the ball goes past the player paddle
if (ball.x - ball.radius < 0) {
computerScore++;
resetBall();
}
// If the ball goes past the computer paddle
if (ball.x + ball.radius > canvas.width) {
playerScore++;
resetBall();
}
}
// Reset Ball to the center
function resetBall() {
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
ball.dx = -ball.dx;
ball.dy = ballSpeed * (Math.random() > 0.5 ? 1 : -1);
}
// Computer AI
function computerAI() {
const target = ball.y;
if (computerPaddle.y + computerPaddle.height / 2 < target) {
computerPaddle.dy = paddleSpeed * 0.6; // Computer paddle speed
} else {
computerPaddle.dy = -paddleSpeed * 0.6;
}
}
// Key Presses
const keys = {};
document.addEventListener('keydown', (e) => {
keys[e.key] = true;
});
document.addEventListener('keyup', (e) => {
keys[e.key] = false;
});
// Update game objects
function update() {
// Player movement
if (keys['ArrowUp']) {
playerPaddle.dy = -paddleSpeed;
} else if (keys['ArrowDown']) {
playerPaddle.dy = paddleSpeed;
} else {
playerPaddle.dy = 0;
}
movePaddle(playerPaddle);
computerAI();
movePaddle(computerPaddle);
moveBall();
}
// Render the game
function render() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw everything
drawPaddle(playerPaddle);
drawPaddle(computerPaddle);
drawBall();
drawScore();
}
// Game loop
function gameLoop() {
update();
render();
requestAnimationFrame(gameLoop);
}
// Start the game
gameLoop();
Explanation:
Initialization:
Drawing Functions:
drawPaddle: Draws a paddle on the canvas.drawBall: Draws the ball.drawScore: Displays the current scores.Movement Functions:
movePaddle: Updates the paddle's position and ensures it doesn't go out of bounds.moveBall: Updates the ball's position, handles collision with walls and paddles, and updates scores if the ball goes past a paddle.resetBall: Resets the ball to the center after a point is scored.Computer AI:
computerAI: Simple AI that moves the computer paddle towards the ball’s y-position.Input Handling:
ArrowUp and ArrowDown) to move the player's paddle.Game Loop:
update: Updates the positions of paddles and the ball.render: Clears the canvas and redraws all elements.gameLoop: Continuously runs the update and render functions using requestAnimationFrame for smooth animations.File Structure:
/pong-game
│
├── index.html
├── styles.css
└── script.js
Open in Browser:
index.html file in your preferred web browser.This basic version of Pong can be enhanced in several ways:
For convenience, here's the complete code integrated together. You can copy and paste this into a single HTML file to run the game.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=800, initial-scale=1.0">
<title>Pong Game</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #000; /* Black background for better contrast */
margin: 0;
}
#gameCanvas {
border: 2px solid #fff; /* White border around the canvas */
background-color: #000; /* Ensures the canvas background is black */
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Paddle properties
const paddleWidth = 10;
const paddleHeight = 100;
const paddleSpeed = 6;
// Ball properties
const ballRadius = 10;
let ballSpeed = 5;
// Scores
let playerScore = 0;
let computerScore = 0;
// Define the left (player) paddle
const playerPaddle = {
x: 10,
y: (canvas.height - paddleHeight) / 2,
width: paddleWidth,
height: paddleHeight,
dy: 0
};
// Define the right (computer) paddle
const computerPaddle = {
x: canvas.width - paddleWidth - 10,
y: (canvas.height - paddleHeight) / 2,
width: paddleWidth,
height: paddleHeight,
dy: 0
};
// Define the ball
const ball = {
x: canvas.width / 2,
y: canvas.height / 2,
radius: ballRadius,
dx: ballSpeed,
dy: ballSpeed
};
// Draw Paddle
function drawPaddle(paddle) {
ctx.fillStyle = '#fff';
ctx.fillRect(paddle.x, paddle.y, paddle.width, paddle.height);
}
// Draw Ball
function drawBall() {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2);
ctx.fillStyle = '#fff';
ctx.fill();
ctx.closePath();
}
// Draw Scores
function drawScore() {
ctx.font = '32px Arial';
ctx.fillText(playerScore, canvas.width / 4, 50);
ctx.fillText(computerScore, 3 * canvas.width / 4, 50);
}
// Move Paddle
function movePaddle(paddle) {
paddle.y += paddle.dy;
// Prevent paddle from going out of bounds
if (paddle.y < 0) {
paddle.y = 0;
} else if (paddle.y + paddle.height > canvas.height) {
paddle.y = canvas.height - paddle.height;
}
}
// Move Ball
function moveBall() {
ball.x += ball.dx;
ball.y += ball.dy;
// Collision with top and bottom walls
if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
ball.dy = -ball.dy;
}
// Collision with player paddle
if (ball.x - ball.radius < playerPaddle.x + playerPaddle.width &&
ball.y > playerPaddle.y &&
ball.y < playerPaddle.y + playerPaddle.height) {
ball.dx = -ball.dx;
}
// Collision with computer paddle
if (ball.x + ball.radius > computerPaddle.x &&
ball.y > computerPaddle.y &&
ball.y < computerPaddle.y + computerPaddle.height) {
ball.dx = -ball.dx;
}
// If the ball goes past the player paddle
if (ball.x - ball.radius < 0) {
computerScore++;
resetBall();
}
// If the ball goes past the computer paddle
if (ball.x + ball.radius > canvas.width) {
playerScore++;
resetBall();
}
}
// Reset Ball to the center
function resetBall() {
ball.x = canvas.width / 2;
ball.y = canvas.height / 2;
ball.dx = -ball.dx;
ball.dy = ballSpeed * (Math.random() > 0.5 ? 1 : -1);
}
// Computer AI
function computerAI() {
const target = ball.y;
if (computerPaddle.y + computerPaddle.height / 2 < target) {
computerPaddle.dy = paddleSpeed * 0.6; // Computer paddle speed
} else {
computerPaddle.dy = -paddleSpeed * 0.6;
}
}
// Key Presses
const keys = {};
document.addEventListener('keydown', (e) => {
keys[e.key] = true;
});
document.addEventListener('keyup', (e) => {
keys[e.key] = false;
});
// Update game objects
function update() {
// Player movement
if (keys['ArrowUp']) {
playerPaddle.dy = -paddleSpeed;
} else if (keys['ArrowDown']) {
playerPaddle.dy = paddleSpeed;
} else {
playerPaddle.dy = 0;
}
movePaddle(playerPaddle);
computerAI();
movePaddle(computerPaddle);
moveBall();
}
// Render the game
function render() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw everything
drawPaddle(playerPaddle);
drawPaddle(computerPaddle);
drawBall();
drawScore();
}
// Game loop
function gameLoop() {
update();
render();
requestAnimationFrame(gameLoop);
}
// Start the game
gameLoop();
</script>
</body>
</html>
Usage:
pong.html and paste the above code into it.pong.html in your web browser.You've now created a basic Pong game using HTML, CSS, and JavaScript! This project covers fundamental concepts such as rendering graphics with the <canvas> element, handling user input, implementing simple AI, and managing game states. You can further enhance this game by adding features like sound effects, increasing difficulty levels, adding a start screen, or implementing multiplayer capabilities.
Feel free to experiment and customize the game to make it your own. Happy coding!
Not yet included in a published release.