Hi everyone!
Today, I want to share a fun mini-project I built: a simple Rock Paper Scissors game using just HTML, CSS, and JavaScript. It’s a great project for beginners to practice JavaScript logic and DOM manipulation. Let me walk you through how it works!
What the Game Does
The game lets the user choose between Rock, Paper, or Scissors. The computer then randomly picks one of the three options. The result is displayed along with the running score for both the user and the computer.
HTML Structure
The HTML defines a simple layout with a title, three buttons, and two sections to display results and score.
<div class="layout">
<h1>Rock Paper Scissors</h1>
<div class="btns">
<button onclick="startGame('rock')">🪨Rock</button>
<button onclick="startGame('paper')">📃Paper</button>
<button onclick="startGame('scissors')">✂️Scissors</button>
</div>
<div id="result"></div>
<div id="score">user : 0 | computer : 0</div>
</div>
Styling with CSS
The CSS centers the content on the page and adds spacing between elements:
.layout {
border: 1px solid;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 20px;
}
JavaScript Game Logic
The startGame() function is where the magic happens:
let userScore = 0;
let computerScore = 0;
function startGame(userSelect) {
let options = ['rock', 'paper', 'scissors'];
let computerSelect = options[Math.floor(Math.random() * options.length)];
let result = '';
if (userSelect == computerSelect) {
result = `Both selected ${userSelect}`;
} else if (
(userSelect == 'rock' && computerSelect == 'scissors') ||
(userSelect == 'paper' && computerSelect == 'rock') ||
(userSelect == 'scissors' && computerSelect == 'paper')
) {
userScore++;
result = `You won! ${userSelect} beats ${computerSelect}`;
} else {
computerScore++;
result = `Computer won! ${computerSelect} beats ${userSelect}`;
}
document.getElementById('result').innerText = result;
document.getElementById('score').innerText = `user : ${userScore} | computer : ${computerScore}`;
}
Bug Fix
I fixed a small issue in the result message where the string syntax was incorrect. Originally it said:
result = You re won ${userSelect} beats ${computerSelect}
;
It should be:
result = You won! ${userSelect} beats ${computerSelect}
;
What I Learned
Random Selection
I used Math.random() and Math.floor() to let the computer randomly choose between rock, paper, and scissors.
Conditional Logic
I wrote if, else if, and else statements to compare the user's choice with the computer's and decide who wins.
Operators
I used comparison operators like ==, && (AND), and logical checks to compare values and conditions:
if (userSelect == computerSelect) { ... }
if ((userSelect == 'rock' && computerSelect == 'scissors') || ...)
CSS Flexbox Layout
I learned how to center items on the screen using Flexbox and add spacing using the gap property.
Top comments (0)