xxxxxxxxxx
123
//class for object where the id is either rock, paper, or scissors
class Obj {
constructor(x, y, speed, id) {
this.id = id;
this.x = x;
this.y = y;
this.size = 25;
//random speed and direction
this.dx = random(-speed, speed);
this.dy = random(-speed, speed);
}
//draw the object
myDraw() {
textSize(this.size);
textAlign(CENTER);
text(this.id, this.x, this.y);
}
//move the object
move() {
this.x += this.dx;
this.y -= this.dy;
}
//check for collisions with borders
checkForCollisions() {
if (this.x <= this.size || this.x >= width - this.size) {
this.dx = -this.dx;
}
if (this.y <= this.size * 1.4 || this.y >= height - this.size * 1.3) {
this.dy = -this.dy;
}
}
}
//function to check for collision of two objects (thisO and all the other objects)
function checkCollision(thisO) {
for (let i = 0; i < obj.length; i++) {
//check the distance between the two objects
let d = dist(
thisO.x,
thisO.y - thisO.size / 2,
obj[i].x,
obj[i].y - obj[i].size / 2
);
//if the two objects are within close proximity and are not the same apply the rock paper scissor rules
if (d <= thisO.size / 2 + obj[i].size / 2) {
// thisO.dx = -thisO.dx;
// thisO.dy = -thisO.dy;
// obj[i].dx = -obj[i].dx;
// obj[i].dy = -obj[i].dy;
if (obj[i].id == "📄" && thisO.id == "🪨") {
thisO.id = "📄";
} else if (obj[i].id == "✂️" && thisO.id == "📄") {
thisO.id = "✂️";
} else if (obj[i].id == "🪨" && thisO.id == "✂️") {
thisO.id = "🪨";
}
}
}
}
let obj = [];
let n = 27;
let mySpeed = 1;
function setup() {
createCanvas(500, 500);
background(255);
start();
}
function start() {
obj = [];
for (let i = 0; i < n; i++) {
obj.push(
new Obj(random(35, width - 50), random(35, height - 35), mySpeed, "✂️")
);
obj.push(
new Obj(random(35, width - 50), random(35, height - 35), mySpeed, "🪨")
);
obj.push(
new Obj(random(35, width - 50), random(35, height - 35), mySpeed, "📄")
);
}
for (let i = 0; i < obj.length; i++) {
obj[i].myDraw();
}
}
function mouseClicked() {
if (
mouseX >= 12.5 &&
mouseX <= width - 12.5 &&
mouseY >= height - 23 &&
mouseY <= height - 3
) {
start();
}
}
function draw() {
stroke(0);
fill(255);
rect(12.5, 12.5, width - 25, height - 40);
fill(200);
stroke(1);
rect(12.5, height - 23, width - 25, 20);
textSize(14);
textAlign(CENTER);
fill(1);
noStroke();
text("Restart", width / 2, height - 9);
for (let i = 0; i < obj.length; i++) {
obj[i].checkForCollisions();
obj[i].move();
obj[i].myDraw();
checkCollision(obj[i]);
}
}