7 – Playing sequences

Let’s add the code that creates the sequences of sounds.

Class work

Topics for today

Scheduling events

The following examples are from w3schools.com:

Workfiles

Download in class: simon-says.zip

Individual files:

We are starting where we left off last week, on version 1 of Simon Says, i.e., we will use simon_1.html and lib1.js and add functions to it to get to version 2.

v2 – Creating and storing a random sequence of pitches

  1. simon_2.html: the only change is to point to the new js script
     

    <!DOCTYPE html>
    <html lang="en-US">
        <head>
            <meta charset="UTF-8">
            <!-- <link rel="stylesheet" type="text/css" href="style.css" /> -->
            <title>Simon Says</title>
        </head>
        
        <body>
            <div id = "container">
                <div id = "header">
                    <h1 id = "title">Play sequence</h1>
                </div>
    
                <div id = "game">
                    <img id="lb_0" onclick="lb_click(0)" src="images/lb_off.png" width="100" height="188">
                    <img id="lb_1" onclick="lb_click(1)" src="images/lb_off.png" width="100" height="188">
                    <img id="lb_2" onclick="lb_click(2)" src="images/lb_off.png" width="100" height="188">
                    <img id="lb_3" onclick="lb_click(3)" src="images/lb_off.png" width="100" height="188">
                    <img id="lb_4" onclick="lb_click(4)" src="images/lb_off.png" width="100" height="188">
                </div>
    
                <div id = "footer">
                    <button id="btn_0" type="button" onclick="play_game()">Play!</button>
                </div>
            </div>
            <script type="text/javascript" src="lib2.js"></script>
        </body>
    </html> 
    

     

  2. lib2.js: generating and storing the sequence
     

    var SS = {};  // Global object container
    
    function init_images() {
        SS.img_off = "images/lb_off.png";
    
        SS.img_on = [ "images/lb_yellow.png",
                      "images/lb_blue.png",
                      "images/lb_green.png",
                      "images/lb_red.png",
                      "images/lb_purple.png"];
    
        SS.n = SS.img_on.length;
    
        SS.img_delay = 800;  
    }
    
    function turn_lb_on(i, image) {
        image.src = SS.img_on[i];
    }
    
    function turn_lb_off(image) {
        image.src = SS.img_off;
    }
    
    function lb_click(i) {
        var img_id = "lb_" + String(i);
        var image = document.getElementById(img_id);
    
        turn_lb_on(i, image);
        setTimeout( function(){turn_lb_off(image)}, SS.img_delay);
    }
    
    function play_game() {
        alert("play game");
    }
    
    window.onload = function() {
        init_images();
    }
    
    function P(i){
        console.log(i);
    }
    

     

  3. Our page so far: simon_2.html