Project: rock, paper, scissors in JavaScript
A complete game against the machine: random numbers, conditions, scoreboard and game over. Play right here.
What you will build
The classic rock, paper, scissors against the computer, best of 5. Great for mastering Math.random(), if / else if and keeping state (the score) between plays.
Play here — it is the page's real JavaScript:
Step 1: the computer's move
Three options in an array. Math.random() gives a number between 0 and 1; we multiply it by 3 and round down to get an index (0, 1 or 2).
const OPCIONES = ["piedra", "papel", "tijera"];
function jugadaOrdenador() {
const indice = Math.floor(Math.random() * 3); // 0, 1 o 2
return OPCIONES[indice];
}
Step 2: who wins
There are only three ways to win. If it's not a draw and you don't win, the machine wins.
function gana(a, b) {
return (a === "piedra" && b === "tijera") ||
(a === "papel" && b === "piedra") ||
(a === "tijera" && b === "papel");
}
true/false expression) is cleaner than an if with return true / return false.Step 3: one round
We compare, update the score and show it.
let puntosTu = 0;
let puntosCpu = 0;
function ronda(tuJugada) {
const cpu = jugadaOrdenador();
if (tuJugada === cpu) {
console.log("Empate");
} else if (gana(tuJugada, cpu)) {
puntosTu++;
console.log("Ganas la ronda");
} else {
puntosCpu++;
console.log("Gana la CPU");
}
console.log(`Marcador: ${puntosTu} - ${puntosCpu}`);
}
Step 4: game over and buttons
Best of 5: the first to reach 5 wins. We wire each button to ronda().
const META = 5;
function comprobarFinal() {
if (puntosTu === META) console.log("🏆 ¡Ganas la partida!");
if (puntosCpu === META) console.log("💥 Gana la CPU");
}
document.querySelectorAll("#ppBotones button").forEach(boton => {
boton.addEventListener("click", () => {
if (puntosTu < META && puntosCpu < META) {
ronda(boton.dataset.op);
comprobarFinal();
}
});
});
Where to go next
- Add "lizard" and "Spock" (rock-paper-scissors-lizard-Spock).
- Save the best streak in
localStorage. - Animate the computer's hand before showing the result with
setTimeout. - Make the computer "learn": have it play whatever beats your most repeated move.