xxxxxxxxxx
99
let classifier;
let video;
let label = 'waiting';
let counter = 0;
let currentMove = '';
let computerMove = '';
const moves = ['rock', 'paper', 'scissors'];
const emoji = {
rock: '✊',
paper: '🤚',
scissors: '✌️',
computer: '🤖',
};
function preload() {
classifier = ml5.imageClassifier('https://teachablemachine.withgoogle.com/models/jR-4BiMT/model.json');
}
function setup() {
createCanvas(windowWidth, windowHeight);
video = createCapture(VIDEO);
video.size(1280, 720);
video.hide();
classifyVideo();
textAlign(CENTER, CENTER);
}
function draw() {
background(0);
imageMode(CENTER);
image(ml5.flipImage(video), width / 2, height / 2, height * video.width / video.height, height);
if (currentMove == label) {
counter += 1;
} else if (computerMove == '') {
counter = 0;
currentMove = label;
}
fill(255);
if (computerMove != '') {
textSize(48);
text(`${emoji.computer}: ${emoji[computerMove]}`, width / 5, height / 8);
noLoop();
setTimeout(() => {
computerMove = '';
counter = 0;
loop();
}, 1500);
} else if (counter >= 10 && currentMove != 'neutral' && currentMove != '' && computerMove == '') {
computerMove = random(moves);
if ((computerMove == 'rock' && currentMove == 'paper') ||
(computerMove == 'paper' && currentMove == 'scissors') ||
(computerMove == 'scissors' && currentMove == 'rock')) { // win
textSize(64);
text('You win!', width / 2, height / 2);
} else if (computerMove == currentMove) { // tie
textSize(64);
text('Tie', width / 2, height / 2);
} else { // loose
textSize(64);
text('You lost...', width / 2, height / 2);
}
} else if (computerMove == '') {
classifyVideo();
}
if (['rock', 'paper', 'scissors'].includes(currentMove)) {
textSize(1);
text(emoji[currentMove], width / 2, height / 2);
} else if (currentMove == 'neutral') {
textSize(64);
text('Ready', width / 2, height / 2);
} else {
textSize(64);
text('Loading...', width / 2, height / 2);
noLoop();
}
}
function classifyVideo() {
classifier.classify(ml5.flipImage(video), gotResult);
}
function gotResult(error, results) {
if (error) {
console.error(error);
return;
}
label = results[0].label.toLowerCase();
loop();
}