WEEK 02

Web Games Development · HTML5 Lab

Canvas & the Dice Game

Draw with <canvas>, roll random numbers, and build the casino game Craps with real game state.

canvas

Math.random

functions

if & switch

Book: Chapter 2 · Dice Game · pp. 21–65

Today · 90 minutes

Plan for the session

StartSegmentTime
0:00Warm-up review10 min
0:10This week’s game and objectives10 min
0:20Concepts: idea, code, line by line, try it35 min
0:55Common mistakes and check your understanding5 min
1:00Lab: build the files25 min
1:25Build-your-own task, recap and exit quiz5 min

Week 2 · Canvas & the Dice Game

2 / 36

Warm-up · 5 minutes

Remember Week 1?

1

What is the difference between a tag and an attribute?

2

Which selector styles the element with id="score"?

3

How does a button run JavaScript?

4

Where do CSS rules go in a one-file page?

Week 2 · Canvas & the Dice Game

3 / 36

This week’s game

Craps: roll two dice, follow the rules

The player throws two dice and only the sum counts: 1 + 3 is the same as 2 + 2. The first throw can win or lose straight away, or set a “point” that must be thrown again.

The dice are drawn on the canvas with code each time, so the game needs no images.

We build it in stages: one die, then two dice, then the full game. A correct game lets the player lose as well as win.

FROM THE BOOK

Chapter 2 · Dice Game
pp. 21–65


YOU WILL BUILD

  • singleDie.html
  • twoDie.html
  • diceGame.html

Week 2 · Canvas & the Dice Game

4 / 36

The rules we must code

Craps in one table

ThrowSum of the diceResult
First throw7 or 11Player wins
First throw2, 3 or 12Player loses
First throw4, 5, 6, 8, 9, 10Sum becomes the point: throw again
Follow-upThe pointPlayer wins
Follow-up7Player loses
Follow-upAnything elseKeep throwing

The number of throws is never fixed. That is why the program must keep track of the state of the game.

Week 2 · Canvas & the Dice Game

5 / 36

Objectives

By the end of Week 2 you can…

01

Create a canvas and get its 2D context with getContext('2d').

02

Draw rectangles and circles with fillRect, strokeRect and arc.

03

Set colours with fillStyle, strokeStyle and lineWidth.

04

Produce random integers with Math.random() and Math.floor().

05

Respond to a button click with an onclick handler.

06

Read and write form fields with document.f.name.value.

07

Model game state with variables: the point and the first turn.

Week 2 · Canvas & the Dice Game

6 / 36

Key words this week

Vocabulary

TermMeaning
canvasAn HTML element you draw on with JavaScript
context (ctx)The object with the drawing methods, from getContext('2d')
coordinateAn (x, y) position; (0, 0) is the top-left corner
pseudo-randomNumbers that look random but are calculated
functionA named block of code you can run again and again
variableA named value the program remembers
stateWhat the game remembers right now: first throw? the point?
switchChooses which code to run by matching a value

Week 2 · Canvas & the Dice Game

7 / 36

What the program must do

What a dice game needs

Randomness

A built-in pseudo-random method makes each throw look unpredictable.

Application state

Remember whether this is a first or a follow-up throw, and the point.

Decisions

if and switch apply the rules to the sum.

Feedback

A button throws; drawn dice and text fields show stage, point and outcome.

Week 2 · Canvas & the Dice Game

8 / 36

Big idea 1 · Random numbers

From 0–1 to a die: scale, floor, shift

1

Scale

× 6 gives 0 up to (not including) 6.

2

Floor

Drop the fraction: 0 to 5.

3

Shift

+ 1 gives 1 to 6.

Week 2 · Canvas & the Dice Game

9 / 36

Example 1 · Random numbers

Rolling dice with Math.random

Math.random() gives 0 up to 1. Scale it, round it down, shift it: a die roll.

CODE · rolls.html

<p id="out"></p>
<script>
  var rolls = [];
  for (var i = 0; i < 10; i++) {
    var die = 1 + Math.floor(Math.random() * 6);
    rolls.push(die);
  }
  document.getElementById("out").textContent =
    rolls.join("  ");
</script>

OUTPUT · new rolls every 1.5 seconds

Week 2 · Canvas & the Dice Game

10 / 36

Line by line · Example 1

Rolling dice with Math.random

Math.random()

A decimal from 0 up to (not including) 1.

Math.random() * 6

Now from 0 up to (not including) 6.

Math.floor(…)

Round down to a whole number: 0 to 5.

1 + …

Shift up: a die value from 1 to 6.

rolls.join("  ")

Turn the list into text, two spaces apart.

Week 2 · Canvas & the Dice Game

11 / 36

Try it · 5 minutes

Test your random numbers

  1. Open the console (F12).
  2. Type 1+Math.floor(Math.random()*6) ten times.
  3. Change 6 to 20 for a 20-sided die.
  4. Write the formula for a number 0–9.

YOU SHOULD SEE

Only values 1–6 appear, never 0 or 7. The 0–9 formula is Math.floor(Math.random()*10).

Week 2 · Canvas & the Dice Game

12 / 36

Big idea 2 · Drawing on a canvas

Canvas coordinates start at the top-left

1

x

Grows to the right.

2

y

Grows downward, not up.

3

Pixels

Everything is measured in pixels inside the canvas.

Week 2 · Canvas & the Dice Game

13 / 36

Example 2 · Drawing on a canvas

Shapes on a coordinate grid

The canvas is a pixel grid: (0, 0) is top-left, x grows right, y grows down.

CODE · shapes.html

<canvas id="c" width="300" height="200"></canvas>
<script>
  var ctx = document.getElementById("c")
              .getContext("2d");
  ctx.lineWidth = 4;
  ctx.strokeRect(20, 20, 160, 160);  // outline
  ctx.fillStyle = "crimson";
  ctx.beginPath();
  ctx.arc(100, 100, 18, 0, 2 * Math.PI);
  ctx.fill();                        // dot
  ctx.fillStyle = "navy";
  ctx.fillRect(210, 40, 70, 120);    // bar
</script>

OUTPUT · canvas 300 × 200, shown enlarged

Week 2 · Canvas & the Dice Game

14 / 36

Line by line · Example 2

Shapes on a coordinate grid

getContext("2d")

The object that holds all drawing tools.

strokeRect(20, 20, 160, 160)

Outline: left, top, width, height.

fillStyle = "crimson"

The colour for the next filled shape.

arc(100, 100, 18, 0, 2*Math.PI)

Circle: centre x, y, radius, full turn.

fillRect(210, 40, 70, 120)

A solid rectangle.

Week 2 · Canvas & the Dice Game

15 / 36

Try it · 5 minutes

Draw a three

  1. Draw a second die outline at (200, 50).
  2. Add three dots in a diagonal: top-left, centre, bottom-right.
  3. Change the dot colour.

YOU SHOULD SEE

A second square with three diagonal dots in your colour.

Week 2 · Canvas & the Dice Game

16 / 36

Big idea 3 · Buttons & form fields

Buttons send input in; fields show results

1

Click

The button calls throwdice().

2

Compute

The code draws the dice and applies the rules.

3

Show

document.f.outcome.value = … updates the form.

Week 2 · Canvas & the Dice Game

17 / 36

Example 3 · Buttons & form fields

Show results in a form field

Give a form a name, and code can read or write any field inside it through .value.

CODE · roll.html

<button onclick="roll()">Roll</button>
<form name="f">
  Result: <input name="result">
  Rolls: <input name="count" value="0">
</form>
<script>
  function roll() {
    var d = 1 + Math.floor(Math.random() * 6);
    document.f.result.value = "You rolled " + d;
    var n = Number(document.f.count.value);
    document.f.count.value = n + 1;
  }
</script>

OUTPUT · demo clicks Roll every 1.5 seconds

Week 2 · Canvas & the Dice Game

18 / 36

Line by line · Example 3

Show results in a form field

onclick="roll()"

Pressing the button runs roll().

<form name="f">

Code can reach this form as document.f.

document.f.result.value = …

Write text into the result box.

Number(document.f.count.value)

Read the count box, as a number.

document.f.count.value = n + 1;

Write the new count back.

Week 2 · Canvas & the Dice Game

19 / 36

Try it · 5 minutes

Add a throws counter

  1. Add an input named count to the form.
  2. Add a global variable throws = 0.
  3. In throwdice(), add 1 and write it to document.f.count.value.

YOU SHOULD SEE

The count box goes up by one on every click.

Week 2 · Canvas & the Dice Game

20 / 36

Big idea 4 · Decisions with switch

State: the game remembers where it is

1

firstturn = true

Use the first-throw rules.

2

firstturn = false

Use the follow-up rules; compare with point.

3

Game over

Set firstturn back to true.

Week 2 · Canvas & the Dice Game

21 / 36

Example 4 · Decisions with switch

Choosing an outcome with switch

switch compares one value with a list of cases. Cases without break share the same code.

CODE · rules.html

function judge(sum) {
  switch (sum) {
    case 7: case 11:
      return "Win";
    case 2: case 3: case 12:
      return "Lose";
    default:
      return "Point is " + sum;
  }
}
for (var s = 2; s <= 12; s++) {
  document.write(s + " → " + judge(s) + "<br>");
}

OUTPUT · judge() applied to every possible sum

Week 2 · Canvas & the Dice Game

22 / 36

Line by line · Example 4

Choosing an outcome with switch

switch (sum) {

Compare sum with each case below.

case 7: case 11:

Either value runs the next line.

return "Win";

Hand back the answer and leave the function.

default:

Runs when no case matched.

for (var s = 2; s <= 12; s++)

Try every possible total of two dice.

Week 2 · Canvas & the Dice Game

23 / 36

Try it · 5 minutes

Trace a game on paper

  1. Throws: 8, 5, 8. After each, write firstturn, point and outcome.
  2. Now throws: 4, 7.
  3. Which lines of code handle each throw?

YOU SHOULD SEE

8, 5, 8: point 8, keep going, win. 4, 7: point 4, then lose.

Week 2 · Canvas & the Dice Game

24 / 36

Common mistakes

When it goes wrong, check these first

The canvas stays blank

Fix: The id in the canvas tag and in getElementById must match exactly. Read the first console error.

A die shows 0 or 7

Fix: Use 1 + Math.floor(Math.random()*6). Math.round gives the wrong spread.

The game never resets

Fix: Set firstturn = true after every win or loss.

Two cases run at once

Fix: End each case’s lines with break, unless you want them to share code.

Week 2 · Canvas & the Dice Game

25 / 36

Check your understanding · 1 of 4

What can Math.random() return?

A

0 to 1, including 1

B

0 up to, not including, 1

C

1 to 6

D

Any whole number

Week 2 · Canvas & the Dice Game

26 / 36

Check your understanding · 2 of 4

Where is (0, 0) on the canvas?

A

The centre

B

Bottom-left

C

Top-left

D

Top-right

Week 2 · Canvas & the Dice Game

27 / 36

Check your understanding · 3 of 4

The first throw is 8. What happens?

A

Player wins

B

Player loses

C

8 becomes the point

D

The throw is ignored

Week 2 · Canvas & the Dice Game

28 / 36

Check your understanding · 4 of 4

What does break do in a switch?

A

Ends the game

B

Leaves the switch

C

Restarts the throw

D

Clears the canvas

Week 2 · Canvas & the Dice Game

29 / 36

Check your understanding

Answers

QAnswerWhy
Q1B · 0 up to, not including, 1It never returns exactly 1, so ×6 never reaches 6.
Q2C · Top-leftx grows right and y grows down from the top-left.
Q3C · 8 becomes the point4, 5, 6, 8, 9 and 10 set the point.
Q4B · Leaves the switchWithout it, the next case’s lines run too.

Week 2 · Canvas & the Dice Game

30 / 36

Lab time · 25 minutes

Your workflow for every file

1

Folder

Create a folder named Week2.

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 diceGame_yourname.html.

Week 2 · Canvas & the Dice Game

31 / 36

Lab activity · Week2 folder

Build the game in three stages

FileObjectivesWhat it adds
singleDie.html1, 2, 3, 4Canvas, drawing, colours and one random die
twoDie.html4, 5Two dice, thrown by clicking a button
diceGame.html6, 7Form fields and the full rules of Craps

Building in stages is a habit the book uses in every chapter: get a small version working, then add to it.

Week 2 · Canvas & the Dice Game

32 / 36

Stuck?

A five-step debugging checklist

  1. Open the console (F12) and read the first red error.
  2. Check the spelling and capitals of every name and id.
  3. Check that brackets, braces and quotes come in pairs.
  4. Check file names, and that every file is in the same folder.
  5. Save, then hard-refresh with Ctrl+F5.

THIS WEEK’S TIP

Add console.log(sum); inside throwdice() to see every throw in the console.

Week 2 · Canvas & the Dice Game

33 / 36

BUILD YOUR OWN · ALL OBJECTIVES

Add a reset and a doubles bonus

Week2\diceGame_yourname.html

Week 2 · Canvas & the Dice Game

34 / 36

How the build-your-own task is marked

Marking guide

CriterionWhat we look forMarks
Runs cleanlyOpens with no errors in the console (F12)2
Required featuresA Reset button restarts the game; doubles announce “You win!”; wins, losses and follow-ups all work4
Readable codeIndented, sensible names, a comment on each function2
Your own touchA personal change: colours, images, text or an extra feature2
Total10

Week 2 · Canvas & the Dice Game

35 / 36

RECAP · CHAPTER 2 · DICE GAME SUMMARY

What you can do now

  • Global variables that hold application state.
  • Arithmetic and programmer-defined functions.
  • Math.random and Math.floor.
  • if and switch statements.
  • Creating a canvas and drawing rectangles and circles.

NEXT WEEK

Week 3 · Animation, Inputs & Media

A ball bouncing in a box: timers, collisions, form input, images, gradients and video.

Week 2 · Canvas & the Dice Game

36 / 36

Keyboard
→ Space next   ← previous   Home/End first / last
F full screen   N speaker notes   P print / save as PDF
Click the right or left half of a slide to move forward or back.

Save as PDF: press P, choose “Save as PDF”, and turn on “Background graphics”.