enchant.js Developers Blog

The Latest News on the HTML5 + JavaScript Game Engine enchant.js

Archive for the ‘Tutorial’ Category

Greetings! shi3z here.

This is my three-day cram course, so get ready for a flurry of postings.

Did you give our last session’s final program a go? The spaceship should follow the movements of your mouse cursor.

Of course, the secret to this movement lies in the program.

ship.tick = function(){ // Spaceship will follow your cursor
this.x += (mouseX-this.x)/10;
this.y += (mouseY-this.y)/10;
};

Let’s explain these one at a time.

(continued below)

First of all, the symbol “+=” that follows “this.x” means that the level of the expression to the right will be added to “this.x.” If “this.x+=1,” then this is the same meaning as “this.x=this.x+1.” This notation appears extremely frequently in games, so make a mental note.

Now then, what about this weird variable “mouseX?” As you may have guessed, this is a variable I made for this special game study system.

With this variable, the mouse cursor’s X coordinates are already stored in the computer’s memory. Which means that, yes, “mouseY” indicates the mouse cursor’s Y coordinates.

In this expression, a level of mouseX minus this.x is divided into 10 and into this.x itself.

What on earth are we talking about?

First of all, the program wants to move the spaceship near to the mouse cursor. There are several other methods for this that are easier to understand.

For instance, a program like this:

ship.tick = function(){ // Spaceship will follow your cursor
if(this.x > mouseX) this.x-=10;
if(this.x < mouseX) this.x +=10; if(this.y > mouseY) this.y-=10;
if(this.y < mouseY) this.y +=10;
};

How did the movements change? In the previous code, the ship slipped straight after the cursor.

In this code, after proceeding at a bit of angle, it should follow chase after the cursor horizontally or vertically.

What gives rise to this change in movement? It’s all in the source code.

This latter code, with lots of “if”s, should be easier to understand.

If the spaceship’s position (this.x and this.y) differs from the position of the mouse, the command tells it to move 10 dots at a time.

However, when for instance the cursor is at an angle other than 45 degrees, the amount of increase for x and y becomes 10 each, and the angle of movement eventually changes to 45 degrees.

This movement is extremely awkward and strange.

By comparison, the first example is simple and effective.

What sort of movement does this formula create?

When you subtract the spaceship’s current coordinates from those of the cursor, this becomes the hector stretching between the spaceship and the cursor.

If we add this, the spaceship will suddenly warp to the position of the mouse cursor.

You can try this out with a simpler program.

 ship.tick = function(){ // Spaceship will follow your cursor
this.x += mouseX-this.x;
this.y += mouseY-this.y;
};

Getting rid of the division by 10, the spaceship should suddenly move as though clinging to the cursor.

By dividing by ten, the closer the spaceship drew to the cursor the more precise its movements became, creating that unique sliding effect.

Why does this smooth movement agree with us?

For one thing, it has an air of reality about it.

It resembles the actual movement of real-life objects rather well.

Cars physically cannot stop abruptly. They must first drop their speed bit by bit.

If you run at full speed and then suddenly stop, you will stumble forward a few steps.

This movement contains that same sort of sensation.

Now then, it’s a bit dull with just a spaceship, isn’t it? Let’s try some other objects as well.

A rock seems appropriate. A “for” loop should be easy to use here.

function onLoad() { var ship= new Image('img/starship.png');
ship.tick = function(){ // Spaceship will follow your cursor
this.x += (mouseX-this.x)/10;
this.y += (mouseY-this.y)/10;
};

for(i=0;i<10;i++){
rock = new Image('img/rock.png');
rock.x = Math.random()*320;
rock.y = Math.random()*480;
}
gameStart();
}

When you execute, the results should be something like this:

A rock is puttering around a white expanse of space. It’s an asteroid.

However, nothing happens if this spaceship bumps into the asteroid. That’s rather boring, so let’s make it so that the game ends when the ship hits the asteroid.

function onLoad() {

function onLoad() {
var ship= new Image('img/starship.png');
ship.tick = function(){ // Spaceship will follow your cursor
this.x += (mouseX-this.x)/10;
this.y += (mouseY-this.y)/10;
};

ship.onHit = function(){ // Crashed!
alert("CRASHED!");
}

for(i=0;i<10;i++){
rock = new Image('img/rock.png');
rock.x = Math.random()*320;
rock.y = Math.random()*480;
}
gameStart();
}

However, this is a bit of a persistent program, and when you crash, the “CRASHED” warning will stay open.

In order to stop it, you need to move the cursor to the correct position and reload.

“alert” is one of the commands (functions) that JavaScript possesses, and has the function of displaying warning windows. The “ship.onHit” function is another special function called up by the system, summoned when the object hits another Image.

Here, when the “ship” hits another object, the game opens the warning window.

With this as your base, give the following problems a try. See you again soon!

1)  Line up “rock” with a “for” loop without using random numbers, and create an electric pen of nervousness game!

2) Define rock.tick and try moving the meteorites too.

3) Try making both moving and non-moving meteorites.

  • 0 Comments
  • Filed under: Tutorial
  • Greetings! shi3z here.

    The other day I had fun as both a guest and a participant at the Pacific Rim Mini Game Development Olympics, but I felt a bit bad about winning the Grand Prize. I’ve got lots of experience, and knew what to do, and next time I think it best that I not take part.

    But I had a lot of fun, both with the event and the mini games themselves.

    I hope to do it again.

    However, most of my programmers had reached the limits of their energy, and I was left with only two.

    In a fix, I decided to take it upon myself to teach Hidemy…who had zero experience in game programming…the basics in three days and send her to participate in the contest. Would this work?

    Continued below:

    In fact, the “Super Easy Programming” guides were originally put together so that Hidemy would be able to learn the basics.

    Truth be told, I wasn’t sure how quickly an English Literature major like her could pick it up.

    Last night, after we had all eaten, I said, “After you’ve read Alan’s guide, make a program of your own and send it in.”

    This was 8 o’clock.

    Then, to my amazement, at 12 o’clock…just 4 hours later…Hidemy sent the following in:

    //Flower
    function flower(){
    for(i=0;i<180;i++){
    if( i<10 ){
    move(2);
    turn(1);
    }if( i>170 ){
    move(2);
    turn(1);
    }else{
    move(1);
    turn(1);
    }
    }
    }

    function onLoad(){
    logo.init();
    penDown();
    for(j=0;j<9;j++){
    flower();
    turn(90);
    }
    penUp();
    }

    She sent in two others as well:

    I was stunned at the speed with which she absorbed this information.

    I thought to myself, “This just might work.”

    With that in mind, I decided to start the guide to game programming.

    Alan’s guide is easy to understand but takes a while to get through, so I’ve gather below a .zip file of everything you need to make a game.

    Please download the file below.

    Game Basics: (game.zip)

    It’s similar to the files that Alan came up with.

    The only real difference is the presence of a file called “game.js” and an “img” folder.

    First, open main.js in the text editor.

    For those of you who’d rather use a browser, here’s a link:

    http://junk.wise9.jp/game/

    Our first program is to display a game character.

    function onLoad() {
    banana = new Image('img/banana.png'); // The character appears here
    }

    The key point of this program is “new Image.”

    This command creates a new image and inserts the variable “banana.”

    This “Image” is a new program I defined specifically for the purpose of teaching game programming. In JavaScript, you can call up clusters of programs from within another.

    We call these clusters of programs “classes” or “libraries.” Actually, classes and libraries are in truth something slightly different, but for the moment we won’t worry about that. If you’re interesting you can look it up, or wait for Alan to discuss it in his series.

    Game development is filled with dull and troublesome tasks. With that in mind, I’ve put together this group of the minimum ingredients necessary to create a game. If this were food, it would be a shrink-wrapped instant meal. We can’t call it gourmet, but anyone can make it and be satisfied. Think of it that way.

    This sort of class contains all the experiences of the programmer who determined the classes. This Image class is one of those.

    Think of it as the secret sauce.

    Now then, see what happens when you execute this program!

    Take notice. Game programs are quite intense. That’s why once you hit “Execute Game,” if you want to stop it or rewrite the source code, you’ll have to reload once.

    Even if you reload, your code won’t disappear, so don’t get too anxious.

    Let’s take a look at those strange characters that come after “new Image.”

    new Image(‘img/banana.png’);

    This, as you may have guessed, is the “File name.” “img” points to the file name, and “banana.pg” becomes the file name. The folder and file name are connected by “/”. You’re probably pretty familiar with all this.

    In “banana.png” there’s a picture of a banana. It may not look like a banana, but just have faith in me here. In this zip file, I’ve prepared basic images necessary for creating a game.

    There’s a lot more besides bananas in there, so please take a peak inside. Next, let’s make our character move. A moving banana’s kind of creepy, so let’s change it to a spaceship. Give the following program a shot.

    function onLoad() {
    ship = new Image('img/starship.png'); //A
    ship.tick = function(){ //B
    this.x = this.x + 1;//C Here we define the movement of the spaceship
    };
    gameStart(); //D
    }

    A few new commands have shown up.

    If line A sets the “Image” as a ship, what does line B do?

    As it turns out, JavaScript variables are all object variables, and you can insert not just numbers but programs as well.

    This is the “tick” variable we’ve set inside the ship variable. This “tick” is a special variable called up at regular intervals.

    The contents of “tick” in line C are quite simple.

    this.x = this.x +1 ;

    A version of “this.x” plus 1 is substituted again for “this.x.” This “this” refers to the object defined by the variable, in this the “ship” itself. Just as there is a “this.x,” there is naturally a “this.y.” Why is it structured this way?

    This is a source of considerably frustration when studying math in school.

    You’d think, “This sort of this.x is impossible.”

    However, this is a substitution and not an equation. It’s not meant to solve anything.

    If you’re confused, consider the following image:

    this.x ← this.x +1 ;

    The “this.x” on the right is a past “this.x,” while the “this.x” on the left is a future “this.x.” Remember the direction of the arrow.

    For example, if “this.x” is 0 when this equation is executed, the end product of this.x will be 1.

    The first stumbling block in programming is mixing up substitutions and equations.

    It’s quite easy when you understand it, but if you don’t establish it first people will be get overwhelmed.

    If you give this a try, the spaceship should appear in the center of the screen and move slowly to the right.

    This is because as levels are added regularly to “this.x,” the coordinates of “this.x” change.

    We’re almost done with part one, so finally I’d like to try a program that let’s the character move where you want him to. I’ll explain in detail next time.

    Please give it a try!

    function onLoad() {
    ship = new Image('img/starship.png');
    ship.tick = function(){ // The spaceship will follow your cursor
    this.x += (mouseX-this.x)/10;
    this.y += (mouseY-this.y)/10;
    };
    gameStart();
    }
  • 0 Comments
  • Filed under: Tutorial
  • Last time I promised you an introduction to game programming, but it appears that the series “shi3z Game Programming” will be covering that. Instead, let me go into a little more depth about the fun of programming!

    This time, let’s talk about something called “recursions.”

    What on earth is a “recursion?”

    Recursions will enable you to create stuff like this!

    Let’s give it a go.

    (continued after the link)

    A few posts back, we talked about something called functions.

    What happens if we call up functions with functions?

    How to explain?

    So far we’ve used the principal function onLoad, and then defined and called up functions we defined ourselves, like circle or random.

    Naturally, one can easily call up functions from within functions.

    So, what happens when we call up functions from functions?

    You get a mess. The code below is a sample, but DO NOT try it out. You might very well bust your browser.

    function onLoad(){
    onLoad(); // What happens here?
    }

    A clever browser like Safari gives us this warning. So, what exactly does it mean?

    maximum call stack size exceeded

    As it turns out, herein lies the secret of calling up functions. You may call up functions freely, but not without limit.

    In other words, there is a limit to number of times you can call up a function. This is called “call stack size.”

    If you call up an unconditional onLoad function within an onLoad function, this calls up new onLoad functions without limit.

    As a result, no matter how large you set the “maximum call stack size,” you are virtually guaranteed to exceed it.

    The call stack size is set at a perfectly reasonable size, but if you call up functions infinitely you’re bound to reach this error.

    Why on earth does such a dangerous function…one with the power to call up itself…exist?

    As it turns out, if you use it properly, it can be extremely useful. It’s a technique called “recursions.”

    Take a look at the following code.

    function onLoad(){
    var proc = function(t){
    if(t<1) // Ends recursion when t falls below 1.
    return;
    for(var i=0;i<360;i++){ // Draws a circle.
    move(t);
    turn(1);
    }
    proc(t*0.8); // Multiplies t by 0.8 and draws a circle again.
    };
    penDown();
    proc(3);
    logo.penUp();
    }

    When you execute, it turns out like this:

    This time we executed without any difficulties in the browser.

    What’s going on here? As you can see, proc is being called up many multiple times. Alert can help you easily understand this program.

    Rewrite the program as you see below.

    function onLoad(){
    var proc = function(t){
    alert(“t=”+t);
    if(t<1) // Ends recursion when t falls below 1.
    return;
    for(var i=0;i<360;i++){ // Draws a circle.
    move(t);
    turn(1);
    }
    proc(t*0.8); // Multiplies t by 0.8 and draws a circle again.
    };
    penDown();
    proc(3); // Assigns 3 to the first level of t.
    logo.penUp();
    }

    Each time “proc” is called up, the “t” level will be displayed in alert. At first, the “t” level is 3.

    The next is “t=2.4000000000000004,” or in other words about 2.4, then 1.92, 1.536, 1.2288, and when it hits 0.98304 next it is less than 1 and so recursions end.

    Take a look at the image on the right. Each time the recursion repeats the radius of the circle gets progressively smaller.

    In this way, recursions allow a limit to be established while calling up a function itself.

    Does this seem difficult? Recursions require quite a lot of experience before you can get used to them. If do learn how to use recursions, however, you can truly claim to be a self-reliant programmer.

    Let’s end with a graphic for drawing a tree using recursions.

    function onLoad(){
    a=20;
    b=0.8;
    var proc = function(t){
    if(t<10){ //  Ends recursion when the level of t falls below 10.
    move(t*b); // Continue.
    move(-t*b); // Return.
    return;
    }
    turn(-a*b);
    move(t*b);
    proc(t*b); // Calls forth function itself (recursion callup).
    move(-t*b);
    turn(a*b);
    turn(a);
    move(t*b);
    proc(t*b); // Calls forth function itself (recursion callup).
    move(-t*b);
    turn(-a);
    };
    penUp();
    turn(180);
    move(-100);
    penDown();
    proc(80);
    logo.penUp();
    }

    You getting an idea of what will happen? In order to get the hang of this program, it’s a good idea to change up the numbers and move around move and turn.

    There’s nothing particularly shocking going on here. Just the help of recursions.

    Watch out for endless recursions, and have fun!

  • 0 Comments
  • Filed under: Tutorial
  • Alan here. When we talked last, I showed you how to make functions.

    So far we’ve learned about variables, commands, and loops, as well as how make your own commands through functions.

    This fills out most of the essentials for making a program, but we still haven’t discussed one of the basics. This is a “conditional statement.”

    This is how you make a command to say, “do xx after ○○ happens.” It’s a command that you use quite frequently, but if you don’t have programming experience it’s a bit hard to think of ways to use it.

    For instance, you often use it to make game characters move.

    It’s something like “when the right key is pressed, the character moves right.”

    The computer makes the character move to the right after “judging” the condition of the right key being pressed.

    In other words, “if” is the very brains of the computer. One could very well say that how well you use “if” in a program determines your skill as a programmer.

    (continued after the link)

    Last time we discussed in our practice problems how to make a program that draws circles. It should look something like this:

    function circle(){
    for(i=0;i<360;i++){
    move(1);
    turn(1);
    }
    }

    function onLoad(){
    logo.init();
    penDown();
    for(j=0;j<4;j++){
    circle();
    turn(90);
    }
    penUp();
    }

    The end result should turn out like below.

    Here, we rotate the circle by 90 degrees, drawing it four times, so we end up with the following result.

    Let’s use “if” to change this shape up a bit.

    Let’s rewrite the circle function as the following.

    function circle(){
    for(i=0;i<360;i++){

    if( i<30 ){
    move(5);
    }
    move(1);
    turn(1);
    }
    }

    “if” appears in the middle. It’s resembles a loop a bit in that regard.

    In the case of “if,” the contents of the parentheses following “if” are referred to as the “conditional expression.” If this is conditional expression is fulfilled, the contents of the parentheses are executed. Here, each time “i” is less than 30, move(5) is executed.

    Let’s give it a go!

    Quite the odd shape, huh? Here we have 4 connected, so let’s rewrite the program so that only one is displayed.

    It’s as though one edge of the circle spins off into oblivion. Here you have proof that “move” is being frequently executed only when “i” is less than 30.

    Let’s mix things up even more.

    function circle(){
    for(i=0;i<360;i++){

    if( i == 180 ){
    turn(90);
    }else{
    move(1);
    turn(1);
    }
    }
    }

    [/pre]

    Here we’re making a 90 degree turn only when “i” equals 180. Also note the command “else” that shows up after “if”’s {} brackets.

    This “else” forms a set with “if,” meaning that if the conditions of “if” are not fulfilled, “else” will be fulfilled.

    Here, when “i” is exactly equal to 180 it will turn 90 degrees. Otherwise, it will move as though drawing a regular circle.

    Can you imagine what this will look like?

    Here it is:

    If we repeat the loop four times, we end up with the flowerlike pattern below.

    As you can see, “if” can be used in many fun and unusual ways.

    Congratulations! We’ve now gone over all the basics of programming.

    Next time, let’s jump right into game programming! Stay tuned!

  • 0 Comments
  • Filed under: Tutorial
  • Greetings! Alan here.

    Let’s dive right back into programming!

    This time, let’s talk about functions!

    You may have heard about functions in school. Did you know, however, that the original Japanese word for “function” means “box?”

    Not quite what you were expecting, huh?

    We’re not talking about numbers so much as we are shapes.

    In today’s world of computer programming, “functions” can refer to much more than just numbers.

    Computer functions are skilled at creating movements or operations.

    By the way, how did last time’s homework turn out?

    We took a loop that made a fern pattern and looped it again.

    What kind of shape did you end up with?

    function onLoad(){
    logo.init();
    penDown();
    for(j=0;j<4;j++){
    for(i=0;i<360;i++){
    move(10);
    turn(i);
    }
    turn(90);
    }
    penUp();
    }

    You can give this a try using the interpreter created by our own shi3z as well: http://junk.wise9.jp/js/ .

    Now then, when we nest two loops the program gets rather complicated.

    Doesn’t it seem a bit troublesome to write one loop at a time each you want to “draw a spiral” or “draw a circle?”

    This is what functions are for. This is essentially different from the “functions” used in mathematics.

    Let’s make a function for that spiral pattern, simplifying that loop.

    function uzumaki(){ // This defines the function.
    for(i=0;i<360;i++){
    move(10);
    turn(i);
    }
    }

    function onLoad(){
    logo.init();
    penDown();
    for(j=0;j<8;j++){
    uzumaki(); //←This is where you call up the function.
    turn(45);
    }
    penUp();
    }

    It’s not at all difficult to program a function.

    A function repackages a program in a new framework.

    Go ahead and execute the code above.

    The results should be slightly different from what you created last go round.

    The “function” defined above creates a new function called “uzumaki.”

    It is “called up” inside the loop.

    The function is “called up” by the function name and the parentheses behind it. Compare the upper and lower halves of the code.

    Do you notice anything?

    As it turns out, all the programs you’ve written up until now have used the function “onLoad.”

    You’ve been writing functions without even realizing it!

    Moreover, the now-familiar “turn” and “move” functions are functions defined in separate files. When you make a function, you make a command, and programming consists of summoning commands that you have written. Herein lies the fun of programming.

    By defining various functions, you can create your own language, your own commands, and your own little world. One could indeed say that programming creates your own small universe.

    Has this made functions a little more appealing?

    Well, we’re still doing pretty boring stuff, so let’s attempt a bit of a function “prank.”

    function uzumaki(){
    for(i=0;i<360;i++){
    move(Math.random()*10);
    turn(i);
    }
    }

    Many functions are already predetermined. Math.random is one of these.

    This refers to a function called “random” within a genre called “Math.”

    JavaScript contains countless functions. One couldn’t hope to remember them all. I certainly can’t.

    With that in mind, we’ll just introduce a few of the really essential ones. You’ll never need to remember all of them. I’d wager that no one has really memorized them all. If you search for “JavaScript Functions” online, you’ll find what you need when you need it.

    Anyway, back to Math.random. This is an extremely interesting function that generates random numbers from 0 to 1. If you multiply it by 10, it will generate levels from 0 to 10. The line it generates might will have been drawn by a drunk.

    By using random numbers, the results of the program always turn up differently. In other words, there’s nothing wrong if your results are different from the picture above.

    The random numbers you see in games use functions just like this one.

    This particular function feels quite apt for the “Math” category, but doesn’t the math you learn in classrooms seem kind of pointless? I mean, what useful purpose could f(x)=ax+b possibly serve?

    Functions in programming are much more slick. These are functions that actually “function.”

    If you rewrite uzumaki with Math.random, I think you’ll see how useful and interesting functions can be. Give it a try!

    I said that Math.random returns results from 0 to 1, but you can do this with your own functions as well.

    You can also define parameters for math functions and functions like move and turn.

    Try rewriting your program to what you see below.

    function random(x){
    return Math.random()*x;
    }

    function uzumaki(){
    for(i=0;i<360;i++){
    move(random(i));
    turn(i);
    }
    }

    function onLoad(){
    logo.init();
    penDown();
    for(j=0;j<8;j++){
    uzumaki();
    turn(45);
    }
    penUp();
    }

    Math.random may be convenient, but it has a regrettably long name and writing out 10 or so is quite inconvenient. With this in mind, I made an original function for returning random numbers called random(x).

    When defining functions, if you set your variables in the parameters section, you can use them in functions as well.

    And when you want to return a value, you set the desired value after the “return” command.

    In this case, that means you’re returning a level multiplied by x in Math.random.

    The uzumaki function also features some clever craftsmanship when it calls up “random.”

    We reset the area that was set as “10” to the variable “i.”

    What happens?

    “i” expands from 0 to 360, so here the random numbers generated also expand from 0 to 360. In other words, our drunk’s strides get wider and wider the further he goes.

    Give it a try!

    Also, here’s some additional ideas to try out.

    Practice Problems

    1. Assign some random numbers to “move”

    2. Try making your own circle or square function.

  • 0 Comments
  • Filed under: Tutorial
  • Super Easy Programming 2: A System for Loops, Turtle-Style

    Greetings. Alan here.

    Did you draw the picture last time?

    It should look like this:

    Do you see what’s going on here?

    Let’s review.

    We moved 100 dots, turned 90 degrees, moved another 100 dots and turned 90 degrees, and repeated the procedure four times.

    Code from Last Time:

    function onLoad() {
    	logo.init(); 
    
    	penDown();
    	move(100);
    	turn(90);
    	move(100);
    	turn(90);
    	move(100);
    	turn(90);
    	move(100);
    	penUp();
    }

    This works okay, but isn’t it a bit troublesome to copy and paste the same code four times? When you want to repeat in a program, the easiest thing to do is to use a command called “for.” Let’s redo our square-drawing program using “for.”

    function onLoad() {
    logo.init();
    penDown();
    for(i=0;i<4;i++){
    move(100);
    turn(90);
    }
    penUp();
    }

    This should produce the exact same square as in the last program. Check for yourself.

    As you can see above, “for” is a command for repeating the information contained within {} and 「」a set number of times. Here, you can see the number 4. This is the number of times the command will be repeated.

    This command is called a “loop.” However, at this stage doesn’t copy and paste still seem faster? To see the benefits, try out the code below.

    function onLoad() {
    logo.init();
    penDown();
    for(i=0;i<360;i++){
    move(1);
    turn(1);
    }
    penUp();}

    We’ve changed 4 to 360, and move and turn to 1 each. You have any idea what might happen?

    Check out the results below:

    You just drew a perfect circle!

    “for” certainly is easier than copying and pasting 360 times, huh?

    Let’s take a closer look at all those “i”s that appeared within “for.”

    This “i” is a “variable.”

    What’s a “variable,” you ask? Simply put, it’s a number of changes.

    The contents change, little by little.

    Let’s take another look at that “for” line.

    for(i=0;i<360;i++){

    If we take a peak inside “for”’s parentheses, what we find may be a bit intimidating.  However, remember that “;” signals the end of a sentence.
 It can also mean a pause or a break. In that case, this particular sentence is divided into “i=0,” “i<360,” and “i++.” The first “i=0” is command 
assigning “0” as the variable. Therefore, i is equal to 0. The “for” sentence decides whether or not to repeat the loop after executing the contents of {}, which in this case is move and turn. 
Here we use the formula “i<360.” 
As you may have guessed, it means that the loop will repeat “if i is smaller than 360.” So what about that last “i++?” This is a command to increase the contents of i by 1.

    Let’s try increasing the contents of i by 2 each. Change “i++” to “i+=2,” save, and reload.

    What happens?

    We only have half a circle!

    Adding 1 apiece created a full 360 degree rotation, whereas adding 2 apiece, the loop was only repeated 180 times and we ended up with only half a circle.

    If you use this the right way you’ll get some interesting results.

    Try using the following to create an octagon.

    penDown();
    for(i=0;i<360;i+=360/8){
    move(360/8);
    turn(360/8);
    }
    penUp();

    You’re dividing 360 into 8, and repeating only that part of the rotation.

    You’ve divided it to end after 8 turns, so you end up with an octagon.

    Naturally, you can use this to create a triangle, or a hexagon, or any other shape you’d like.

    However, the one most people don’t consider is a heptagon (7 sides).

    You can’t divide 360 into 7.

    It’s extremely difficult to draw a heptagon with a protractor. That’s where computers come in handy.

    Here’s what we end up with.

    Quite the weird shape, huh?

    Not to be sidetracked, but I remember becoming an elementary school hero when I could draw a heptagon while my classmates were still struggling with pentagons and octagons. You never know when programming might come in handy!

    Incidentally, there are times when this “i” is referred to as a “loop variable” or “incrementer.”

    So, are loops a little more interesting now?

    Let’s try out another trick.

    As it turns out, you can use this loop variable “i” inside the loop.

    Give the following a try.

    for(i=0;i<360;i++){
    move(10);
    turn(i);
    }

    Any guesses as to how this will turn out?

    You’re simply moving 10 dots and turning by “i” degrees. However, the “i” rises from 1 to 360, meaning that the curve also increases steeply.

    What on Earth…?!

    You can use a look to draw this strange spiral-looking shape. Just FYI!

    You can also use the loop to make more loops.

    for(j=0;j<4;j++){
    for(i=0;i<360;i++){
    move(10);
    turn(i);
    }
    turn(90);
    }

    I added an additional “j” loop outside the original “i” loop and repeated the “spiral” four times. Any guesses as to what will happen?

    Give it a try and see what appears! See you next time!

  • 0 Comments
  • Filed under: Tutorial
  • Greetings! Alan here.

    We’ve been hearing from a lot of folks who want to try programming but don’t know where to start. Allow me to go back to the basics and explain from step one.

    There are lots of programming languages out there, but let’s start with one that’s popular and free: JavaScript.

    You’ll need:

    ・A web browser (Chrome or Safari, NOT Internet Explorer)

    Download the latest web browser; it’s absolutely free. If you’re using Windows, you can still download Apple’s Safari browser. Google’s Chrome browser also works. None of them cost a dime.

    Windows’ Internet Explorer works a bit differently, so we’ll leave it for later.

    ・A text editor you’re comfortable with. Unfortunately, Windows’ standard Microsoft Word, Note Pad, and Wordpad won’t work here. For Windows, try Apsaly (http://www.vector.co.jp/soft/win95/writing/se423509.html). For Mac, you can download mi (http://www.mimikaki.net/). Both are free and easy to use.

    And that’s all you need!

    There are multiple ways to start programming, but let’s begin with the most traditional.

    We’ll proceed with the following steps.

    1. Enter a model program.

    2. Execute the model program.

    3. Revise the model program.

    4. Execute the revised program and check it.

    5. Try something harder!

    In general, you learn faster with a model to start from.

    This is a shortcut to learning computer programming. It works for most any programming language. Now then, what should we use as our model?

    Something too basic will be dull, and something too advanced might scare you off. Lots of people are interested in programming but quickly get turned away by the long strings of strange symbols. Who cares about all that math?

    With that in mind, why don’t we start with some computer graphics?

    When beginning to program, one must first remember something called a source code.

    Source code is also simply called code for short (however, be aware that “code” can have other meanings as well). This refers to the programming language a program is written in.

    Programming languages are special languages to give commands to computers. Special commands require special “grammar.” However, these are manmade languages, and far simpler than any foreign language that humans speak.

    Let’s jump right in. Copy the following codes into a text editor, and save under the designated file names.

    File name: start.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=”UTF-8″>
    <script type=”text/javascript” src=”wiselogo.js”></script>
    <script type=”text/javascript” src=”main.js”></script>
    </head>
    <body onload=”onLoad()”>
    <canvas id=”canvas0″ width=”500″ height=”500″
    style=”border:1px black solid”>
    </canvas>
    </body>
    </html>

    File name: wiselogo.js

    var Vector = function(x,y){
    this.x = x;
    this.y =y;
    this.plus = function(v){
    this.x += v.x;
    this.y += v.y;
    },
    this.times = function(t){
    return new Vector(this.x*t,this.y*t);
    }
    };

    var logo = {
    canvas:null,
    context:null,
    cursor:new Vector(250,250),
    direction:new Vector(0,1),
    rotate :0,
    pen : false,
    penDown:function(){this.pen = true;},
    penUp:function(){this.pen = false;},
    init:function(){
    this.canvas =document.getElementById(“canvas0″);
    this.context=this.canvas.getContext(“2d”);
    },
    turn:function(r){
    this.rotate += r;
    this.direction.x = Math.sin(this.rotate*3.14159/180);
    this.direction.y = Math.cos(this.rotate*3.14159/180);
    },
    move :function(t){
    if(this.pen){
    this.context.beginPath();
    this.context.moveTo(this.cursor.x,this.cursor.y);
    }
    this.cursor.plus(this.direction.times(t));
    if(this.pen){
    this.context.lineTo(this.cursor.x,this.cursor.y);
    this.context.stroke();
    }
    },
    printpos :function(){
    alert(‘hoge: ‘+this.cursor.x+”,”+this.cursor.y);
    }
    };

    var move = function(t){logo.move(t)};
    var turn= function(r){logo.turn(r)};
    var penDown= function(){logo.penDown()};
    var penUp = function(){logo.penUp()};

    File name: main.js

    function onLoad() { // We’ll deal with this later.
    logo.init(); // This too.

    penDown(); // Lower pen.
    move(50); // Move 50.
    penUp(); // Raise pen.

    }

    After saving these source codes under the correct file names, open start.html in Safari or Chrome.

    For Mac, simply double-click start.html. For Windows, if Chrome is not set as your default browser, simply open a new window in Chrome and drag and drop start.html into the browser.

    How’d it go?

    You should be seeing a screen that looks like this.

    If you aren’t, check the following.

    • Make sure that start.html, wiselogo.js, and main.js aren’t all in the same file.
    • Are you using Chrome or Safari? (remember, Internet Explorer doesn’t work)

    So, what exactly does this program do? Most programs have one main element. For this basic program, that element is of course main.js.

    What does main.js do? Let’s ignore “function” and “init” for the time being and focus on “penDown().”

    As it turns out, this is a drawing tool. You need a pen to draw, right?

    Imagine that the screen is a piece of paper, and you’re holding a pen. Lower the pen to the paper. “penDown()” does just that.

    “move(50)” moves the lowered pen by 50 dots.

    Lastly, “penUp()” raises the lowered pen.

    That’s why you see a straight line in the middle of the screen. You can grasp a lot of the basics of programming language in this one short program.

    Let’s go into a bit more depth.

    In JavaScript, the text after a double slash (//) is called a comment and can be filled out freely. It’s usually used for memos to make the program easier to understand.

    The blue areas are commands. However, in JavaScript commands are referred to as functions (there’s a slight technical difference but we’ll ignore it for the time being.

    penDown is a command for lowering the pen.

    The parenthesis after a command define that command’s parameter. “penDown” doesn’t have any parameters set, but “move” is set to 50.

    The final semicolon (;) indicates the end of a phrase. It’s analogous to the period at the end of a sentence.

    Computers get confused without a semicolon and don’t know where a sentence ends. Be sure to remember your semicolons from here on out!

    This is all pretty dull, isn’t it?

    Let’s rewrite main.js and see what happens.

    Using your text editor, change main.js to the following:

    function onLoad() { // We’ll deal with this later.
    logo.init(); // This too.

    penDown(); // Lower pen.
    move(50); // Move 50.
    penUp(); // Raise pen.
    move(50);
    penDown();
    move(50);
    penUp();

    }

    How’d it go? Did you get the following screen?

    Are you starting to get the hang of it?

    We lowered the pen once, moved it 50 dots, raised it, moved it another 50 dots, lowered it again, moved it 50 dots, and raised it once more.

    Hence, the two lines on your screen.

    Since you can only make straight lines with penDown, move, and penUp, let’s introduce a new command: turn.

    As the name suggests, “turn” changes direction.

    Change main.js to the following:

    function onLoad() { // We’ll deal with this later.
    logo.init(); // This too.

    penDown();
    move(100);
    turn(90);
    move(100);
    turn(90);
    move(100);
    turn(90);
    move(100);
    penUp();
    }

    “turn,” like “move,” requires a parameter.

    The parameter for move was distance of movement. The parameter for turn is angle. We moved 100 dots, turned 90 degrees, moved 100 dots, turned 90 degrees, and repeated four times.

    What happens? Give it a try and find out!

    Next time we’ll try something a little harder!

  • 6 Comments
  • Filed under: Tutorial
  • about “enchant.js”

    enchant.js is an HTML5 + JavaScript based game engine. It is a standalone library that enables cross-platform application development for PC, Mac, iPhone, iPad, and Android from just 30 KB of source code.

    enchant.js was developed at Ubiquitous Entertainment Inc.'s Akihabara Research Center, and released April of 2011. Nearly 200 games have been created in its first two months of release, making it the world's most-used HTML5 game engine.

    enchant.js Official Website

    Category

    facebook Like