// Cloned by Josh W on 5 Dec 2022 from World "websocket test" by Conall
// Please leave this clone trail here.
class Player {
constructor(x) {
this.x = x;
this.y = 400;
this.h = 90;
this.w = 15;
this.points = 0;
}
update_pos(y){
this.y = y;
}
draw(){
fill('#ffffff');
rect(this.x, this.y, this.w, this.h);
}
move(amount){
this.y += amount;
}
}
class Score{
constructor(x){
this.x = x
this.y = 700
this.points = 0
}
draw(player1, player2){
fill('#ffffff');
textSize(24);
text(player1.points + '\t:\t' + player2.points, 380, 50);
}
}
class Ball{
constructor(){
this.x = 400;
this.y = 400;
this.vel_x = 2;
this.vel_y = 5;
this.r = 10
}
update_pos(){
if (this.x < 10) {
this.x = 400;
this.y = 400;
this.vel_x = 2
}
if (this.x > 800 - 10) {
this.x = 400;
this.y = 400;
this.vel_x = -2
}
if (this.y < 10 || this.y > 800 - 10) {
this.vel_y *= -1;
}
this.x += this.vel_x;
this.y += this.vel_y;
}
update_score_p1(player){
if (this.x > 800 - 10){
player.points += 1;
}
}
update_score_p2(player){
if (this.x < 10) {
player.points += 1;
}
}
check_collision(player) {
// if ball collides on x-axis
if ((player.x - this.r) < this.x && this.x < (player.x + player.w + this.r)) {
// and on y-axis
if ((player.y - this.r) < this.y && this.y < (player.y + player.h + this.r)) {
this.vel_x *= -2
}
}
}
draw(){
fill(255);
ellipse(this.x, this.y, this.r * 2);
}
respawn() {
this.x = 400
this.y = 400
}
}
AB.socketStart();
// Canvas
function setup() {
createCanvas(800, 800);
left = new Player(30);
right = new Player(800 - 50);
score = new Score();
ball = new Ball();
}
function draw() {
// Background
background(0);
ball.draw();
left.draw();
right.draw();
ball.update_pos();
ball.update_score_p1(left);
ball.update_score_p2(right);
score.draw(left, right);
ball.check_collision(left);
ball.check_collision(right);
if (keyIsDown(87)) { // W
left.move(-10);
} else if (keyIsDown(83)) { // S
left.move(10);
}
if (keyIsDown(UP_ARROW)) {
right.move(-10);
} else if (keyIsDown(DOWN_ARROW)) {
right.move(10);
}
if ( AB.socket ){
if ( AB.socket.connected ){
AB.socketOut([left.x, left.y, right.x, right.y, ball.x, ball.y, ball.vel_x, ball.vel_y]);
}
}
}
AB.socketIn = function(array) // incoming data on socket
{
left.x = array[0];
left.y = array[1];
right.x = array[2];
right.y = array[3];
ball.x = array[4];
ball.y = array[5];
ball.vel_x = array[6];
ball.vel_y = array[7];
};