PONG with SVG.js

Tutorial on https://css-tricks.com/pong-svg-js/

by Wout

HTML

<div id="pong"></div>

JavaScript

// define document width and height
var width = 450, height = 300

// create SVG document and set its size
var draw = SVG('pong').size(width, height)
draw.viewbox(0,0,450,300)


// draw background
var background = draw.rect(width, height).fill('#dde3e1')

// draw line
var line = draw.line(width/2, 0, width/2, height)
line.stroke({ width: 5, color: '#fff', dasharray: '5,5' })


// define paddle width and height
var paddleWidth = 15, paddleHeight = 80

// create and position left paddle
var paddleLeft = draw.rect(paddleWidth, paddleHeight)
paddleLeft.x(0).cy(height/2).fill('#00ff99')

// create and position right paddle
var paddleRight = paddleLeft.clone()
paddleRight.x(width-paddleWidth).fill('#ff0066')


// define ball size
var ballSize = 10

// create ball
var ball = draw.circle(ballSize)
ball.center(width/2, height/2).fill('#7f7f7f')


// define inital player score
var playerLeft = playerRight = 0

// create text for the score, set font properties
var scoreLeft = draw.text(playerLeft+'').font({
  size: 32,
  family: 'Menlo, sans-serif',
  anchor: 'end',
  fill: '#fff'
}).move(width/2-10, 10)

// cloning rocks!
var scoreRight = scoreLeft.clone()
  .text(playerRight+'')
  .font('anchor', 'start')
  .x(width/2+10)


// random velocity for the ball at start
var vx = 0, vy = 0

// AI difficulty
var difficulty = 2

// update is called on every animation step
function update(dt) {
  // move the ball by its velocity
  ball.dmove(vx*dt, vy*dt)

  // get position of ball
  var cx = ball.cx()
    , cy = ball.cy()
  
  // get position of ball and paddle
  var paddleLeftCy = paddleLeft.cy()

  // move the left paddle in the direction of the ball
  var dy = Math.min(difficulty, Math.abs(cy - paddleLeftCy))
  paddleLeftCy += cy > paddleLeftCy ? dy : -dy

  // constraint the move to the canvas area
  paddleLeft.cy(Math.max(paddleHeight/2, Math.min(height-paddleHeight/2, paddleLeftCy)))

  // check if we hit top/bottom borders
  if ((vy < 0 && cy <= 0) || (vy > 0 && cy >=...