xxxxxxxxxx
131
// Final P - PING PONG
let player1;
let player2;
let ball;
let player1Score = 0;
let player2Score = 0;
function preload() {
ballImg = loadImage('ball.png');
}
function setup() {
createCanvas(800, 400);
player1 = new Player(20, height / 2);
player2 = new Player(width - 20, height / 2);
ball = new Ball();
}
function draw() {
background(0);
player1.display();
player2.display();
ball.display();
player1.update();
player2.update();
ball.update();
// Player collisions
if (ball.hits(player1) || ball.hits(player2)) {
ball.reflectX();
}
// Top and bottom border collision
if (ball.y < 0 || ball.y > height) {
ball.reflectY();
}
// Score
if (ball.x > width) {
player1Score++;
ball.reset();
} else if (ball.x < 0) {
player2Score++;
ball.reset();
}
// Show score
textSize(32);
fill(255);
textAlign(CENTER);
text(player1Score + " - " + player2Score, width / 2, 50);
// User instructions
textSize(17);
text("Use W and S to move", 100, height - 20);
}
class Player {
constructor(x, y) {
this.x = x;
this.y = y;
this.height = 80;
this.width = 20;
this.speed = 5;
}
display() {
fill(255);
rect(this.x, this.y - this.height / 2, this.width, this.height);
}
update() {
if (keyIsDown(87)) { // W
this.y -= this.speed;
}
if (keyIsDown(83)) { // S
this.y += this.speed;
}
// Limit movement within canvas
this.y = constrain(this.y, this.height / 2, height - this.height / 2);
}
}
class Ball {
constructor() {
this.x = width / 2;
this.y = height / 2;
this.diameter = 20;
this.speedX = random(-5, 5);
this.speedY = random(-5, 5);
}
display() {
image(ballImg, this.x, this.y, this.diameter, this.diameter);
}
update() {
this.x += this.speedX;
this.y += this.speedY;
}
hits(player) {
if (this.x + this.diameter / 2 >= player.x &&
this.x - this.diameter / 2 <= player.x + player.width &&
this.y + this.diameter / 2 >= player.y - player.height / 2 &&
this.y - this.diameter / 2 <= player.y + player.height / 2) {
return true;
}
return false;
}
reflectX() {
this.speedX *= -1;
}
reflectY() {
this.speedY *= -1;
}
reset() {
this.x = width / 2;
this.y = height / 2;
this.speedX = random([-5, 5]);
this.speedY = random([-5, 5]);
}
}