Magic

1. DISPLAY OBJECTS

SHOW ▼︎
image showing from left to right, a pink circle, purple button and a purple bowler hat all on a blue background

Display objects are things you can see when they are on the stage (the screen). Examples are shapes, components (labels, buttons, etc.) and images.

An object is made from a class - which has the instructions or ingredients for the object. Use the new keyword to make the object from its class.

01
new Circle(80, pink); // 80 is the size and pink is the color

We can make the object do something with a method, which is like a verb. Here, we center the object on the stage and move it to the left 200 pixels. We use a dot to separate the object and the methods. At the end of the line is a semi-colon (;) that ends the statement.

02
new Circle(80, pink).center().mov(-200);

Statements usually run in order to make the magic happen! Here are parts that a statement can have:

a picture showing the parts of a code statement.  The statement is var answer = 31 + 15 semicolon.  Var is the keyword, answer is the identifier, = is the operator, 31 + 15 is the expression, semicolon is the terminator (cool) and the whole thing is the statement.

Sometimes we have to use an object later so we store it in a variable. Then we can change a property of the object. Properties are like adjectives.

03
var button = new Button().center();
button.enabled = false;  // turn off the button

// Class names start with a capital letter
// Variable names should start with lower case
// They can't have spaces so we can use camelCase ;-)
var myHat = new Pic("hat01").center().mov(200);

// In JavaScript 6 we now use const and let
// Imagine that pink Circle with the Hat is Dr Abstract
// const is for things that will not change
const name = "Dr Abstract";
// let is for things that will (unfortunately) change!
let age = 50; 

// Here is a Label DisplayObject that can show text!
// There is no need to store this label in a variable
// because we do not need it later in our code.
// The parameters are the text, the size, the font, the color...
new Label("Dr Abstract", 100, "gf_Anton", purple).center();

// Or we could have used the variables from above.
// We join the name and the age with + sign 
// and center the label 100 pixels up from the bottom.
new Label(name + " is " + age).pos(0,100,CENTER,BOTTOM);

// Here are some very magical Display Objects.
// A Blob and a Squiggle.  You can change their shape.
// We store them in a const even though they change
// because they still are the same Blob and Squiggle.
const blob = new Blob().loc(200,200); // locate x and y
const squiggle = new Squiggle().loc(500, 200);
			

See Hat on Head and press CODE button.

You can make your own Blob and Squiggle paths and get CODE for their points at   PATHS

make fun shapes with Blob and Squiggle paths!

The characters, words and order they are written is called syntax. Code will not work if syntax is broken. We call this a bug (but not the cute yellow bug in our tutorial). Bugs are quite common so you will have to summon patience! Think of coding as the world's greatest puzzle and feel rewarded when it works!

ZIM Skool - JavaScript Coding Lessons for Kids, teens and all!  This link takes you to another site called ZIM Skool with more in-depth lessons for coding. See MORE at ZIM Skool!

2. PARAMETERS AND ANIMATION

SHOW ▼︎
a picture showing parameters of a rectangle.  These are placed in round brackets and are width, height, color, etc. to tell more information about the rectangle.  The parameters can be found in the Spells section where a hundred spells are many having dozens of parameters.

Parameters can be used by an object or a method to receive extra information. We send arguments to the parameters inside round brackets () and they must be in the order shown in the Spell list.

04
const myBuilding = new Container(500,300).center();
    
// Containers are invisible and are used to hold other objects. 
// Here we tell the container to be 500 in width and 300 in height.

new Rectangle(100, 50, blue, green, 10, 20)
    .center(myBuilding); // a new line is fine for dots

// 100 and 50 are arguments for the width and height parameters
// blue and green are the color and borderColor
// 10 and 20 are the borderWidth and corner 
// we tell the center() method to center the rectangle in myBuilding
    

If you want to use the default values you can write null or undefined in JavaScript 6. You must keep the order and you can't just leave parameters blank.

05
new Rectangle(100, 50, blue, null, null, 20)
    .center(myBuilding);

// do not provide a borderColor and borderWidth instead put null
    

It can be annoying to count the number of nulls. So we have a second way to make parameters. We can use a configuration object { } as a single parameter:

06
new Rectangle({
    width:100, height:50, color:blue, corner:20
}).center(myBuilding);

// {parameter:value, parameter:value, etc.}
// ** the order does not matter
// ** can be on one line or lots of lines
    

ANIMATION

This picture shows six different features of ZIM animate.  Absolute, relative, series, from, wait and sequence.  These make an object animate in different ways.

We often use a configuration object when we animate things to make them move, spin, fade out, or scale bigger, loop and rewind!

07
new Rectangle(100,100,green)
    .centerReg() // will now animate around middle
    .animate({
        props:{scale:2}, // can animate more than one property
        time:1,          // one second ***
        rewind:true,     // get bigger then smaller
        loop:true        // keep doing animation
    });
    

See the ANIMATE page for all sorts of animation options!

ZIM Skool - JavaScript Coding Lessons for Kids, teens and all!  This link takes you to another site called ZIM Skool with more in-depth lessons for coding. See MORE at ZIM Skool!

3. FUNCTIONS AND EVENTS

SHOW ▼︎
a picture showing a list of example functions such as shuffle, rand, loop and a dozen more.

A function is a block of code that you can run whenever you want and as many times as you want. An example would be to explode an asteroid. You can make (define) your own function:

08
function greet(message, location) {
    new Label("hi").pos(rand(200,800), 500);
    // put as many statements as you want here!
    // the { } are called a "block of code"
    // they are like a box that holds the code to run
    // we indent to easily see what is in the function
}
    
// a function must be called to run
greet(); // call (run) the function - a label gets added
greet(); // call the function again - another label gets added

// rand() is a function to get a random number
// pos() is a special function - a method - stored on the object
// note that pos() is dotted to the object and rand() is not
    

Arguments can be passed to the function parameters.

09
function greet(message, location) {
    new Label(message).pos(location, 500);
}
greet("hello", 200); // Label says hello at x=200
greet("goodbye", 600); // second Label says goodbye at x=600
    

EVENTS

An event is when something happens. This is the magic of interactivity!

Example Events

  • click
  • pressdown / mousedown
  • pressmove
  • pressup
  • change
  • complete
We use the on() method which has TWO parameters we will use:
   1. the type of event
   2. a function to call when the event happens

10
var button = new Button().center();
button.on("click", go);
function go() {
    zgo("https://zimjs.com"); // short ZIM function to go to URL
}

We often use an arrow function as the second argument of the on() method:

11
// ARROW FUNCTION
const button = new Button().center();
button.on("click", ()=>{ // an arrow function
    zgo("https://zimjs.com");
}); // note the closing round bracket

ZIM Skool - JavaScript Coding Lessons for Kids, teens and all!  This link takes you to another site called ZIM Skool with more in-depth lessons for coding. See MORE at ZIM Skool!

4. ARRAYS AND LOOPS

SHOW ▼︎
The picture shows the same code as in the content below for arrays and loops.

An Array holds a list of things in [ ] that we can access by index number that starts at 0.

12
// We use const because colors holds only this array object 
// even though the order changes later with shuffle
const colors = [pink, orange, red, green, blue];

// we use let so that myColor can hold a different color object 
// later when we assign a new color with pluck() 
let myColor = colors[0]; // gets the first color, pink

new Circle(90, myColor).center(); // a pink circle
new Circle(50, colors[2]).center(); // with a red circle on top

// we can use the length property of an array too
new Circle(20, colors[colors.length-1]).center(); // blue on top

// we can change colors, add colors, sort, shuffle and more!
colors[1] = brown; // the second color is now brown
colors.push(grey); // grey has been added to the end
colors.sort(); // alphabetical order using sort() method
shuffle(colors); // ZIM function to randomize array
myColor = pluck(colors); // ZIM function to pick randomly
    

LOOPS

A loop repeats a block of code between { } as many times as you want:

13
loop(10, ()=>{ 
    new Triangle().center().drag(); // 10 draggable black triangles!
});

loop(10, i=>{ // a single argument does not need () for the arrow function
    // i increases each loop - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
    new Triangle().loc(100+i*100, 500);
    // 10 triangles spaced by 100 pixels across the stage
});

We can also loop through an array!

14
const colors = [red, orange, yellow, green, blue, pink];
loop(colors, (color, i)=>{ // two arguments need () for the arrow function
    // color will be red, then orange, then yellow, etc.
    new Rectangle(50, 50, color).pos(20+i*60, 20);
});
this shows the colors red, orange, yellow, green, blue and pink that matches the array.  Red looks rough, orange is smoother and yellow is very smooth.  Green looks fresh and blue looks wet or airy and pink looks soft or tastes like strawberries.

And loop through a Container:

15
// the rectangles are now on the stage which is a container
loop(S, object=>{
    object.sca(.5); // makes each rectangle half as big
});

These examples are with the ZIM Loop. There are also for loops and while loops. These are common to all programming languages do similar things but with different syntax. See the MORE link for examples.

ZIM Skool - JavaScript Coding Lessons for Kids, teens and all!  This link takes you to another site called ZIM Skool with more in-depth lessons for coding. See MORE at ZIM Skool!

5. CONDITIONALS AND DEBUGGING

SHOW ▼︎
a picture of the ornamator which was made with conditionals and took lots of debugging!

Programming uses logic to determine what happens. Another word for this is a conditional or an if statement.

16
if (circle.color == blue) {
    circle.alp(.5);
}

// this compares the colors and if equal (==) then
// sets the alpha (transparency) of the circle to half
    

You can do something else if the condition is false:

17
if (circle.color == blue) {
    circle.alp(.5);
} else {
    circle.alp(0); // hide the circle
}

You can also do multiple conditions:

18
if (circle.color == blue) {
    circle.color = black; // change color to black
} else if (circle.color = red) {
    circle.color = white; // change color to white
} // could add another else if () {} or an else {}
    

DEBUGGING

When the code breaks you will probably see an error message. Here are some common bugs:

Syntax Errors

  1. Forgot to end a quote " ' ` or a bracket ( { [
  2. Too many brackets (selecting a bracket highlights its match)
  3. Using a keyword that does not exist
  4. Typos - spelled a keyword incorrectly
  5. Using an undefined variable in an expression
  6. Using a bad character (-+*&, etc.) in a variable name
  7. missing comma (,) or colon (:) in array or object literal

If nothing shows up - here are some things to check for:

Nothing Shows

  1. The Internet is down
  2. You forgot to add object to the stage - use addTo(), center(), centerReg()
  3. You forgot to put stage.update() at the end of an event function
  4. When adding to a container, remember to add the container to the stage
  5. You are viewing the wrong file

ZIM Skool - JavaScript Coding Lessons for Kids, teens and all!  This link takes you to another site called ZIM Skool with more in-depth lessons for coding. See MORE at ZIM Skool!

6. CONTROLS

SHOW ▼︎
a dozen small pictures of ZIM controls with Pragma, Dr Abstract's daughter sitting crosslegged on a bright pink box next to them.  She is happy because the controls lets you do things easily!  The first control is accessibility for screen readers.  The second lets you swipe things with your finger.  Then there are pages, controls to change the size and rotation, parallax for 3D effects, controls for animations, motion controllers, emitters of particles, animating to sound, a portal from one place to another, and virtual reality controls!

Controls help you do things with one or more objects. We will look at a few but there are many more.

19
const circle = new Circle(50, red).center();
new MotionController(circle);

// the circle will move to where you press on stage
// add ,"mousemove" to make the circle follow your mouse
// or use "keydown", "gamebutton", "gamestick", or "swipe"
    

You can use a Ticker to constantly check for something:

20
const rectangle = new Rectangle().pos(100, 100);
Ticker.add(()=>{
    // assuming we are controlling the circle from above
    if (circle.hitTestCircleRect(rectangle)) {
        rectangle.removeFrom();
    }
});

Use an interval to keep on adding new rectangles. An interval is like a Ticker but you give it a time interval. There is also timeout which runs once after a certain time.

21
const rectangles = new Container().addTo();

// Every second add a new Rectangle randomly to the container
// Note - this is a ZIM interval with seconds first then the function.
// The JavaScript version is like this: setInterval(function, milliseconds).
interval(1, ()=>{
    // W and H are the width and height of the stage (S)
    new Rectangle().addTo(rectangles).pos(rand(W-100), rand(H-100));
});

// in a Ticker, loop through all the rectangles
Ticker.add(()=>{
    loop(rectangles, function(rectangle) {
        if (circle.hitTestRect(rectangle)) {
            rectangle.removeFrom();
        }
    }, true); // loop backwards when removing
});

A fun control is called an Emitter. It makes particles!

22
// EMITTER 1 
const particles = new Emitter().center();
// Lets make the emitter go to where we mousedown.
new MotionController(emitter, "mousedown");

// EMITTER 2
// Start the Emitter paused if you want to make only a few particles 
const reward = new Emitter({startPaused:true});
// then make the emitter give a reward when pressing on the stage.
// We get where we pressed by asking the Frame (F) 
// for mouseX and mouseY and then we use the spurt(number) method
reward.loc(F.mouseX, F.mouseY).spurt(10);
    

The ZIM Pen is also a wonderful control to play with!

23
// parameters are (size, color, penType) and more
const pen = new Pen().center();
new MotionController(pen, "pressmove");

// try these instead!  (Do one at a time)

const pen = new Pen({penType:"kitetail"}).center();
new MotionController(pen, "pressmove");
// or "barbwire", "grass", "hair", "city", or "splatter"

const pen = new Pen(20, series(red, purple)).center();
new MotionController(pen, "pressmove");

const pen = new Pen([20,80,160], dark).center();
new MotionController(pen, "pressmove");

const pen = new Pen(series(30,100), series(orange,blue)).center();
new MotionController(pen, "pressmove");
    
Another picture of ZIM controls - now we see that Pragma was sitting on the dot of the letter i in ZIM.  She is surrounded by an arch of words above that say the ZIM controls.  Dr Abstract presents the controls which are Accelerator, swiper, motionController, grid, guide, parallax, scroller, dynamo, accessibility, pages, hotspots and layouts.  More controls have been added since then too!  This is all part of the ZIM Foundation for Creative Coding and powered by CreateJS.  We hope to make coding magical for everyone!


CONCLUSION

Apprentice, you have seen the secrets of many apps and games!

Please continue to explore and have a great time coding.

challenge your friends to make amazing creations.

Start a coding club and let your teachers know about ZIM.

All the best, we love creative coders!


Pragma and Dr. Abstract

ZIM Skool - JavaScript Coding Lessons for Kids, teens and all!  This link takes you to another site called ZIM Skool with more in-depth lessons for coding. See MORE at ZIM Skool!