How to Build a Quiz App with JavaScript: A Step-by-Step Guide

 

Ping Pong Game Using JavaScript

Do you want to build your own ping pong game using JavaScript?

If yes, then you have come to the right place. In this article, we will guide you through the step-by-step process of building a ping pong game using JavaScript.

JavaScript is a powerful programming language that is widely used for web development. It is a versatile language that can be used to create complex web applications, including Ping Pong Game Using JavaScript. With JavaScript, you can create interactive and engaging games that can be played in any web browser.

In this tutorial, we will use JavaScript to create a Ping Pong Game Using JavaScript. Ping pong is a classic game that is loved by people of all ages. The game involves hitting a ball back and forth between two players using paddles. The objective of the game is to score points by making the ball hit the opponent’s side of the table.

Setting Up the HTML and CSS

Before we start coding our ping pong game in JavaScript, we need to set up the HTML and CSS. The HTML will define the structure of the Ping Pong Game Using JavaScript, while the CSS will define the style and layout of the game.

First, we will create the HTML file and add the necessary elements for the game. We will create a canvas element where we will draw the game and add two div elements for the paddles. We will also add a score display element and a button to start the game.

Next, we will create the CSS file and add the necessary styles for the game. We will define the size and position of the canvas and the paddles. We will also add styles for the score display and the button.

Drawing the Game Board

Once we have set up the HTML and CSS, we can start coding the game in JavaScript. The first step is to draw the game board on the canvas element. We will use the canvas API to draw the game board.

We will define the dimensions of the game board and draw a rectangle on the canvas using the fillRect() method. We will also draw a center line on the canvas using the moveTo() and lineTo() methods.

Creating the Paddles

The next step is to create the paddles. We will use the div elements that we added in the HTML to create the paddles. We will position the paddles on the canvas and add styles to make them look like paddles.

We will also add event listeners to the paddles to detect when the player moves the paddle up or down. We will use the keyboard events to move the paddles.

Creating the Ball

The next step is to create the ball. We will use the canvas API to create the ball on the canvas. We will define the position and velocity of the ball and draw it on the canvas.

We will also add collision detection to the ball to detect when it hits the paddles or the walls of the game board. When the ball hits a paddle, it will bounce back in the opposite direction. When the ball hits the wall, it will bounce back in the same direction.

Adding Scoring and Winning

The final step is to add scoring and winning to the game. We will add a score display element to the HTML and update the score when a player scores a point.

We will also add a winning condition to the game. When a player reaches a certain number of points, the game will end, and the player will be declared the winner.

Keyword clusters:

  • Ping pong game using JavaScript
  • Building a ping pong game
  • JavaScript programming language
  • Web development
  • Canvas API
  • Creating paddles in JavaScript
  • Ball

Index.html

				
					<!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</title>
    <link rel="icon" type="image/png" href="favicon.png">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <!-- script -->
    <script src="main.js"></script>
</body>
</html>
				
			

style.css

				
					body{
    margin: 0;
    background-color: rgb(255, 242, 0);
    display: flex;
    justify-content: center;
    font-family: 'Courier New', Courier, monospace;
}

canvas{
    margin-top: 25px;
    z-index: 10;
}

.game-over-container{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 500px;
    height: 500px;
    background-color: rgb(163, 73, 164);
    margin-top: -4px;
    z-index:11;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: whitesmoke;
}

button{
    cursor: pointer;
    color: rgb(0, 0, 0);
    background-color: rgb(195, 195, 195);
    border: none;
    height: 50px;
    width: 200px;
    border-radius: 5px;
    font-size: 20px;
    font-family: 'Courier New', Courier, monospace;
}

button:hover{
    filter: brightness(80%);
}

button:active{
    transform: scale(0.95);
}

button:focus{
    outline: none;
}

/* Montior and Large */
@media screen and (min-width: 1800px){
    canvas{
        margin-top: 100px;
    }
    .game-over-container{
        margin-top: -19px;
    }
}

/* Large Smartphone (vertical) */
@media screen and (max-width: 500px){
    canvas{
        width: 100%;
        height: 700px;
        margin-top: 50px;
    }
    .game-over-container{
        width: 100%;
        height: 700px;
    }
}

				
			

main.js

				
					// Canvas
const { body } = document;
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const width = 500;
const height = 700;
const screenWidth = window.screen.width;
const canvasPosition = screenWidth / 2 - width / 2;
const isMobile = window.matchMedia('(max-width: 600px)');
const gameOverEl = document.createElement('div');

// Paddle
const paddleHeight = 10;
const paddleWidth = 50;
const paddleDiff = 25;
let paddleBottomX = 225;
let paddleTopX = 225;
let playerMoved = false;
let paddleContact = false;

// Ball
let ballX = 250;
let ballY = 350;
const ballRadius = 5;

// Speed
let speedY;
let speedX;
let trajectoryX;
let computerSpeed;

// Change Mobile Settings
if (isMobile.matches) {
  speedY = -2;
  speedX = speedY;
  computerSpeed = 4;
} else {
  speedY = -1;
  speedX = speedY;
  computerSpeed = 3;
}

// Score
let playerScore = 0;
let computerScore = 0;
const winningScore = 7;
let isGameOver = true;
let isNewGame = true;

// Render Everything on Canvas
function renderCanvas() {
  // Canvas Background
  context.fillStyle = 'black';
  context.fillRect(0, 0, width, height);

  // Paddle Color
  context.fillStyle = 'white';

  // Player Paddle (Bottom)
  context.fillRect(paddleBottomX, height - 20, paddleWidth, paddleHeight);

  // Computer Paddle (Top)
  context.fillRect(paddleTopX, 10, paddleWidth, paddleHeight);

  // Dashed Center Line
  context.beginPath();
  context.setLineDash([4]);
  context.moveTo(0, 350);
  context.lineTo(500, 350);
  context.strokeStyle = 'grey';
  context.stroke();

  // Ball
  context.beginPath();
  context.arc(ballX, ballY, ballRadius, 2 * Math.PI, false);
  context.fillStyle = 'white';
  context.fill();

  // Score
  context.font = '32px Courier New';
  context.fillText(playerScore, 20, canvas.height / 2 + 50);
  context.fillText(computerScore, 20, canvas.height / 2 - 30);
}

// Create Canvas Element
function createCanvas() {
  canvas.width = width;
  canvas.height = height;
  body.appendChild(canvas);
  renderCanvas();
}

// Reset Ball to Center
function ballReset() {
  ballX = width / 2;
  ballY = height / 2;
  speedY = -3;
  paddleContact = false;
}

// Adjust Ball Movement
function ballMove() {
  // Vertical Speed
  ballY += -speedY;
  // Horizontal Speed
  if (playerMoved && paddleContact) {
    ballX += speedX;
  }
}

// Determine What Ball Bounces Off, Score Points, Reset Ball
function ballBoundaries() {
  // Bounce off Left Wall
  if (ballX < 0 && speedX < 0) {
    speedX = -speedX;
  }
  // Bounce off Right Wall
  if (ballX > width && speedX > 0) {
    speedX = -speedX;
  }
  // Bounce off player paddle (bottom)
  if (ballY > height - paddleDiff) {
    if (ballX > paddleBottomX && ballX < paddleBottomX + paddleWidth) {
      paddleContact = true;
      // Add Speed on Hit
      if (playerMoved) {
        speedY -= 1;
        // Max Speed
        if (speedY < -5) {
          speedY = -5;
          computerSpeed = 6;
        }
      }
      speedY = -speedY;
      trajectoryX = ballX - (paddleBottomX + paddleDiff);
      speedX = trajectoryX * 0.3;
    } else if (ballY > height) {
      // Reset Ball, add to Computer Score
      ballReset();
      computerScore++;
    }
  }
  // Bounce off computer paddle (top)
  if (ballY < paddleDiff) {
    if (ballX > paddleTopX && ballX < paddleTopX + paddleWidth) {
      // Add Speed on Hit
      if (playerMoved) {
        speedY += 1;
        // Max Speed
        if (speedY > 5) {
          speedY = 5;
        }
      }
      speedY = -speedY;
    } else if (ballY < 0) {
      // Reset Ball, add to Player Score
      ballReset();
      playerScore++;
    }
  }
}

// Computer Movement
function computerAI() {
  if (playerMoved) {
    if (paddleTopX + paddleDiff < ballX) {
      paddleTopX += computerSpeed;
    } else {
      paddleTopX -= computerSpeed;
    }
  }
}

function showGameOverEl(winner) {
  // Hide Canvas
  canvas.hidden = true;
  // Container
  gameOverEl.textContent = '';
  gameOverEl.classList.add('game-over-container');
  // Title
  const title = document.createElement('h1');
  title.textContent = `${winner} Wins!`;
  // Button
  const playAgainBtn = document.createElement('button');
  playAgainBtn.setAttribute('onclick', 'startGame()');
  playAgainBtn.textContent = 'Play Again';
  // Append
  gameOverEl.append(title, playAgainBtn);
  body.appendChild(gameOverEl);
}

// Check If One Player Has Winning Score, If They Do, End Game
function gameOver() {
  if (playerScore === winningScore || computerScore === winningScore) {
    isGameOver = true;
    // Set Winner
    const winner = playerScore === winningScore ? 'Player 1' : 'Computer ';
    showGameOverEl(winner);
  }
}

// Called Every Frame
function animate() {
  renderCanvas();
  ballMove();
  ballBoundaries();
  computerAI();
  gameOver();
  if (!isGameOver) window.requestAnimationFrame(animate);
}

// Start Game, Reset Everything
function startGame() {
  if (isGameOver && !isNewGame) {
    body.removeChild(gameOverEl);
    canvas.hidden = false;
  }
  isGameOver = false;
  isNewGame = false;
  playerScore = 0;
  computerScore = 0;
  ballReset();
  createCanvas();
  animate();
  canvas.addEventListener('mousemove', (e) => {
    playerMoved = true;
    // Compensate for canvas being centered
    paddleBottomX = e.clientX - canvasPosition - paddleDiff;
    if (paddleBottomX < paddleDiff) {
      paddleBottomX = 0;
    }
    if (paddleBottomX > width - paddleWidth) {
      paddleBottomX = width - paddleWidth;
    }
    // Hide Cursor
    canvas.style.cursor = 'none';
  });
}

// On Load
startGame();
				
			

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top