0% found this document useful (0 votes)
8 views3 pages

JavaScript Pong Game Implementation

Uploaded by

tasleemafzal84
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

JavaScript Pong Game Implementation

Uploaded by

tasleemafzal84
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

const canvas = document.

getElementById("gameCanvas");
const ctx = [Link]("2d");

const PADDLE_WIDTH = 15, PADDLE_HEIGHT = 100;


const BALL_RADIUS = 10;
const PADDLE_SPEED = 10;
let ballVelocityX = 5, ballVelocityY = 5;

let player1Y = [Link] / 2 - PADDLE_HEIGHT / 2;


let player2Y = [Link] / 2 - PADDLE_HEIGHT / 2;
let ballX = [Link] / 2 - BALL_RADIUS;
let ballY = [Link] / 2 - BALL_RADIUS;

let scorePlayer1 = 0;
let scorePlayer2 = 0;

// Update the score display


function updateScore() {
[Link]('scorePlayer1').innerText = `Player 1: $
{scorePlayer1}`;
[Link]('scorePlayer2').innerText = `Player 2: $
{scorePlayer2}`;
}

// Draw the paddles, ball, and game screen


function draw() {
[Link](0, 0, [Link], [Link]);

// Draw paddles
[Link] = 'white';
[Link](50, player1Y, PADDLE_WIDTH, PADDLE_HEIGHT); // Player 1 Paddle
[Link]([Link] - 50 - PADDLE_WIDTH, player2Y, PADDLE_WIDTH,
PADDLE_HEIGHT); // Player 2 Paddle

// Draw ball
[Link]();
[Link](ballX, ballY, BALL_RADIUS, 0, [Link] * 2);
[Link]();
}

// Move paddles based on key input


function movePaddles() {
// Player 1 (Left Paddle) controls: W and S
if (keys['w'] && player1Y > 0) {
player1Y -= PADDLE_SPEED;
}
if (keys['s'] && player1Y + PADDLE_HEIGHT < [Link]) {
player1Y += PADDLE_SPEED;
}

// Player 2 (Right Paddle) controls: Up and Down arrows


if (keys['ArrowUp'] && player2Y > 0) {
player2Y -= PADDLE_SPEED;
}
if (keys['ArrowDown'] && player2Y + PADDLE_HEIGHT < [Link]) {
player2Y += PADDLE_SPEED;
}
}
// Move the ball and check for collisions
function moveBall() {
ballX += ballVelocityX;
ballY += ballVelocityY;

// Ball collision with top or bottom walls


if (ballY <= 0 || ballY >= [Link]) {
ballVelocityY *= -1;
}

// Ball collision with paddles


if (ballX <= 50 + PADDLE_WIDTH && ballY >= player1Y && ballY <= player1Y +
PADDLE_HEIGHT) {
ballVelocityX *= -1;
}
if (ballX >= [Link] - 50 - PADDLE_WIDTH - BALL_RADIUS * 2 && ballY >=
player2Y && ballY <= player2Y + PADDLE_HEIGHT) {
ballVelocityX *= -1;
}

// Ball out of bounds (Left or Right)


if (ballX <= 0) {
scorePlayer2++;
resetBall();
}
if (ballX >= [Link]) {
scorePlayer1++;
resetBall();
}
}

// Reset ball to center after scoring


function resetBall() {
ballX = [Link] / 2 - BALL_RADIUS;
ballY = [Link] / 2 - BALL_RADIUS;
ballVelocityX *= -1; // Randomize direction
}

// Listen for keydown and keyup events


let keys = {};
[Link]('keydown', (e) => {
keys[[Link]] = true;

// Fullscreen toggle with F11


if ([Link] === 'F11') {
[Link](); // Prevent the default F11 action
toggleFullScreen();
}

// Exit full-screen with Esc key


if ([Link] === 'Escape') {
if ([Link]) {
[Link]();
}
}
});
[Link]('keyup', (e) => {
keys[[Link]] = false;
});
// Function to toggle full-screen mode
function toggleFullScreen() {
if (![Link]) {
// Enter full-screen
if ([Link]) {
[Link]();
} else if ([Link]) { // Firefox
[Link]();
} else if ([Link]) { // Chrome, Safari and Opera
[Link]();
} else if ([Link]) { // IE/Edge
[Link]();
}
} else {
// Exit full-screen
if ([Link]) {
[Link]();
} else if ([Link]) { // Firefox
[Link]();
} else if ([Link]) { // Chrome, Safari and Opera
[Link]();
} else if ([Link]) { // IE/Edge
[Link]();
}
}
}

// Game loop function


function gameLoop() {
movePaddles();
moveBall();
draw();
updateScore();
requestAnimationFrame(gameLoop); // Continue the loop
}

// Start the game loop


gameLoop();

Common questions

Powered by AI

Full-screen mode is toggled by checking if there is a full-screen element. If not, the full-screen request is made using 'canvas.requestFullscreen' or its browser-specific variants like 'mozRequestFullScreen', 'webkitRequestFullscreen', or 'msRequestFullscreen'. If already in full-screen mode, it exits using 'document.exitFullscreen' or similar vendor-specific calls depending on the browser, such as 'document.mozCancelFullScreen', 'document.webkitExitFullscreen', or 'document.msExitFullscreen' .

The implementation checks for collisions with the top and bottom walls using the condition 'if (ballY <= 0 || ballY >= canvas.height)'. When this condition is met, it reverses the vertical velocity of the ball by multiplying 'ballVelocityY' by -1, thus ensuring it bounces off the walls .

When the ball goes out of bounds on the left, 'scorePlayer2' is incremented, and similarly, 'scorePlayer1' is incremented when it goes out on the right. The 'resetBall' function is then called, which places the ball back at the center, reverses its horizontal velocity, and can randomize the direction. This mechanism ensures a continuous gameplay cycle with scoring .

Scores are updated by directly incrementing the respective player's score and invoking 'updateScore()' which modifies the DOM elements to reflect updated scores. This is effective as it provides immediate feedback to players on scoring changes, ensuring scores stay synchronized with gameplay events .

The game differentiates control keys for the players by assigning specific keys to each player: 'W' and 'S' for Player 1, and 'ArrowUp' and 'ArrowDown' for Player 2. The game uses an object 'keys' to track the state of these keys based on 'keydown' and 'keyup' events, allowing independent control of each paddle .

The game handles key states for toggling full-screen mode using conditional checks within the 'keydown' event listener. It prevents default browser behavior for 'F11' using 'e.preventDefault()' and includes a custom function 'toggleFullScreen()' to enter or exit full-screen mode depending on the current state. It also addresses exiting full-screen with the 'Escape' key by checking 'document.fullscreenElement' status, ensuring consistent user interactions across different scenarios .

The paddle movement is bounded by checking the 'Y' position within the 'movePaddles' function. For Player 1, the movement is restricted with 'if (player1Y > 0)' and 'if (player1Y + PADDLE_HEIGHT < canvas.height)', while for Player 2, 'if (player2Y > 0)' and 'if (player2Y + PADDLE_HEIGHT < canvas.height)' conditions ensure paddles stay within the canvas .

Ball collisions with paddles are determined by checking positions relative to paddle boundaries. If the ball's X position is within a paddle's range and the Y position matches the paddle's height constraints, the 'ballVelocityX' is inverted. Specifically, checks like 'ballX <= 50 + PADDLE_WIDTH' for Player 1 and 'ballX >= canvas.width - 50 - PADDLE_WIDTH - BALL_RADIUS * 2' for Player 2 ensure proper collision detection .

The continuous game loop is maintained by using 'requestAnimationFrame(gameLoop)', which recursively calls the 'gameLoop' function. This function integrates key operations including 'movePaddles()', 'moveBall()', 'draw()', and 'updateScore()', ensuring that all game components are updated and redrawn at each frame .

The paddle positions are updated through event listeners that track key presses and releases. The 'keydown' event modifies a 'keys' object to keep track of pressed keys, while the 'keyup' event sets the respective keys back to false. In the 'movePaddles' function, the positions are updated by checking if the associated keys ('W' and 'S' for Player 1, 'ArrowUp' and 'ArrowDown' for Player 2) are true, adjusting the paddles' Y positions by 'PADDLE_SPEED' within the boundaries of the canvas .

You might also like