JSFiddle - React, Tailwind, and code Playground
by Josh Pullen
HTML
<canvas id="canvas">You need a newer browser to play this game.</canvas>
CSS
html, body {
margin:0px;
padding:0px;
width:100%;
height:100%;
overflow-x:hidden;
overflow-y:hidden;
}
#canvas {
background:#000;
width:100%;
height:100%;
}
JavaScript
/* Key input */
var keys = [];
function keyDown(e) {
keys[e.keyCode] = true;
e.preventDefault();
}
function keyUp(e) {
keys[e.keyCode] = false;
}
window.addEventListener("keydown", keyDown, false);
window.addEventListener("keyup", keyUp, false);
/* The ball */
var ball = {
width: 16,
height: 16,
x: window.innerWidth / 2 - this.width / 2,
y: window.innerHeight / 2 - this.height / 2,
xVel: (Math.random - 0.5) * 3,
yVel: (Math.random - 0.5) * 3,
color: "#ffffff",
update: function (){
this.x += this.xVel;
this.y += this.yVel;
if(this.y < 0) {this.y = 0; this.yVel *= -1;}
if(this.x < 0) {this.x = 0; this.xVel *= -1;}
if(this.y + this.height > window.innerHeight) {this.y = window.innerHeight - this.height; this.yVel *= -1;}
if(this.x + this.width > window.innerWidth) {this.x = window.innerWidth - this.width; this.xVel *= -1;}
}
};
/* The left paddle */
var paddle1 = {
height:50,
y: window.innerHeight / 2 - this.height / 2,
yVel: 0,
keyDir: 0, /* This keeps track of the user input. 1 makes the paddle go up, -1 is down, and 0 is nothing. */
controlSpeed: 2,
update: function (){
this.keyDir = 0;
if(keys[38]) {this.keyDir++;}
if(keys[40]) {this.keyDir--;}
this.yVel = (this.yVel + this.keyDir * this.controlSpeed) * 0.8;
this.y += this.yVel;
if(this.y < 0) {this.y = 0;}
if(this.y > window.innerHeight - this.height) {this.y = window.innerHeight - this.height;}
}
};
/* And now the right... */
var paddle2 = {
height:50,
y: window.innerHeight / 2 - this.height / 2,
yVel: 0,
keyDir: 0,
controlSpeed: 2,
update: function (){
this.keyDir = 0;
if(keys[87]) {this.keyDir++;}
if(keys[83]) {this.keyDir--;}
this.yVel = (this.yVel + this.keyDir * this.controlSpeed) * 0.8;
this.y += this.yVel;
if(this.y < 0) {this.y = 0;}
...