Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!--design - https://dribbble.com/shots/16962160-Pong-49th-Birthday-Design  -->
<body>
    <div class="pong-container">
      <h1>pong</h1>
      <div id="pong" class="pong-square">
        <canvas id="canvas" width="400" height="300"></canvas>
      </div>

      <hr />

      <div class="player-score">
        <div class="player">
          <h3>Computer</h3>
          <span id="leftScore">0</span>
        </div>
        <h1 class="player">Atari</h1>
        <div class="player">
           <h3>You</h3>
          <span id="rightScore">0</span>
        </div>
      </div>
    </div>

    <script src="./script.js" type="module"></script>
  </body>
</html>

              
            
!

CSS

              
                body {
  font-family: sans-serif;
  background-color: #603813;
  overflow: hidden;
}

.pong-container {
  position: absolute;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 2rem;
  background: #fded22;
  width: 40vw;
  max-height: 65vh;
  top: 50%;
  left: 50%;
  translate: -50% -50%;
  border-radius: 30px;
  gap: 1rem;

}

.pong-container > h1 {
  text-transform: uppercase;

}

.pong-container .pong-square {
  background-color: #2e1305;
  width: 400px;
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 2rem;
  border-radius: 03px;
}

.pong-container .pong-square > canvas {
  border-radius: 30px;
}

hr {
  border: 5px solid #2e1305;
  border-radius: 5px;
  width: 100%;
  margin: 20px 0;
}

.player-score {
  margin: 0 2rem;
  background-color: #c8b299;
  width: 80%;
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  border-radius: 10px;
}

.player-score .player {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.player-score .player > span {
  font-size: 1.2rem;
  font-weight: 900;
}



.player-score h1 {
  text-transform: uppercase;
}
              
            
!

JS

              
                let canvas = document.querySelector("#canvas");
let pong = document.querySelector("#pong");
let leftScore = document.querySelector("#leftScore");
let rightScore = document.querySelector("#rightScore");
let ctx = canvas.getContext("2d");

let width = canvas.width;
let height = canvas.height;

const MAX_COMPUTER_SPEED = 2;

const BALL_SIZE = 8;

let ballPosition;

let xSpeed;
let ySpeed;

function initBall() {
  ballPosition = { x: 20, y: 30 };
  xSpeed = 4;
  ySpeed = 2;
}

const PADDLE_WIDTH = 5;
const PADDLE_HEIGHT = 30;
const PADDLE_OFFSET = 10;

let leftPaddleTop = 10;
let rightPaddleTop = 30;

let computerScore = 0;
let userScore = 0;

let gameOver = false;

// Event listeners
document.addEventListener("mousemove", (event) => {
  rightPaddleTop = event.y - canvas.offsetTop - pong.offsetTop - PADDLE_HEIGHT;
});

function drawCanvas() {
  // canvas bg-color
  ctx.fillStyle = "#a0887a";
  ctx.fillRect(0, 0, width, height);

  // all items on the canvas will be white
  ctx.fillStyle = "white";

  // draw ball
  ctx.beginPath();
  ctx.arc(ballPosition.x, ballPosition.y, BALL_SIZE, 0, Math.PI * 2, false);
  ctx.fill();

  // draw dividing line
  ctx.beginPath();
  ctx.moveTo(width / 2, 0);
  ctx.lineTo(width / 2, height);
  ctx.setLineDash([10, 8]);
  ctx.lineWidth = 5;
  ctx.strokeStyle = "white";
  ctx.stroke();

  // draw left paddle
  ctx.fillRect(PADDLE_OFFSET, leftPaddleTop, PADDLE_WIDTH, PADDLE_HEIGHT);

  // draw right paddle
  ctx.fillRect(
    width - PADDLE_WIDTH - PADDLE_OFFSET,
    rightPaddleTop,
    PADDLE_WIDTH,
    PADDLE_HEIGHT
  );

  // Draw scores
  (ctx.font = "40px monospace"), (ctx.textAlign = "left");
  ctx.fillText(computerScore.toString(), 50, 50);
  ctx.textAlign = "right";
  ctx.fillText(userScore.toString(), width - 50, 50);
}

function followBall() {
  let ball = {
    top: ballPosition.y,
    bottom: ballPosition.y + BALL_SIZE,
  };

  let leftPaddle = {
    top: leftPaddleTop,
    bottom: leftPaddleTop + PADDLE_HEIGHT,
  };

  if (ball.top < leftPaddle.top) {
    leftPaddleTop -= MAX_COMPUTER_SPEED;
    return;
  }

  if (ball.bottom > leftPaddle.top) {
    leftPaddleTop += MAX_COMPUTER_SPEED;
    return;
  }
}

function updateBallPosition() {
  ballPosition.x += xSpeed;
  ballPosition.y += ySpeed;
  followBall();
}

function checkPaddleCollision(ball, paddle) {
  return (
    ball.left < paddle.right &&
    ball.right > paddle.left &&
    ball.top < paddle.bottom &&
    ball.bottom > paddle.top
  );
}

function adjustAngle(distanceFromTop, distanceFromBottom) {
  if (distanceFromTop < 0) {
    ySpeed -= 0.5;
    return;
  }

  if (distanceFromBottom < 0) {
    ySpeed += 0.5;
  }
}

function checkCollision() {
  let ball = {
    left: ballPosition.x,
    right: ballPosition.x + BALL_SIZE,
    top: ballPosition.y,
    bottom: ballPosition.y + BALL_SIZE,
  };

  let leftPaddle = {
    left: PADDLE_OFFSET,
    right: PADDLE_OFFSET + PADDLE_WIDTH,
    top: leftPaddleTop,
    bottom: leftPaddleTop + PADDLE_HEIGHT,
  };

  let rightPaddle = {
    left: width - PADDLE_WIDTH - PADDLE_OFFSET,
    right: width - PADDLE_OFFSET,
    top: rightPaddleTop,
    bottom: rightPaddleTop + PADDLE_HEIGHT,
  };

  if (checkPaddleCollision(ball, leftPaddle)) {
    // check if left paddle collision occurred
    let distanceFromTop = ball.top - leftPaddle.top;
    let distanceFromBottom = leftPaddle.bottom - ball.bottom;
    adjustAngle(distanceFromTop, distanceFromBottom);
    xSpeed = Math.abs(xSpeed);
    return;
  }

  if (checkPaddleCollision(ball, rightPaddle)) {
    // check if right paddle collision occurred
    let distanceFromTop = ball.top - rightPaddle.top;
    let distanceFromBottom = rightPaddle.bottom - ball.bottom;
    adjustAngle(distanceFromTop, distanceFromBottom);
    xSpeed = -Math.abs(xSpeed);
    return;
  }

  if (ball.left < 0) {
    userScore++;
    rightScore.innerText = userScore;
    initBall();
    return;
  }

  if (ball.right > width) {
    computerScore++;
    leftScore.innerText = computerScore;
    initBall();
    return;
  }

  if (computerScore > 9 || userScore > 9) {
    gameOver = true;
  }

  if (ball.top < 0 || ball.bottom > height) {
    ySpeed = -ySpeed;
    return;
  }
}

function drawGameOver() {
  ctx.fillStyle = "white";
  ctx.font = "30px monospace";
  ctx.textAlign = "center";
  ctx.fillText("GAME OVER", width / 2, height / 2);

  if (computerScore > 9) {
    ctx.fillStyle = "white";
    ctx.font = "30px monospace";
    ctx.textAlign = "center";
    ctx.fillText("Player 1 Won!", width / 2, height / 2 + PADDLE_HEIGHT);
    return;
  }

  if (userScore > 9) {
    ctx.fillStyle = "white";
    ctx.font = "30px monospace";
    ctx.textAlign = "center";
    ctx.fillText("Player 2 Won!", width / 2, height / 2 + PADDLE_HEIGHT);
    return;
  }
}

function gameLoop() {
  drawCanvas();
  updateBallPosition();
  checkCollision();

  if (gameOver) {
    drawCanvas();
    drawGameOver();
    return;
  }

  setTimeout(gameLoop, 30);
}

initBall();
gameLoop();

              
            
!
999px

Console