Magic
1. DISPLAY OBJECTS
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.
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.
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:
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.
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
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!
See MORE at ZIM Skool!
2. PARAMETERS AND ANIMATION
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.
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.
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:
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
We often use a configuration object when we animate things to make them move, spin, fade out, or scale bigger, loop and rewind!
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!
See MORE at ZIM Skool!
3. FUNCTIONS AND EVENTS
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:
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.
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
1. the type of event
2. a function to call when the event happens
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:
// ARROW FUNCTION const button = new Button().center(); button.on("click", ()=>{ // an arrow function zgo("https://zimjs.com"); }); // note the closing round bracket
See MORE at ZIM Skool!
4. ARRAYS AND LOOPS
An Array holds a list of things in [ ] that we can access by index number that starts at 0.
// 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:
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!
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); });
And loop through a Container:
// 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.
See MORE at ZIM Skool!
5. CONDITIONALS AND DEBUGGING
Programming uses logic to determine what happens. Another word for this is a conditional or an if statement.
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:
if (circle.color == blue) { circle.alp(.5); } else { circle.alp(0); // hide the circle }
You can also do multiple conditions:
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
- Forgot to end a quote " ' ` or a bracket ( { [
- Too many brackets (selecting a bracket highlights its match)
- Using a keyword that does not exist
- Typos - spelled a keyword incorrectly
- Using an undefined variable in an expression
- Using a bad character (-+*&, etc.) in a variable name
- missing comma (,) or colon (:) in array or object literal
If nothing shows up - here are some things to check for:
Nothing Shows
- The Internet is down
- You forgot to add object to the stage - use addTo(), center(), centerReg()
- You forgot to put stage.update() at the end of an event function
- When adding to a container, remember to add the container to the stage
- You are viewing the wrong file
See MORE at ZIM Skool!
6. CONTROLS
Controls help you do things with one or more objects. We will look at a few but there are many more.
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:
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.
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!
// 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!
// 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");
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
See MORE at ZIM Skool!