Week 2 — Canvas & the Dice Game

This week you start drawing. We use the HTML5 <canvas> element to paint dice, generate random rolls, and implement the classic casino game Craps with real game state.

🎯 Objectives

  • Create a canvas and get its 2D drawing context with getContext('2d').
  • Draw rectangles and circles using strokeRect, fillRect and arc.
  • Set colours with fillStyle, strokeStyle and lineWidth.
  • Produce random integers with Math.random() and Math.floor().
  • Respond to a button click with an onclick handler.
  • Read and write form fields with document.f.name.value.
  • Model game state with variables (the Craps point and first turn).

🛠 Weekly tasks

  1. Objective 1 — create a <canvas> and get its 2D context with getContext('2d'): Activity 1 + build singleDie.html.
  2. Objective 2 — draw rectangles and circles with fillRect, strokeRect and arc: Activity 2 + build singleDie.html.
  3. Objective 3 — set colours with fillStyle, strokeStyle and lineWidth: Activity 3 + build singleDie.html.
  4. Objective 4 — produce random integers with Math.random() and Math.floor(): Activity 4 + build singleDie.html and twoDie.html.
  5. Objective 5 — respond to a button click with an onclick handler: Activity 5 + build twoDie.html.
  6. Objective 6 — read and write form fields with document.f.name.value: Activity 6 + build diceGame.html.
  7. Objective 7 — model game state (the Craps point and first turn): Activity 7 + build diceGame.html.
  8. Build your own diceGame_yourname.html — using everything you have learned; add a Reset button and announce “You win!” when the player rolls doubles. (All objectives)

🎓 Lecture activity Open lecture slides →

A 90-minute session of 36 slides. Each concept is taught four ways: the big idea, a short example with its live output, a line-by-line explanation, and a 5-minute “try it” task. The lab work at 1:00 uses the Lab activity below.

Session plan

  1. 0:0010 minWarm-upReview questions on last week
  2. 0:1010 minGame & objectivesThis week’s game, objectives and key words
  3. 0:2035 minConceptsBig idea → code with live output → line by line → try it
  4. 0:555 minCheck understandingCommon mistakes and a 4-question quiz
  5. 1:0025 minLabBuild the files in the Lab activity below
  6. 1:255 minWrap-upBuild-your-own task, marking guide and recap

Concepts this week

  • 1. Random numbers — Rolling dice with Math.random
  • 2. Drawing on a canvas — Shapes on a coordinate grid
  • 3. Buttons & form fields — Show results in a form field
  • 4. Decisions with switch — Choosing an outcome with switch

The slides open as a page on this site. Press F for full screen, the arrow keys to move, N for speaker notes, and P to save as PDF (turn on “Background graphics”).

🧪 Lab activity: work through the files Printable lab sheet

Create a folder named Week2 on your PC. Build the three files below in order. Each file adds the objectives shown in its heading, so every objective is covered by the end. Save each file and refresh the browser, and tick a checkpoint once you have proved it works.

Want a head start? A scaffold file starter.html is provided — choose it in the preview dropdown, copy it into your Week2 folder, and complete its TODOs.

  1. Create your Week2 folder

    On your own PC — do this once before starting.

    1. Create a folder named Week2 on your PC.
    2. Open your Week2 folder in VS Code or Sublime Text.
    3. Create each file below in your editor as you reach it.
  2. singleDie.html Objectives 1, 2, 3, 4

    Week2\singleDie.html — canvas, drawing, colours and random.

    1. [Obj 1] Create singleDie.html and add this scaffold code.
      <!DOCTYPE html>
      <html lang="en">
      <head><title>Throwing 1 die</title></head>
      <body>
        <canvas id="canvas" width="400" height="300">No canvas support.</canvas>
      
        <script>
          var ctx = document.getElementById("canvas").getContext("2d");
          // TODO: draw the die face and dots
        </script>
      </body>
      </html>
    2. [Obj 2, 3] Add the die face with fillRect and outline it with strokeRect.
      ctx.fillStyle = "#f9f9f9";
      ctx.fillRect(50, 50, 100, 100);
      ctx.lineWidth = 5;
      ctx.strokeStyle = "#333";
      ctx.strokeRect(50, 50, 100, 100);
    3. [Obj 2, 3] Add a dot() helper that draws one dot with arc().
      function dot(x, y) {
        ctx.beginPath();
        ctx.fillStyle = "#009966";
        ctx.arc(x, y, 6, 0, Math.PI * 2, true);
        ctx.fill();
      }
    4. [Obj 4] Add the random roll and draw the dots for that number.
      var ch = 1 + Math.floor(Math.random() * 6);
      var cx = 100, cy = 100, d = 25;
      if (ch === 1 || ch === 3 || ch === 5) { dot(cx, cy); }
      if (ch >= 2) { dot(cx - d, cy - d); dot(cx + d, cy + d); }
      if (ch >= 4) { dot(cx + d, cy - d); dot(cx - d, cy + d); }
      if (ch === 6) { dot(cx - d, cy); dot(cx + d, cy); }
    5. Save and refresh.
  3. twoDie.html Objectives 2, 3, 4, 5

    Week2\twoDie.html — drawing and a button click.

    1. [Obj 5] Create twoDie.html and add this scaffold code.
      <!DOCTYPE html>
      <html lang="en">
      <head><title>Throwing dice</title></head>
      <body>
        <canvas id="canvas" width="400" height="300"></canvas>
        <br />
        <button onclick="throwdice()">Throw dice</button>
      
        <script>
          var ctx = document.getElementById("canvas").getContext("2d");
      
          function throwdice() {
            // TODO: roll two dice and draw them
          }
      
          function drawface(n, dx) {
            // TODO: draw the die outline and dots
          }
        </script>
      </body>
      </html>
    2. [Obj 4] Add the random rolls in throwdice().
      var ch1 = 1 + Math.floor(Math.random() * 6);
      var ch2 = 1 + Math.floor(Math.random() * 6);
      drawface(ch1, 50);
      drawface(ch2, 200);
    3. [Obj 2, 3] Add the die outline in drawface(n, dx).
      ctx.fillStyle = "#f9f9f9";
      ctx.fillRect(dx, 50, 100, 100);
      ctx.strokeStyle = "#333";
      ctx.strokeRect(dx, 50, 100, 100);
    4. [Obj 2, 3] Add the dots in drawface(n, dx).
      var cx = dx + 50, cy = 100, d = 25;
      function dot(x, y) {
        ctx.beginPath();
        ctx.fillStyle = "#009966";
        ctx.arc(x, y, 6, 0, Math.PI * 2, true);
        ctx.fill();
      }
      if (n === 1 || n === 3 || n === 5) { dot(cx, cy); }
      if (n >= 2) { dot(cx - d, cy - d); dot(cx + d, cy + d); }
      if (n >= 4) { dot(cx + d, cy - d); dot(cx - d, cy + d); }
      if (n === 6) { dot(cx - d, cy); dot(cx + d, cy); }
    5. [Obj 5] Save, refresh, and click Throw dice.
  4. diceGame.html Objectives 5, 6, 7

    Week2\diceGame.html — the Craps game with form fields and game state.

    1. [Obj 5, 6] Create diceGame.html and add this scaffold code.
      <!DOCTYPE html>
      <html lang="en">
      <head><title>Craps game</title></head>
      <body>
        <canvas id="canvas" width="400" height="300"></canvas>
        <br />
        <button onclick="throwdice()">Throw dice</button>
        <form name="f">
          Stage: <input name="stage" value="First Throw" />
          Point: <input name="pv" value="  " />
          Outcome: <input name="outcome" value="   " />
        </form>
      
        <script>
          var ctx = document.getElementById("canvas").getContext("2d");
          // TODO: add the game state variables
          // TODO: draw the dice and apply the Craps rules
        </script>
      </body>
      </html>
    2. [Obj 7] Add the game state variables (the Craps point and first turn).
      var firstturn = true;
      var point;
    3. [Obj 2, 3] Add drawface(n, dx) to draw one die.
      function drawface(n, dx) {
        ctx.fillStyle = "#f9f9f9";
        ctx.fillRect(dx, 50, 100, 100);
        ctx.strokeStyle = "#333";
        ctx.strokeRect(dx, 50, 100, 100);
        var cx = dx + 50, cy = 100, d = 25;
        function dot(x, y) {
          ctx.beginPath();
          ctx.fillStyle = "#009966";
          ctx.arc(x, y, 6, 0, Math.PI * 2, true);
          ctx.fill();
        }
        if (n === 1 || n === 3 || n === 5) { dot(cx, cy); }
        if (n >= 2) { dot(cx - d, cy - d); dot(cx + d, cy + d); }
        if (n >= 4) { dot(cx + d, cy - d); dot(cx - d, cy + d); }
        if (n === 6) { dot(cx - d, cy); dot(cx + d, cy); }
      }
    4. [Obj 4, 6, 7] Add throwdice() to roll, draw and apply the Craps rules.
      function throwdice() {
        var ch1 = 1 + Math.floor(Math.random() * 6);
        var ch2 = 1 + Math.floor(Math.random() * 6);
        drawface(ch1, 50);
        drawface(ch2, 200);
        var sum = ch1 + ch2;
        if (firstturn) {
          if (sum === 7 || sum === 11) { document.f.outcome.value = "You win!"; }
          else if (sum === 2 || sum === 3 || sum === 12) { document.f.outcome.value = "You lose!"; }
          else { point = sum; document.f.pv.value = point; firstturn = false; }
        } else {
          if (sum === point) { document.f.outcome.value = "You win!"; firstturn = true; }
          else if (sum === 7) { document.f.outcome.value = "You lose!"; firstturn = true; }
        }
      }
    5. Save, refresh, and play a few rounds.
Finished example output

The dice are drawn by drawing the outline of a square and then filling in the correct number of dots. Every dot position is calculated from dicex, dicey and dotrad.

📚 Craps rules used in the game