Revisiting-Concepts-Notatio.../2.Ghost-Writing.md
gauthiier 6f0ddc2595 loop
2023-01-15 12:22:25 +01:00

2.6 KiB

Ghost Writing: Text, Arrays, Randomness

autopilot creativity

Sketch: 2.0 Array + Index

// Array + Index!

var NAMES = ["David", "Karin", "Sigrid", "Nanna", "Laura", "Maaike"];
var INDEX = 0;
    
function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
}

function keyTyped() {
  if(key == 'x') {
    print("Hi " + NAMES[0] + "!");
  }
}

// Reference: https://p5js.org/reference/

🤔 What are indices?

 ["David", "Karin", "Sigrid", "Nanna", "Laura", "Maaikke"]  <--- Array (var NAMES)
     |        |         |        |         |        |
     0        1         2        3         4        5		<--- indices (var INDEX)

📚 Exercice

  1. Modify sketch 2.0 so that:
  • When key 'k' is pressed then "Hi Karin!" is printed on the console
  • When key 's' is pressed then "Hi Sigrid!" is printed on the console
  • When key 'n' is pressed then "Hi Nanna!" is printed on the console
  • When key 'm' is pressed then "Hi Maaike!" is printed on the console
  1. Modify sketch 2.0 so that:
  • Every time key 'x' is pressed then print the name of the following person in the array ("Hi David!", "Hi Karin!", "Hi Sigrid!", and so forth)

🤔 Who/what is "undefined"?

Sketch: 2.1 Array + Index + Loop

// Array + Index + Loop!

var NAMES = ["David", "Karin", "Sigrid", "Nanna", "Laura", "Maaike"];
var ACTIVITIES = ["piano", "tennis", "chess", "records"];
var INDEX = 0;
    
function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);
}

function keyTyped() {
  if(key == 'x') {
    for(let i = 0; i < 4; i++) {
      print(NAMES[INDEX] + " likes to play " + ACTIVITIES[i]);  
    }
  }
}

// Reference: https://p5js.org/reference/

🤔 How do for-loops work?

for(let i = 0; i < X; i++) {
  // do_somethings();
}

where

let i = 0 
// is the declaration and initialisation of the control variable (i)

i < X 
//is the continuation condition: if the condition is true, then executed the statement in the loop [do_something();], exit the loop when the consition is false

i++
//is the incremental (update) statement that is executed at the end of the loop (i.e. after the loop statement [do_something();] as been executed)