PONG

by Carson Evans

HTML

<canvas id="canvas" width="800" height="600"></canvas>

CSS

html,body {
  background-color: #000;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
}

canvas {
  border: 1px dashed #fff;
}

JavaScript

const c = document.querySelector('#canvas');
const ctx = c.getContext("2d");
const keys = {};
const paddleSpeed = 5
const ballSize = 20;
const paddleWidth = 20;
const paddleHeight = 100;
const pos1 = [10, c.height / 2 - paddleHeight / 2];
const pos2 = [c.width - 30, c.height / 2 - paddleHeight / 2];
const ballPos = [c.width / 2 - ballSize / 2, c.height / 2 - ballSize / 2];
const state = {
	serving: 'left',
  
}

window.onkeydown = ({key}) => {
	keys[key] = true;
};

window.onkeyup = ({key}) => {
	keys[key] = false;
};

function draw() {
	ctx.beginPath();
	ctx.fillStyle = '#000';
	ctx.fillRect(0, 0, c.width, c.height);
  
  if (keys.w && pos1[1] >= 0) {
  	pos1[1] -= paddleSpeed;
  } else if (keys.s && pos1[1] <= c.height - paddleHeight) {
  	pos1[1] += paddleSpeed;
  }
  
  if (keys.ArrowUp && pos2[1] >= 0) {
  	pos2[1] -= paddleSpeed;
  } else if (keys.ArrowDown && pos2[1] <= c.height - paddleHeight) {
  	pos2[1] += paddleSpeed;
  }
  
  
  ctx.fillStyle = '#fff';
  ctx.fillRect(pos1[0], pos1[1], paddleWidth, paddleHeight);
  ctx.fillRect(pos2[0], pos2[1], paddleWidth, paddleHeight);
  ctx.fillRect(ballPos[0], ballPos[1], ballSize, ballSize);
  
  requestAnimationFrame(draw);
}

requestAnimationFrame(draw)