Canvas Pong

Pong created in canvas with a simple computer player. Try to beat the computer, or scroll down to learn more about the game.

Full source code is available in Github:
https://github.com/tanmancan/canvas-pong

Link

Computer Player

The game contains a simple computer player, that will track the ball and try to hit it back. Its movements are simulated to give the appearance of a thinking AI.

In order to simulate a delayed reaction, we use a setTimeout function.

const delay = Math.ceil(Math.random() * this.handicap);
window.setTimeout(() => {
  // Movement logic
}, delay);

To simulate the computer thinking and waiting for the ball, we restrict its movement based on certain conditions. The first condition will prevent the computer from tracking the ball when it is moving away. And the second condition, will keep the computer paddle near the center of the game board. Both of these restrictions will give the appearance of the computer waiting for the player to hit the ball back.

// If ball's position is 3/4th of the canvas away
const aiNoFollowThreshHold = ball.positionX >= canvas.canvasWidth * (0.75);

// If paddle is either in the top 1/4th of the canvas, 
// or the bottom 1/4th of the canvas
const aiRestThreshHold = (aiPaddle.positionY > canvas.canvasHeight * 0.25)
	&& (aiPaddle.positionY < this.canvasHeight * 0.75);

// Ball is moving right
if (ball.deltaX > 0) {
  if (aiNoFollowThreshHold && aiRestThreshHold) {
    // Do not move paddle vertically
    aiPaddle.deltaY = 0;
  }
}
Link

Playing Locally

The game can be played locally using Docker or Node. After starting the game using either method, visit http://localhost:8080 to start playing.

Docker

$ cd /path/to/canvas-pong
$ docker build -t canvas-pong .
$ docker-compose up

Node

$ cd /path/to/canvas-pong
$ npm install
$ npm run dev

More Work

Thumbnail for React Json Print
React, JSX, JSON, Node.js, NPM Package, Data Tree, Typescript