xxxxxxxxxx
150
let sample = [];
let animation;
let key_input = 'a';
let socket = io("https://juicers.glitch.me");
function preload() {
sample[0] = loadSound('./se01.wav');
sample[1] = loadSound('./se02.wav');
sample[2] = loadSound('./se03.wav');
sample[3] = loadSound('./se04.wav');
sample[4] = loadSound('./se05.wav');
sample[5] = loadSound('./se06.wav');
}
function setup() {
createCanvas(windowWidth, windowHeight);
// Move socket listener here to avoid multiple event bindings
socket.on("message", function(data) {
key_input = data;
triggerAnimationAndSound(key_input);
});
}
function draw() {
background(0);
if (animation) {
animation.draw();
}
}
// Function to handle animations and sounds
function triggerAnimationAndSound(key_input) {
const validKeys = ['a', 's', 'd', 'f', 'g', 'h'];
let index = validKeys.indexOf(key_input);
if (index === -1 || !sample[index]) return; // Prevent errors
sample[index].stop(); // Stop currently playing sound
sample[index].play();
let animationClasses = [Anim_a, Anim_s, Anim_d, Anim_f, Anim_g, Anim_h];
animation = new animationClasses[index]();
}
// Detect keyboard input
function keyTyped() {
triggerAnimationAndSound(key);
}
// Animation A
class Anim_a {
constructor() {
this.x = width / 2;
this.y = height / 2;
this.diameter = 0;
this.speed = 10;
}
draw() {
noStroke();
fill(0, 127, 255);
ellipse(this.x, this.y, this.diameter, this.diameter);
this.diameter += this.speed;
}
}
// Animation S
class Anim_s {
constructor() {
this.width = 0;
this.speed = 80;
}
draw() {
noStroke();
fill(255, 192, 203);
rectMode(CORNER);
rect(0, 0, this.width, height);
this.width += this.speed;
}
}
// Animation D
class Anim_d {
constructor() {
this.rotate = 0;
this.size = 0;
this.speed = 50;
}
draw() {
push();
fill(255, 255, 0);
noStroke();
translate(width / 2, height / 2);
rotate(radians(this.rotate));
rectMode(CENTER);
rect(0, 0, this.size, this.size);
pop();
this.rotate += this.speed;
this.size += this.speed;
}
}
// Animation F
class Anim_f {
constructor() {
this.bgColor = 255;
this.speed = -2;
}
draw() {
noStroke();
fill(this.bgColor);
rect(0, 0, width, height);
this.bgColor += this.speed;
}
}
// Animation G
class Anim_g {
constructor() {
this.posy = height + 50;
}
draw() {
noStroke();
fill(255);
rect(0, this.posy - 50, width, 50);
rect(0, height - this.posy, width, 50);
this.posy *= 0.9;
}
}
// Animation H
class Anim_h {
constructor() {
this.width = width;
this.height = height;
}
draw() {
stroke(255);
strokeWeight(20);
noFill();
rectMode(CENTER);
rect(width / 2, height / 2, this.width, this.height);
this.width *= 0.7;
this.height *= 0.7;
rectMode(CORNER);
strokeWeight(1);
}
}