Pong

by Tsskyx

HTML

<canvas id="gameWindow" width="600" height="500"></canvas>

JavaScript

var canvas, ctx, p, ball, ai, mouseY, game = false, difficulty = 0.15, divLine = 40, goal = 10;
window.onload = function() {
	canvas = document.getElementById("gameWindow");
	ctx = canvas.getContext("2d");
  ctx.textAlign = "center";
 	ctx.font = "40px Arial";
  canvas.addEventListener("mousemove", function(event) {
		mouseY = event.clientY - canvas.getBoundingClientRect().top - document.documentElement.scrollTop;
	});
  canvas.addEventListener("click", function() {
    game = !game;
    ball.reset(0, 0);
	});
  ball = new Ball();
  p = new Player();
  ai = new AI();
	setInterval(function() {
		ctx.fillStyle = "black";
		ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.strokeStyle = "white";
    ctx.lineWidth = 3;
    ctx.setLineDash([canvas.height/divLine, canvas.height/divLine]);
    ctx.beginPath();
		ctx.moveTo(canvas.width/2, canvas.height/divLine/2);
		ctx.lineTo(canvas.width/2, canvas.height);
		ctx.stroke();
    ctx.fillStyle = "white";
    ball.display();
    p.display();
		ai.display();
	}, 1000/60);
}
function Ball() {
	this.rad = 8;
  this.speed = 8;
  this.pos = {
  	x: canvas.width/2,
    y: canvas.height/2
  }
  this.dir = {
  	x: -1,
    y: 0
  }
  this.reset = function(res, ang) {
  	switch (Math.sign(res)) {
    	case -1:
      	ai.score++;
        break;
      case 1:
      	p.score++;
        break;
      case 0:
      	ai.score = 0;
        p.score = 0;
    }
  	if (p.score == goal || ai.score == goal) {
    	game = false;
    } else {
    	this.pos.x = canvas.width/2;
    	this.pos.y = (ang) ? constrain(Math.random()*canvas.height/2, this.rad) : canvas.height/2;
    	this.dir.x = (res < 0) ? 1 : -1;
    	this.dir.y = (ang) ? 0.5 : 0;
    }
  }
  this.display = function() {
  	if (game) {
  		this.pos.x += this.dir.x * this.speed;
    	this.pos.y += this.dir.y * this.speed;
    }
    this.dir.y = (this.pos.y < this.rad) ? Math.abs(this.dir.y) : (this.pos.y > canvas.height - this.rad) ? -Math.abs(this.dir.y) : this.dir.y;
    if...