WEEK 06
Web Games Development · HTML5 Lab
Audio, Video & Rewards
Create elements from code, control media from JavaScript, and reward correct answers with sound and video.
createElement
events
audio
video
Book: Chapter 6 · Quiz · pp. 179–210
Today · 90 minutes
Plan for the session
| Start | Segment | Time |
|---|---|---|
| 0:00 | Warm-up review | 10 min |
| 0:10 | This week’s game and objectives | 10 min |
| 0:20 | Concepts: idea, code, line by line, try it | 35 min |
| 0:55 | Common mistakes and check your understanding | 5 min |
| 1:00 | Lab: build the files | 25 min |
| 1:25 | Build-your-own task, recap and exit quiz | 5 min |
Week 6 · Audio, Video & Rewards
2 / 35
Warm-up · 5 minutes
Remember Week 5?
1
setTimeout or setInterval: which runs only once?
2
How does the memory game know two cards match?
3
What does a hit-test check?
4
How can you avoid picking the same item twice?
Week 6 · Audio, Video & Rewards
3 / 35
This week’s game
Put them in order and win a reward
In the book’s quiz, the player matches countries to capitals. The blocks are created by code, move when clicked, change colour on success, and a video plays as the reward.
The lab’s presidentsClick.html uses the same ideas: it picks presidents at random, you click them in order, and a correct answer plays “Hail to the Chief” and a fireworks video.
Good rule from the book: give feedback for every player action.
FROM THE BOOK
Chapter 6 · Quiz
pp. 179–210
YOU WILL BUILD
- presidentsClick.html
- hail_to_the_chief.mp3 / .ogg
- sfire3.webm / .mp4 / .ogv
Week 6 · Audio, Video & Rewards
4 / 35
Objectives
By the end of Week 6 you can…
01
Embed media with <audio> / <video> and several <source> fallbacks.
02
Control playback: play(), currentTime, muted.
03
Show and hide elements with visibility and display.
04
Create elements at runtime with createElement and appendChild.
05
Add and remove event listeners.
06
Pick several unique random items from an array.
07
Validate an ordering with a comparison loop.
08
Position elements with CSS position and inline styles.
Week 6 · Audio, Video & Rewards
5 / 35
Key words this week
Vocabulary
| Term | Meaning |
|---|---|
| DOM | The page’s elements, as objects that code can change |
| createElement | Makes a new element in code |
| appendChild | Adds an element to the page |
| textContent | The text inside an element |
| removeEventListener | Stops listening for an event |
| <source> | One file option for an audio or video element |
| visibility | hidden hides an element but keeps its space |
| display | none removes an element from the layout |
Week 6 · Audio, Video & Rewards
6 / 35
What the program must do
What a quiz needs
A knowledge base
Facts stored in an array of arrays.
Random questions
A different set each time, never the same fact twice.
Feedback
Colour and text change after every click.
A reward
Audio and video play natively in HTML5, with no plug-ins.
Week 6 · Audio, Video & Rewards
7 / 35
Big idea 1 · Creating elements
Build the page while it runs
1
Create
document.createElement
2
Fill
innerHTML / textContent
3
Add and place
appendChild, style.top, style.left
Week 6 · Audio, Video & Rewards
8 / 35
Example 1 · Creating elements
Build page elements with code
createElement makes an element; set its text and style; appendChild puts it on the page.
CODE · boxes.html · script
var names = ["Ada", "Grace", "Alan", "Tim"];
names.forEach(function (name, i) {
var box = document.createElement("div");
box.textContent = (i + 1) + ". " + name;
box.style.position = "absolute";
box.style.left = (20 + i * 170) + "px";
box.style.top = (20 + i * 100) + "px";
box.style.border = "3px double teal";
box.style.padding = "8px";
document.body.appendChild(box);
});
OUTPUT · elements created by the script
Week 6 · Audio, Video & Rewards
9 / 35
Line by line · Example 1
Build page elements with code
document.createElement("div")
Make a new, empty div (not on the page yet).
box.textContent = …
Put text inside it.
box.style.position = "absolute";
Place it with left and top.
(20 + i * 170) + "px"
Each box further right; CSS needs units.
document.body.appendChild(box);
Add it to the page, so it appears.
Week 6 · Audio, Video & Rewards
10 / 35
Try it · 5 minutes
Change the quiz size
- Change nq from 4 to 6.
- Change rowsize from 50 to 70.
- Refresh and play.
YOU SHOULD SEE
Six boxes appear, spaced further apart.
Week 6 · Audio, Video & Rewards
11 / 35
Big idea 2 · Checking an order
Correct means always increasing
1
Record
Each pick stores the fact’s original position.
2
Compare
Is slots[i] > slots[i+1] anywhere?
3
Decide
Any drop: WRONG. No drop: CORRECT.
Week 6 · Audio, Video & Rewards
12 / 35
Example 2 · Checking an order
Is the list in order?
Compare each item with the next one. One pair out of order is enough to fail.
CODE · order.html · script
function inOrder(list) {
for (var i = 0; i < list.length - 1; i++) {
if (list[i] > list[i + 1]) {
return false; // found a drop
}
}
return true; // no drops at all
}
document.write("2,5,9,11 → " +
inOrder([2, 5, 9, 11]) + "<br>");
document.write("2,9,5,11 → " +
inOrder([2, 9, 5, 11]));
OUTPUT · output of the two checks
Week 6 · Audio, Video & Rewards
13 / 35
Line by line · Example 2
Is the list in order?
i < list.length - 1
Stop one early: the last item has no next.
list[i] > list[i + 1]
Is this item bigger than the one after it?
return false;
Out of order: answer now and stop looking.
return true;
Reached the end with no drops.
inOrder([2, 9, 5, 11])
9 > 5, so the answer is false.
Week 6 · Audio, Video & Rewards
14 / 35
Try it · 5 minutes
Trace checkorder on paper
- slots = [2, 5, 9, 11]: CORRECT or WRONG?
- slots = [2, 9, 5, 11]: CORRECT or WRONG?
- For the second, at which i does the loop stop?
YOU SHOULD SEE
[2, 5, 9, 11] is CORRECT. [2, 9, 5, 11] is WRONG, and the loop stops at i = 1.
Week 6 · Audio, Video & Rewards
15 / 35
Big idea 3 · Audio & video
Hidden until earned
1
Load
Audio and video with several sources, hidden by CSS.
2
Trigger
checkorder finds the order is correct.
3
Reward
Make visible, set currentTime, play().
Week 6 · Audio, Video & Rewards
16 / 35
Example 3 · Audio & video
Players with fallback formats
List several sources; the browser plays the first it supports. Code can press play.
CODE · media.html
<audio id="song" controls>
<source src="win.mp3" type="audio/mpeg">
<source src="win.ogg" type="audio/ogg">
Your browser cannot play this audio.
</audio>
<video id="clip" width="320" controls muted>
<source src="fireworks.webm" type="video/webm">
<source src="fireworks.mp4" type="video/mp4">
</video>
<script>
// later, as a reward:
document.getElementById("song").play();
</script>
OUTPUT · no media files in this preview: empty players shown
Week 6 · Audio, Video & Rewards
17 / 35
Line by line · Example 3
Players with fallback formats
<audio controls>
An audio player with play and volume buttons.
<source src="win.mp3" …>
First choice of file.
<source src="win.ogg" …>
Backup, for browsers without mp3.
muted
Muted video is allowed to start by itself.
….play();
Start playing from code, e.g. as a reward.
Week 6 · Audio, Video & Rewards
18 / 35
Try it · 5 minutes
Change the reward
- Set song.currentTime to 0 and listen.
- Add a second audio element and play it on WRONG.
YOU SHOULD SEE
At 0 there are a few seconds of silence. Right and wrong answers now sound different.
Week 6 · Audio, Video & Rewards
19 / 35
Big idea 4 · Showing & hiding
Stylesheet sets the start; code changes it
1
CSS
.thing is absolute; audio and video start hidden.
2
Place
Code sets style.top and style.left for each box.
3
Reveal
Code sets visibility and display for the reward.
Week 6 · Audio, Video & Rewards
20 / 35
Example 4 · Showing & hiding
Hidden until earned
visibility:hidden hides but keeps the space. display:none removes the element from the layout.
CODE · reveal.html
<style>
.reward { visibility: hidden; color: darkorange; }
.gone { display: none; }
</style>
<p>Line one</p>
<p class="reward">You win!</p>
<p class="gone">Removed from the layout</p>
<p>Line two</p>
<script>
setTimeout(function () {
document.querySelector(".reward")
.style.visibility = "visible";
}, 2000);
OUTPUT · reward appears after 2 seconds
Week 6 · Audio, Video & Rewards
21 / 35
Line by line · Example 4
Hidden until earned
visibility: hidden;
Invisible, but still takes up its space.
display: none;
Gone from the layout: no space at all.
document.querySelector(".reward")
Find the first element with class reward.
.style.visibility = "visible"
Show it from code.
setTimeout(…, 2000)
Do it once, after two seconds.
Week 6 · Audio, Video & Rewards
22 / 35
Try it · 5 minutes
Move the quiz
- Change col1 from 20 to 400.
- Change the picked colour from gold to your own.
- Note: init() sets row1 from the window height.
YOU SHOULD SEE
The boxes appear further right, and picked boxes use your colour.
Week 6 · Audio, Video & Rewards
23 / 35
Common mistakes
When it goes wrong, check these first
The media never plays
Fix: Keep the mp3, ogg and video files in the Week6 folder. Browsers may need a click before sound plays.
A box can be picked twice
Fix: Call removeEventListener with the same function reference used to add it.
All boxes pile up at the top-left
Fix: Add "px" to top and left, and keep position:absolute on .thing.
A second round goes wrong
Fix: setupgame() clears facts[i][2] but checks facts[c][1]. Reset [1] so used facts are cleared for the next round.
Week 6 · Audio, Video & Rewards
24 / 35
Check your understanding · 1 of 4
What does appendChild do?
A
Deletes an element
B
Adds an element to the page
C
Copies CSS
D
Plays a video
Week 6 · Audio, Video & Rewards
25 / 35
Check your understanding · 2 of 4
Why call removeEventListener after a pick?
A
To run faster
B
So the box cannot be picked again
C
To hide the box
D
To reset the game
Week 6 · Audio, Video & Rewards
26 / 35
Check your understanding · 3 of 4
slots = [3, 8, 6, 10]. The result is…
A
CORRECT
B
WRONG
C
An error
D
Depends on nq
Week 6 · Audio, Video & Rewards
27 / 35
Check your understanding · 4 of 4
visibility:hidden vs display:none?
A
They are the same
B
hidden keeps its space; none removes it
C
none keeps its space
D
hidden deletes the element
Week 6 · Audio, Video & Rewards
28 / 35
Check your understanding
Answers
| Q | Answer | Why |
|---|---|---|
| Q1 | B · Adds an element to the page | createElement makes it; appendChild puts it on the page. |
| Q2 | B · So the box cannot be picked again | The box stops responding to clicks. |
| Q3 | B · WRONG | 8 > 6, so the order is broken. |
| Q4 | B · hidden keeps its space; none removes it | display:none takes the element out of the layout. |
Week 6 · Audio, Video & Rewards
29 / 35
Lab time · 25 minutes
Your workflow for every file
1
Folder
Create a folder named Week6.
2
Copy
Copy the example files and their images, audio or video into it.
3
Open
Open the folder in VS Code or Sublime Text.
4
Save
Edit, then save with Ctrl+S.
5
Check
Refresh the browser (F5). Open the console (F12).
Never edit the original example for grading. Work on a copy named with your name, for example presidentsClick_yourname.html.
Week 6 · Audio, Video & Rewards
30 / 35
Lab activity · presidentsClick.html
Build the quiz in six steps
| Step | Objectives | Checkpoint |
|---|---|---|
| Scaffold: styles, audio, video | 1, 8 | Page loads with the media hidden |
| facts array + variables | 6 | One entry per president, in order |
| setupgame() | 4, 5, 6, 8 | nq different boxes appear |
| pickelement() | 5, 6 | A picked box turns gold and is locked |
| checkorder() | 2, 3, 5, 7 | CORRECT plays sound and video |
| init() | 2, 8 | Runs from onload; boxes start halfway down |
Week 6 · Audio, Video & Rewards
31 / 35
Stuck?
A five-step debugging checklist
- Open the console (F12) and read the first red error.
- Check the spelling and capitals of every name and id.
- Check that brackets, braces and quotes come in pairs.
- Check file names, and that every file is in the same folder.
- Save, then hard-refresh with Ctrl+F5.
THIS WEEK’S TIP
After a round, type slots in the console to see the exact order the player clicked.
Week 6 · Audio, Video & Rewards
32 / 35
BUILD YOUR OWN · ALL OBJECTIVES
Show the answer and race the clock
Week6\presidentsClick_yourname.html
- On WRONG, display the correct order.
- Add a timer with Date that shows how long the player took.
- Bonus from the book: use images instead of names, or play several rounds.
Week 6 · Audio, Video & Rewards
33 / 35
How the build-your-own task is marked
Marking guide
| Criterion | What we look for | Marks |
|---|---|---|
| Runs cleanly | Opens with no errors in the console (F12) | 2 |
| Required features | The correct order is shown after WRONG; a working timer; the sound and video reward still work | 4 |
| Readable code | Indented, sensible names, a comment on each function | 2 |
| Your own touch | A personal change: colours, images, text or an extra feature | 2 |
| Total | 10 |
Week 6 · Audio, Video & Rewards
34 / 35
RECAP · CHAPTER 6 · QUIZ SUMMARY
What you can do now
- createElement, getElementById and appendChild.
- Click handling with addEventListener.
- Changing colours by changing CSS from code.
- An array of arrays for quiz content; for and do-while loops.
- video and source elements in several formats.
KEEP GOING
The rest of the book
Chapter 7 Mazes (arrow keys and local storage), 8 Rock-Paper-Scissors, 9 Hangman, 10 Blackjack.
Week 6 · Audio, Video & Rewards
35 / 35