0% found this document useful (0 votes)
60 views9 pages

HTML Random Number Game Tutorial

This tutorial guides beginners through creating a simple HTML, CSS, and JavaScript game that displays a random image of numbers 1-10 and allows users to guess the number. It covers project setup, coding the game logic, styling, sound feedback, and deployment options. The tutorial also suggests enhancements and testing tips to improve the game experience.

Uploaded by

2022astonuser1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views9 pages

HTML Random Number Game Tutorial

This tutorial guides beginners through creating a simple HTML, CSS, and JavaScript game that displays a random image of numbers 1-10 and allows users to guess the number. It covers project setup, coding the game logic, styling, sound feedback, and deployment options. The tutorial also suggests enhancements and testing tips to improve the game experience.

Uploaded by

2022astonuser1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

HTML Game Tutorial — Random Number

vs Random Picture
Goal: build a simple HTML + CSS + JavaScript game that shows a random picture of the
digits 1–10 and then selects a random number 1–10 to compare against the shown image. The
tutorial format is step-by-step, beginner-friendly, and includes code, explanations, and
deployment tips.

Page 1 — Overview & Learning Outcomes


What you will learn
• Project structure and required assets
• Basic HTML layout for a small game
• Styling with CSS for a clean UI
• JavaScript logic to load images, pick a random image, generate a random number, and
compare results
• Small polish: animations, sounds, scorekeeping, accessibility
• How to test and deploy the game (e.g., GitHub Pages or simple static hosting)

Who this tutorial is for


• Beginners who know basic HTML and JavaScript
• Hobbyists who want a small playable game to customize

Required tools
• Any text editor (VS Code, Sublime, Notepad++)
• A browser (Chrome, Firefox, Edge)
• Optional: Git and GitHub for deployment

Page 2 — Project Setup and Assets


File structure (example)
random-number-game/
├─ [Link]
├─ [Link]
├─ [Link]
└─ assets/
├─ numbers/
├─ [Link]
├─ [Link]
├─ ...
└─ [Link]
└─ sounds/
├─ correct.mp3
└─ wrong.mp3

Place 10 images of numbers ([Link] through [Link]) in assets/numbers/. These can be


simple PNGs with the numeral centered on a colored background. Keep file names numeric
to make logic easier.

Creating or sourcing images


• You can draw your own images or export numbered PNGs from a graphics tool.
• Make them the same size (e.g., 512×512 or 256×256) so layout is consistent.

Page 3 — HTML Skeleton ([Link])


Create [Link]. This file contains the game layout and elements the JS will control.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Random Number vs Picture — Mini Game</title>
<link rel="stylesheet" href="[Link]" />
</head>
<body>
<main class="game">
<h1>Guess or Match? Random Number vs Picture</h1>

<section class="board">
<div class="image-area" aria-live="polite">
<img id="numberImage" src="assets/numbers/[Link]" alt="Number 1" />
</div>

<div class="controls">
<button id="newImageBtn">Show Random Picture</button>
<button id="pickNumberBtn">Pick Random Number</button>
</div>

<div id="result" class="result" aria-live="polite"></div>

<div class="scoreboard">
Score: <span id="score">0</span>
</div>
</section>

<footer>
<small>Built with HTML, CSS & JavaScript — tutorial style</small>
</footer>
</main>
<script src="[Link]"></script>
</body>
</html>

Explanation

• #numberImage displays the currently shown picture (one of the 10 images).


• #newImageBtn makes the game show a new random picture.
• #pickNumberBtn makes the program randomly select a number between 1–10 and
compare it with the currently shown picture.
• #result shows text like "Correct!" or "Try again".
• #score keeps a simple running score.

Page 4 — CSS Styling ([Link])


Create [Link] for a simple, responsive layout and pleasant visuals.

:root{
--bg:#f7f9fc;
--card:#ffffff;
--accent:#2b8aef;
--success:#16a34a;
--danger:#ef4444;
--muted:#6b7280;
}

*{box-sizing:border-box}
body{font-family:Inter, system-ui, Arial, sans-serif; background:var(--bg);
margin:0; padding:24px; color:#111}
.game{max-width:720px;margin:0 auto;background:var(--
card);padding:24px;border-radius:12px;box-shadow:0 6px 20px
rgba(10,10,20,0.06)}
h1{font-size:1.4rem;margin:0 0 12px}
.board{display:grid;grid-template-columns:1fr;gap:16px;align-items:center}
.image-area{display:flex;justify-content:center;align-
items:center;padding:16px;border-radius:8px;background:#fafafa;border:1px
solid #eee}
.image-area img{max-width:240px;width:60%;height:auto;display:block}
.controls{display:flex;gap:10px;justify-content:center}
button{padding:10px 14px;border-radius:8px;border:0;background:var(--
accent);color:#fff;font-weight:600;cursor:pointer}
button:active{transform:translateY(1px)}
.result{min-height:28px;text-align:center;font-weight:700}
.scoreboard{color:var(--muted);text-align:center}

/* Result states */
.[Link]{color:var(--success)}
.[Link]{color:var(--danger)}

@media(min-width:800px){
.board{grid-template-columns:1fr 1fr}
.controls{grid-column:1 / -1}
}
Explanation

• Clean card-style layout with a centered image area.


• Buttons are styled for clarity and visual affordance.
• Result uses color classes (.correct, .wrong) which JavaScript will toggle.

Page 5 — JavaScript: Basics ([Link]) —


Part 1
Create [Link]. We'll start by wiring DOM elements and basic helpers.

// [Link]
const numberImage = [Link]('numberImage');
const newImageBtn = [Link]('newImageBtn');
const pickNumberBtn = [Link]('pickNumberBtn');
const resultDiv = [Link]('result');
const scoreSpan = [Link]('score');

let currentImageNumber = 1; // currently shown picture number (1-10)


let score = 0;

// Helper: pick random integer inclusive


function randInt(min, max){
return [Link]([Link]() * (max - min + 1)) + min;
}

// Helper: set result text + class


function showResult(text, state){
[Link] = text;
[Link]('correct','wrong');
if(state) [Link](state);
}

Explanation

• randInt(1, 10) will be used to pick random numbers.


• currentImageNumber keeps track of which image is currently displayed.
• showResult centralizes how we display results so CSS classes are applied
consistently.

Page 6 — JavaScript: Show Random


Picture & Preload Images — Part 2
Preloading images improves perceived performance and prevents flicker.
// Preload images
const images = [];
for(let i=1;i<=10;i++){
const img = new Image();
[Link] = `assets/numbers/${i}.png`;
images[i] = img; // store by index for easy access
}

function showRandomPicture(){
const n = randInt(1,10);
currentImageNumber = n;
// Set the image element src and alt for accessibility
[Link] = images[n].src;
[Link] = `Number ${n}`;
// clear previous result
showResult('');
}

// wire button
[Link]('click', showRandomPicture);

// show one on load


[Link]('load', showRandomPicture);

Explanation

• We store images[1]..images[10] to make mapping from index to image trivial.


• showRandomPicture() randomly chooses a number, updates currentImageNumber,
and updates the img element.

Page 7 — JavaScript: Picking a Random


Number & Comparison — Part 3
Now implement the logic used when the user clicks Pick Random Number.

function pickRandomNumberAndCompare(){
const picked = randInt(1,10);

// show the picked number to the player


// you can display both the numeric picked value and whether it's a match
if(picked === currentImageNumber){
showResult(`Picked ${picked} — Correct!`, 'correct');
score += 1;
playSound('correct');
} else {
showResult(`Picked ${picked} — Wrong. It was ${currentImageNumber}.`,
'wrong');
score = [Link](0, score - 1);
playSound('wrong');
}
[Link] = score;
}
[Link]('click', pickRandomNumberAndCompare);

Explanation

• The function generates a random number picked and compares it to


currentImageNumber.
• On correct guess, increment score; on wrong guess, decrement (but keep non-
negative).
• We call playSound() (defined next) for feedback — optional but nice.

Page 8 — JavaScript: Optional Sound


Feedback, Animations, and Edge Cases
Add simple sound play and button disable while audio plays to prevent accidental double-
clicks.

// sound map — these files are optional


const sounds = {
correct: 'assets/sounds/correct.mp3',
wrong: 'assets/sounds/wrong.mp3'
};

function playSound(key){
if(!sounds[key]) return;
const a = new Audio(sounds[key]);
[Link]().catch(()=>{});
}

// Prevent spamming the pick button: disable briefly


function disableButtonTemporarily(btn, ms=700){
[Link] = true;
setTimeout(()=> [Link] = false, ms);
}

// call it inside pickRandomNumberAndCompare if you want


// disableButtonTemporarily(pickNumberBtn, 700);

Accessibility & Edge Cases

• Use alt attributes on images (done earlier) so screen readers know what’s shown.
• Use aria-live="polite" on the image-area and result so assistive tech
announces updates.
• If assets fail to load, show a fallback message or use SVG numbers embedded in
HTML.

Page 9 — Enhancements and Ideas


Make the game more fun:

• Time-based challenge: add a countdown — the user must press "Pick Random
Number" before time runs out.
• Multiple lives instead of score: give 3 lives and end game when lives hit zero.
• Leaderboard: store high score in localStorage.
• Different modes:
o Player chooses a number and the game picks a picture — reverse the roles.
o Use actual photos of objects labeled 1–10 for a more visual challenge.
• Mobile improvements: make buttons larger and increase hit areas.

Example: store high score in localStorage


function saveHighScore(){
const high = Number([Link]('highscore') || 0);
if(score > high){
[Link]('highscore', score);
// notify the player
showResult(`New high score! ${score}`, 'correct');
}
}

Page 10 — Testing, Deployment & Final


Notes
Testing tips
• Test in different browsers.
• Test slow network or simulate slow CPUs (DevTools) to ensure images preload
correctly.
• Test keyboard-only use (tab order) and screen readers.

Deploying
1. GitHub Pages: push random-number-game repository with these files to GitHub,
enable Pages on main branch.
2. Netlify / Vercel: both accept static sites — drag & drop or connect repo.
3. Simple hosting: upload files to any static host.

Final checklist
• Images 1–10 named consistently and placed in assets/numbers/.
• Buttons wired and accessible.
• Graceful fallback for missing assets.
• Cross-browser tested.
Appendix: Full [Link] (complete)
// Full [Link] — copy/paste
const numberImage = [Link]('numberImage');
const newImageBtn = [Link]('newImageBtn');
const pickNumberBtn = [Link]('pickNumberBtn');
const resultDiv = [Link]('result');
const scoreSpan = [Link]('score');

let currentImageNumber = 1;
let score = 0;

function randInt(min, max){


return [Link]([Link]() * (max - min + 1)) + min;
}

function showResult(text, state){


[Link] = text;
[Link]('correct','wrong');
if(state) [Link](state);
}

// Preload images
const images = [];
for(let i=1;i<=10;i++){
const img = new Image();
[Link] = `assets/numbers/${i}.png`;
images[i] = img;
}

function showRandomPicture(){
const n = randInt(1,10);
currentImageNumber = n;
[Link] = images[n].src;
[Link] = `Number ${n}`;
showResult('');
}

function pickRandomNumberAndCompare(){
const picked = randInt(1,10);
if(picked === currentImageNumber){
showResult(`Picked ${picked} — Correct!`, 'correct');
score += 1;
playSound('correct');
} else {
showResult(`Picked ${picked} — Wrong. It was ${currentImageNumber}.`,
'wrong');
score = [Link](0, score - 1);
playSound('wrong');
}
[Link] = score;
// optional: prevent spam
[Link] = true;
setTimeout(()=> [Link] = false, 700);
}

// sound map
const sounds = { correct: 'assets/sounds/correct.mp3', wrong:
'assets/sounds/wrong.mp3' };
function playSound(key){ if(!sounds[key]) return; const a = new
Audio(sounds[key]); [Link]().catch(()=>{}); }

[Link]('click', showRandomPicture);
[Link]('click', pickRandomNumberAndCompare);
[Link]('load', showRandomPicture);

Thank you — the 10-page tutorial is complete. Feel free to ask me to export it to PDF or
DOCX, or to customize the design, add keyboard controls, or convert the images to inline
SVGs for total portability.

You might also like