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

              
                <canvas></canvas>

<p>
  <strong>Controls:</strong><br />
  Left Paddle - up and down arrows<br />
  Right Paddle - W and S (set enable_autopilot to false in JS)
</p>
              
            
!

CSS

              
                canvas {
  display: block;
  margin: 20px auto;
  border: 1px solid #666;
  // background-color: black;
}

p {
  line-height: 1.5;
  text-align: center;
}
              
            
!

JS

              
                (function() {
  console.clear()

  /**
   * INIT
   */

  // init canvas
  const canvas = document.querySelector('canvas')
  const ctx = canvas.getContext('2d')

  canvas.width = 900
  canvas.height = canvas.width / 1.6

  // globals
  const sizes = {
    paddle: {
      width: canvas.width / 50,
      height: canvas.height / 4
    },
    gutter: canvas.height / 20,
    score: canvas.width / 16.67
  }

  const bounds = {
    up: sizes.gutter,
    down: (canvas.height - sizes.gutter),
    left: sizes.gutter,
    right: (canvas.width - sizes.gutter)
  }

  const ballSpeed = 15
  
  const enable_autopilot = true

  /**
   * PADDLES
   */

  // Paddle constructor
  function Paddle(side = 'left') {
    let x = sizes.gutter
    if (side === 'right') {
      x = canvas.width - sizes.paddle.width - sizes.gutter
    }

    this.position = [x, sizes.gutter]
    this.velocity = 1
    this.score = 0
  }

  Paddle.prototype.incScore = function() {
    this.score += 1
    return this.score
  }

  Paddle.prototype.nextPosition = function(v) {
    let velocity = typeof v === 'number' ? v : this.velocity
    let [x, y] = this.position
    let nextY = y + (sizes.gutter * velocity)
    
    let inBounds = velocity > 0 ? nextY > bounds.down - sizes.paddle.height : nextY < bounds.up

    return {
      pos: nextY,
      outOfBounds: inBounds
    }
  }

  Paddle.prototype.move = function(v) {
    let velocity = typeof v === 'number' ? v : this.velocity
    let [x, y] = this.position
    let nextY = y + (sizes.gutter * velocity)
    
    let outOfBounds = velocity > 0 ? nextY > bounds.down - sizes.paddle.height : nextY < bounds.up
    if (outOfBounds) {
      if (typeof v === 'undefined') this.velocity *= -1
      return
    }

    this.position = [x, nextY]
  }
  
  Paddle.autopilot = function(paddle) {
    this.velocity = .25
    
    Paddle.autopilot.loop = setInterval(function() {
      paddle.move()
    }, 50)
  }
  
  Paddle.stopAutopilot = function() {
    if (Paddle.autopilot.loop) {
      clearInterval(Paddle.autopilot.loop)
    }
  }

  Paddle.prototype.render = function() {
    let [x, y] = this.position
    ctx.fillRect(x, y, sizes.paddle.width, sizes.paddle.height)

    let fontSize = sizes.score
    let xMod = this.score > 9 ? 3 : 2
    let scoreX = (canvas.width / 2) - (sizes.gutter * xMod)
    let scoreY = sizes.gutter + fontSize
    
    if (x > canvas.width / 2) {
      scoreX = (canvas.width / 2) + sizes.gutter
    }
    
    ctx.font = fontSize + 'px sans-serif'
    ctx.fillText(this.score, scoreX, scoreY)
  }

  /**
   * BALL
   */

  // ball constructor
  function Ball() {
    this.reset(ballSpeed)
  }

  Ball.prototype.reset = function(v) {
    this.position = [(canvas.width - sizes.gutter) / 2, canvas.height / 2]
    this.velocity = [-v, (-v * 1.5) * Math.random()]

    // uncomment to make the ball go back and forth at init paddle pos
    // this.position = [(canvas.width - sizes.gutter) / 2, canvas.height / 5]
    // this.velocity = [-v, 0]
  }

  Ball.prototype.nextPosition = function() {
    let [Px, Py] = this.position
    let [Vx, Vy] = this.velocity
    let [Nx, Ny] = [Px + Vx, Py + Vy]

    return {
      pos: [Nx, Ny],
      outOfBounds: Nx < bounds.left || Nx > bounds.right
    }
  }

  Ball.prototype.detectCollision = function(paddle) {
    let [Px, Py] = paddle.position
    let [Bx, By] = this.nextPosition().pos
    let vertical = (By > Py && By < Py + sizes.paddle.height)

    // left paddle
    if (Px < canvas.width / 2) {
      return Bx <= (Px + sizes.paddle.width + (sizes.gutter / 2)) && vertical
    }

    // right paddle
    if (Px > canvas.width / 2) {
      return Bx >= Px && vertical
    }

    return false
  }
  
  Ball.prototype.reflect = function(Py) {
    let [Bx, By] = this.nextPosition().pos
    let [Vx, Vy] = this.velocity
    let newVelocity = [(Vx * -1), (Vy * -1)]

    let quadSize = sizes.paddle.height / 4
    let quadrants = [
      { name: 'top', pos: (quadSize) + Py },
      { name: 'mid1', pos: (quadSize * 2) + Py },
      { name: 'mid2', pos: (quadSize * 3) + Py },
      { name: 'btm', pos: (quadSize * 4) + Py }
    ]

    this.velocity = quadrants.reduce((v, q) => {
      if (q.pos > By) {
        switch (q.name) {
          case 'top':
            v[1] += 8
            break
          case 'mid1':
            v[1] += 4
            break
          case 'mid2':
            v[1] -= 4
            break
          case 'btm':
            v[1] -= 8
            break
          default:
            break
        }
      }
      return v
    }, newVelocity)
  }

  Ball.prototype.move = function(state) {
    let { pos, outOfBounds } = this.nextPosition()
    let [Nx, Ny] = pos
    let [Vx, Vy] = this.velocity
    let collideLeft = this.detectCollision(state.left)
    let collideRight = this.detectCollision(state.right)
    let Py = collideLeft ? state.left.position[1] : state.right.position[1]

    // bounce off the walls
    if (Ny < bounds.up || Ny > bounds.down) {
      this.velocity = [Vx, (Vy * -1)]
    }

    // bounce off paddles
    if (collideLeft || collideRight) {
      this.reflect(Py)
    }

    this.position = pos
    if (outOfBounds && !(collideLeft || collideRight)) {
      if (Nx > canvas.width / 2) {
        state.left.incScore()
      } else {
        state.right.incScore()
      }

      this.reset(ballSpeed)
    }
  }

  Ball.prototype.render = function() {
    let [x, y] = this.position
    ctx.beginPath()
    ctx.arc(x, y, sizes.gutter / 2, 0, 2 * Math.PI)
    ctx.fill()
  }

  /**
   * RENDER & RUN
   */

  // render loop
  function renderBoard(state) {
    // clear
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    
    // draw bg
    ctx.fillStyle = 'black'
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    ctx.fillStyle = 'white'
    
    // pre-start state
    if (state === 'init') {
      ctx.font = (canvas.width / 16.67) + 'px sans-serif'
      ctx.fillText('Click to start', canvas.width / 3, canvas.height / 2)
      return
    }

    // draw midline
    ctx.fillRect(canvas.width / 2, 0, sizes.paddle.width / 3, canvas.height)

    state.left.render()
    state.right.render()
    state.ball.render()

    requestAnimationFrame(renderBoard.bind(null, state))
  }

  // setup
  function playPong() {
    var state = {
      left: new Paddle('left'),
      right: new Paddle('right'),
      ball: new Ball()
    }
    
    if (enable_autopilot) Paddle.autopilot(state.right)

    // run ball
    setInterval(state.ball.move.bind(state.ball, state), 50)

    // paddle controls
    document.addEventListener(enable_autopilot ? 'keydown' : 'keyup',
      e => {
        let dirs = [38, 40, 83, 87]
        if (dirs.indexOf(e.keyCode) === -1) return
        e.preventDefault()
        if (e.keyCode === 38) state.left.move(-1)
        if (e.keyCode === 40) state.left.move(1)
        if (enable_autopilot === false && e.keyCode === 83) state.right.move(1)
        if (enable_autopilot === false && e.keyCode === 87) state.right.move(-1)
      })

    // animate
    requestAnimationFrame(renderBoard.bind(null, state))
  }
  
  renderBoard('init')

  canvas.addEventListener('click', function(ev) {
    let started = ev.target.getAttribute('data-started')
    if (!started) {
      ev.target.setAttribute('data-started', true)
      playPong()
    }
  })

})()
              
            
!
999px

Console