Week 3

Sep 9 – More Interactive Programs

mousePressed()

Click in the circle (or not).

Explain: How does the program know if you clicked inside the circle? How does clicking change the background color — trace the flow of information in the program. What would happen if background() were called in setup()?
sketch

var x = 150;
var y = 100;
var d = 25;
var g = 0;

function setup() {
    createCanvas(300, 200);
}

function draw() {
    background(g);
    ellipse(x, y, d, d);
}

function mousePressed() {
    if (dist(mouseX, mouseY, x, y) < d/2) {
        g += 30;
    }
}

Button LEFT and RIGHT

Click with the left and right mouse buttons (on Macs, right click is usually done by holding down the control key while you click.) Whether or not right-clicks are delivered to JavaScript is browser-dependent, so right click may just cause the browser to pop up a menu.

Explain the difference between mousePressed() (above) and mouseIsPressed (in this example).

sketch

function setup() {
    createCanvas(120, 120);
    strokeWeight(30);
}

function draw() {
    background(204);
    stroke(102);
    line(40, 0, 70, height);
    if (mouseIsPressed) {
        if (mouseButton == LEFT) {
            stroke(255);
        } else {
            stroke(0);
        }
        line(0, 70, width, 50);
    }
}

Mouse Guide

Explain how this program works. There are basically one binary decision to make: What is it? Explain how offset is used.
sketch

var x;
var offset = 10;

function setup() {
    createCanvas(240, 120);
    x = width / 2;
}

function draw() {
    background(204);
    if (mouseX > x) {
        x += 0.5;
        offset = -10;
    }
    if (mouseX < x) {
        x -= 0.5;
        offset = 10;
    }
    line(x, 0, x, height);
    line(mouseX, mouseY, mouseX + offset, mouseY - 10);
    line(mouseX, mouseY, mouseX + offset, mouseY + 10);
    line(mouseX, mouseY, mouseX + offset * 3, mouseY);
}

Here is an illustration of various ways to implement the “Mouse Guide” problem shown above.

Exercise: Make a “lamp” you can turn on and off with mouse clicks like this (click in the canvas to see it work).
sketch

Sep 11

Data and Types

Javascript data is stored in variables and code. There are different types of data including numbers, strings and Booleans.

Some operators and functions do different things depending on the types of their operands.

Numbers

A number in Javascript is an approximation of a real number in math. Real numbers include things like Pi, seven, 11/7, and 1.1. We say approximation because Numbers in Javascript have finite precision: about 12 digits. However, integers (up to about 16 decimal digits) are represented exactly.

Literal numbers are written as decimal integers (1776), with decimal points (98.6), or scientific notation (1.23e-10).

Strings

A string is a sequence of characters, e.g. some text.

Literal strings are just strings enclosed in double or single quotes, e.g. "this is a string" and 'this is also a string'.

Some String Operations

splicing strings: "abc" + "xyz" –> "abcxyz"
converting numbers to strings:
String(10) —> "10"
10.toString() —> "10"
"" + 10 —> "10"

Boolean values

Boolean values are true and false. Boolean values are result from comparison operators (among others), e.g. 4 < 5 has the Boolean value of true. When a Boolean value is required, e.g. in the condition after “if”, any not-zero number is interpreted to mean true.

Operators &&, ||, == and === return Boolean values.

=== compares for “true” equality: same value, same type.

== compares for loosely equal values, but false == 0, and “10” == 10

Mouse Inside?

Explain how this example works. There are 4 comparison tests. Why? What would happen if you used “or” (||) instead of “and” (&&)?

sketch

var x = 80;
var y = 30;
var w = 80;
var h = 60;

function setup() {
    createCanvas(240, 120);
}

function draw() {
    background(204);
    if ((mouseX > x) & (mouseX < x+w) &&
        (mouseY > y) && (mouseY < y+h)) {
        fill(0);
    } else {
        fill(255);
    }
    rect(x, y, w, h);
}

keyIsPressed

Try pressing a key after selecting the canvas below. Explain how the key is detected.
sketch

function setup() {
    createCanvas(240, 120);
}

function draw() {
    background(204);
    line(20, 20, 220, 100);
    if (keyIsPressed) {
        line(220, 20, 20, 100);
  }
}

key Input

Try typing a key after selecting the canvas below. What is the value of the variable key. What is its type? Is it a number? When does it change? What is the value of key immediately after you press a key and then immediately after you release the key?
sketch

function setup() {
  createCanvas(120, 120);
  textSize(64);
  textAlign(CENTER);
}

function draw() {
  background(255);
  text(key, 60, 80);
}

Exercise: Modify the program in keyIsPressed (above) to act differently depending on which key is pressed.

Counting

Exercise: Make a program to count how many times the canvas has been “clicked.” Depending on whether the answer is 0, 1, or 2, set the background to different colors. Hint: start with the program above from Monday, Sep 12 under mousePressed().

Sep 13

  • Lab exam: use your personal computer, no Internet access allowed, see instructions on example exam on Piazza.
  • Autolab has feedback! Click on your grade to see comments (LO1 is an exception)
  • “=” for assignment, “===” for equality test.
  • Looking Outwards posts should have captions for any and all media.
  • Add comments to your code or lose points!
  • Include headers with name and andrew ID etc. in your code or lose points!
  • Pong animation on Deliverables page (might be) rotated. Be sure to check requirements.
  • Although not always stated explicitly, we expect creative effort in all projects. (Starting this week: assume 10% for effort unless stated otherwise. Assignments, not so much: these are “technical exercises” to develop understanding and (hopefully) take you through the paces without taking a lot of time. Nevertheless, we do add one to five “bonus” points for excellent work, technical or otherwise.
  • Programming style – programs should be formatted consistently and perhaps even beautiful. We are taking off points this week for stylistic inconsistencies and irregularities.

Drag and Drop

Try the program below (drag the dot with the mouse). Explain how it works. When does dragging get set and reset? What happens when dragging is true, and what happens when it is false? How does the program know where to draw the dot? Why doesn’t the program just draw the dot with mouseX and mouseY?

sketch

var x = 200;
var y = 200;
var diameter = 5;

// this variable keeps track of whether circle should drag or not
var dragging = false;

function setup() {
    createCanvas(400, 400);
    fill(0);
}

function draw() {
    background(255);
  
    // if in dragging state, update x and y to follow mouse
    if (dragging) {
        x = mouseX;
        y = mouseY;
    }
  
    // draw the ellipse at x,y position
    ellipse(x, y, diameter, diameter);
}

// when mouse is pressed, check if click is inside circle
// if it is, set dragging state to true
function mousePressed() {
    if (dist(x, y, mouseX, mouseY) < diameter/2) {
        dragging = true;
    }
}

// whenever mouse is released, return draging state to false
function mouseReleased() {
    dragging = false;
}

Key is H or N

Type h or H or n or N into the canvas below. Explain how the program works. When does the program “discover” you have typed a letter? Immediately, or when something else happens? Why does the program test keyIsPressed as well as the key value? How does the program “ignore” whether the key is upper or lower case?

sketch

function setup() {
    createCanvas(120, 120);
}

function draw() {
    background(204);
    if (keyIsPressed) {
        if ((key == 'h') || (key == 'H')) {
            line(30, 60, 90, 60);
        }
        if ((key == 'n') || (key == 'N')) {
            line(30, 20, 90, 100);
        }
    }
    line(30, 20, 30, 100);
    line(90, 20, 90, 100);
}

Mouse Lines

Try moving the mouse around in the canvas below. Explain how the gray line depends on the mouse. Explain how the black line depends on the mouse. How far left and right can the black line go?

sketch

function setup() {
    createCanvas(240, 120);
    strokeWeight(12);
}

function draw() {
    background(204);
    stroke(102);
    line(mouseX, 0, mouseX, height);  // Gray line
    stroke(0);
    var mx = mouseX/2 + 60;
    line(mx, 0, mx, height);  // Black line
}

More Mouse Lines

Try moving the mouse around in the canvas below. Explain how the white line depends on the mouse. Read about the map() function. Explain how the black line depends on the mouse. What is the range of x (horizontal) values of the endpoint that moves?

sketch

function setup() {
    createCanvas(240, 120);
    strokeWeight(12);
}

function draw() {
    background(204);
    stroke(255);
    line(120, 60, mouseX, mouseY); // White line
    stroke(0);
    var mx = map(mouseX, 0, width, 60, 180);
    line(120, 60, mx, mouseY); // Black line
}

Exercise: Explain how the “easing” program below works. Modify the “easing” program below so that the speed of following the mouse is controlled by a variable. Try values of 0.2 (faster) and 0.01 (slower). For speedy workers: Add another ellipse that also follows the mouse, but which has a different rate of convergence.

sketch

var x = 300;
var y = 300;
var diffx = 0;
var diffy = 0;
var targetX = 300;
var targetY = 300;
  
function setup() {
    createCanvas(600, 400);
}

function draw() {
    background(0);
    diffx = mouseX - x;
    diffy = mouseY - y;
    x = x + 0.1*diffx;
    y = y + 0.1*diffy;
    ellipse(x, y, 50, 50);
}