enchant.js Developers Blog

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

Our story about using Ruby on enchant.js with HotRuby is nearing its climax. Up until now we’ve focused on whether enchant.js can be called up from Ruby, but this time I tried to actually package it with class succession.

Corrections to HotRuby.protype.classes were among the main additions to the code. Up until now we did anything and everything with Sprites, but here we’ve added Scene and Entity classes.

Entity is the parent class for Sprite, and I prepared a Label for other classes using Entity.

"Sprite" : {
"initialize" : function(recver, args) {
var sprite = new Sprite(args[0],args[1]);
recver.__instanceVars.entity = sprite;
HotRuby.prototype.classes.extendRubyClass("Sprite","Entity");
},
"image" : function(recver,args) {
return HotRuby.prototype.classes.
newNativeObject("String",
recver.__instanceVars.entity.imageName);
},
"image=" : function(recver,args) {
recver.__instanceVars.entity.imageName=args[0].__native;
return recver.__instanceVars.entity.image=
game.assets[args[0].__native];
}
},
"Label" : {
"initialize" : function(recver, args) {
var label = new Label(args[0].__native);
recver.__instanceVars.entity = label;
HotRuby.prototype.classes.extendRubyClass("Label","Entity");
},
"text" : function(recver,args) {
return HotRuby.prototype.classes.
newNativeObject("String",
recver.__instanceVars.entity.text);
},
"text=" : function(recver,args) {
return recver.__instanceVars.entity.text=args[0].__native;
}
},
"Entity" : {
"initialize" : function(recver, args) {
var obj = HotRuby.prototype.classes["Entity"];
'x y scaleX scaleY rotation frame'.split(' ').forEach(function(prop) {
obj[prop] = function(recver,args){
return recver.__instanceVars.entity[prop];};
obj[prop+"="] = function(recver,args){
recver.__instanceVars[prop]=args[0];
return recver.__instanceVars.entity[prop]=args[0];};
obj["@"+prop+"="] = function(recver,args){
recver.__instanceVars[prop]=args[0];
return recver.__instanceVars.entity[prop]=args[0];};
obj[prop+"+="] = function(recver,args){
return recver.__instanceVars.entity[prop]+=args[0];};
obj[prop+"-="] = function(recver,args){
return recver.__instanceVars.entity[prop]-=args[0];};
obj[prop+"*="] = function(recver,args){
return recver.__instanceVars.entity[prop]*=args[0];};
obj[prop+"/="] = function(recver,args){
return recver.__instanceVars.entity[prop]/=args[0];};
obj[prop+"++"] = function(recver,args){
return recver.__instanceVars.entity[prop]++;};
obj[prop+"--"] = function(recver,args){
return recver.__instanceVars.entity[prop]--;};
obj[prop+"<"] = function(recver,args){
return recver.__instanceVars.entity[prop] < args[0] ? this.trueObj : this.falseObj;};
obj[prop+"<="] = function(recver,args){
return recver.__instanceVars.entity[prop] <= args[0] ? this.trueObj : this.falseObj;};
obj[prop+">"] = function(recver,args){
return recver.__instanceVars.entity[prop] > args[0] ? this.trueObj : this.falseObj;};
obj[prop+">="] = function(recver,args){
return recver.__instanceVars.entity[prop] >= args[0] ? this.trueObj : this.falseObj;};
obj[prop+"=="] = function(recver,args){
return recver.__instanceVars.entity[prop] == args[0] ? this.trueObj : this.falseObj;};
});
},
"setupEventListener" : function(recver,args) {
var classObj = ruby.__proto__.classes[recver.__className];
var hr = this;
'enterframe touchstart touchend touchmove'.split(
' ').forEach(function(eventName){
if(classObj[eventName]){
var func = function() {
var hr = arguments.callee.hr;
var proc = arguments.callee.proc;
hr.runOpcode(
proc.__opcode,
proc.__parentStackFrame.classObj,
proc.__parentStackFrame.methodName,
recver,
hr.nativeAryToRubyObjectAry(arguments),
proc.__parentStackFrame,
true);
};
func.hr = hr;
func.proc={};
func.proc.__parentStackFrame=ruby.topSF;
func.proc.__opcode= classObj[eventName];
recver.__instanceVars.entity.addEventListener(
eventName,func);
}
});
},
"addEventListener" : function(recver,args) {
var func = function() {
var hr = arguments.callee.hr;
var proc = arguments.callee.proc;
hr.runOpcode(
proc.__opcode,
proc.__parentStackFrame.classObj,
proc.__parentStackFrame.methodName,
recver,
hr.nativeAryToRubyObjectAry(arguments),
proc.__parentStackFrame,
true);
};
func.hr = this;
func.proc = args[1];
recver.__instanceVars.entity.addEventListener(
args[0].__native,
func);
},
},

As you can see, up until now most of the Sprite contents was divided up as Entity shared contents, and only image (Sprite-native parameter) is treated as a Sprite class.

Also, Label (which like Sprite has the superclass Entity) only provides elements distinct to the “text” Label.

HotRuby class succession is realized with functions like what you see below:

extendRubyClass:function(subClass,superClass,recver,args){
//Ruby class succession
var subClass = HotRuby.prototype.classes[subClass];
var superClass = HotRuby.prototype.classes[superClass];
superClass["initialize"](recver,args); //Calls up parent class constructor
//Class construction rewriting only happens once
if(subClass[superClass+"_done"]){
return;
}
subClass[superClass+"_done"]=true; //Class construction initialization ending flag
for(var i in superClass){ //Copies parent class members (succession)
if(!subClass[i]){
subClass[i]=superClass[i];
}
}
},

HotRuby’s internal construction is such that all included classes are all stored as associative arrays in HotRuby.prototype.classes.

For succession, all you need to do is copy the elements of the super class. At this point, it’s still a fairly whatever-works sort of construction, so it doesn’t work when not calling up the superclass constructor (in normal object orientation the super class constructor is not called up unless explicitly stated).

In any event, here I was able to package Label. The Ruby code looks something like this:

class Bear < Sprite
def initialize w,h,image
super(w,h)
self.image = Game.assets(image)
self.y=50
self.setupEventListener();
end
def enterframe
self.x+=1
end
end
bear = Bear.new(32,32,"chara1.gif")
label = Label.new("Hello enchant.js");
Game.rootScene.addChild(bear)
Game.rootScene.addChild(label)

The “Hello enchant.js” displayed in the opening screenshot is based on work of the Label class.

Of course, you can set both Label and Sprite to subclass event handlers.

class Button < Label
def initialize x,y,text
super text
self.x = x
self.y = y
self.setupEventListener();
end
def touchend
self.text="Thank you!"
end
end
button = Button.new(100,100,"Tap Here");
Game.rootScene.addChild(button)

If you click the “Tap Here” label displayed on the screen, the display should change to read “Thank you” courtesy of the program you just wrote.

Seems like we’ve picked up enough of the essentials to create a game. You can probably create a simple game with this info alone.

If we prepare the Group and Map classes, we should be able to put together most any enchant.js game.

The Group class can be packaged with comparative ease, but he Map class looks a bit tricky. Won’t know until we try though, will we? It might be fairly easy with Ruby’s two dimensional arrays.

Let’s take a breath and move on to the next challenge!

  • Comments Off
  • Filed under: Report
  • Can enchant.js be used on Ruby? Yesterday’s experiment continues. This time I revised HotRuby.js while analyzing HotRuby.

    If you take a look at the guts of HotRuby.js, you realize that it’s rather rough. It’s like the classes are just simply packaged and that’s it.

    The packaging in this area is around line 1110 of HotRuby.js.

    HotRuby.prototype.classes = {
    "Object" : {
    "==" : function(

    In order to make it respond to enchant.js, it’s relatively easy to fiddle around with this area.

    Let’s forget about game.preload for the time being and try packaging the Sprite class.

    "Game" : {
    "assets" : function(recver, args) {
    return args[0];
    }
    },
    "Sprite" : {
    "initialize" : function(recver, args) {
    var sprite = new Sprite(args[0],args[1]);
    game.rootScene.addChild(sprite);
    sprite.image=game.assets['andy.gif'];
    recver.__instanceVars.sprite = sprite;
    var obj = HotRuby.prototype.classes["Sprite"];
    //Package each parameter's operator manually
    //Still a bit rough, but puts into action
    'x y scaleX scaleY rotation frame'.split(' ').forEach(function(prop) {
    obj[prop] = function(recver,args){
    return recver.__instanceVars.sprite[prop];};
    obj[prop+"="] = function(recver,args){
    recver.__instanceVars[prop]=args[0];
    return recver.__instanceVars.sprite[prop]=args[0];};
    obj["@"+prop+"="] = function(recver,args){
    console.log("hoge");
    recver.__instanceVars[prop]=args[0];
    return recver.__instanceVars.sprite[prop]=args[0];};
    obj[prop+"+="] = function(recver,args){
    return recver.__instanceVars.sprite[prop]+=args[0];};
    obj[prop+"-="] = function(recver,args){
    return recver.__instanceVars.sprite[prop]-=args[0];};
    obj[prop+"*="] = function(recver,args){
    return recver.__instanceVars.sprite[prop]*=args[0];};
    obj[prop+"/="] = function(recver,args){
    return recver.__instanceVars.sprite[prop]/=args[0];};
    obj[prop+"++"] = function(recver,args){
    return recver.__instanceVars.sprite[prop]++;};
    obj[prop+"--"] = function(recver,args){
    return recver.__instanceVars.sprite[prop]--;};
    obj[prop+"<"] = function(recver,args){
    return recver.__instanceVars.sprite[prop] < args[0] ? this.trueObj : this.falseObj;};
    obj[prop+"<="] = function(recver,args){
    return recver.__instanceVars.sprite[prop] <= args[0] ? this.trueObj : this.falseObj;};
    obj[prop+">"] = function(recver,args){
    return recver.__instanceVars.sprite[prop] > args[0] ? this.trueObj : this.falseObj;};
    obj[prop+">="] = function(recver,args){
    return recver.__instanceVars.sprite[prop] >= args[0] ? this.trueObj : this.falseObj;};
    obj[prop+"=="] = function(recver,args){
    return recver.__instanceVars.sprite[prop] == args[0] ? this.trueObj : this.falseObj;};
    });
    },
    //Accessor for image property is treated and packaged specially
    "image" : function(recver,args) {
    return HotRuby.prototype.classes.
    newNativeObject("String",
    recver.__instanceVars.sprite.imageName);
    },
    "image=" : function(recver,args) {
    recver.__instanceVars.sprite.imageName=args[0].__native;
    return recver.__instanceVars.sprite.image=
    game.assets[args[0].__native];
    },
    //The key here, event listener, is called up and packaged with a block-equipped method
    "addEventListener" : function(recver,args) {
    //Block area extracted as a JavaScript function
    var func = function() {
    var hr = arguments.callee.hr;
    var proc = arguments.callee.proc;
    hr.runOpcode(
    proc.__opcode,
    proc.__parentStackFrame.classObj,
    proc.__parentStackFrame.methodName,
    recver, // Object is recver
    hr.nativeAryToRubyObjectAry(arguments),
    proc.__parentStackFrame,
    true);
    };
    func.hr = this;
    func.proc = args[1]; //Block is accepted as secondary argument
    // Connects to enchant.js event listener
    recver.__instanceVars.sprite.addEventListener(
    args[0].__native,
    func);
    },
    //Used during class definition style. Mentioned later.
    "setupEventListener" : function(recver,args) {
    var classObj = ruby.__proto__.classes[recver.__className];
    var hr = this;
    'enterframe touchstart touchend touchmove'.split(
    ' ').forEach(function(eventName){
    if(classObj[eventName]){
    var func = function() {
    var hr = arguments.callee.hr;
    var proc = arguments.callee.proc;
    hr.runOpcode(
    proc.__opcode,
    proc.__parentStackFrame.classObj,
    proc.__parentStackFrame.methodName,
    recver,
    hr.nativeAryToRubyObjectAry(arguments),
    proc.__parentStackFrame,
    true);
    };
    func.hr = hr;
    func.proc={};
    func.proc.__parentStackFrame=ruby.topSF;
    func.proc.__opcode= classObj[eventName];
    recver.__instanceVars.sprite.addEventListener(
    eventName,func);
    }
    });
    },

    As I wrote in the comments, the key here is the packaging of addEventListener.

    enchant.js’s secret for simply creating games lies in its event driven model.

    If this is clearly defined on the Ruby end of things, we’ve made quite a lot of progress.

    Last time we forcefully pulled things out of the JavaScript end, but in order for the Ruby side to be packaged neatly, this time we’re making use of Ruby’s trademark block method.

    Thanks to these improvements in HotRuby.js, this Ruby code is much more akin to enchant.js.

    bear = Sprite.new(32,32)
    bear.image = Game.assets "chara1.gif"
    bear.addEventListener('enterFrame'){|e|
    self.x+=1
    }

    You can display these bears and animate them to move to the right. Quite like enchant.js on JavaScript!

    Because functions aren’t a first-level object in Ruby, we can’t deliver nameless functions as in JavaScript. It feels quite unnatural.

    In addition, because Ruby is a programming language with such precisely defined classes, you can think of event processing by overriding class methods, like enterFrame, as the muscle.

    Consider the following example.

    class Bear < Sprite
    def initialize w,h,image
    super(w,h)
    self.image = Game.assets(image)
    self.y=50
    self.setupEventListener(); //Sets up event listener
    end
    def enterframe
    self.x+=1
    end
    end
    bear = Bear.new(32,32,"chara1.gif")

    This is a much easier way of writing things. Of course, part of Ruby’s appeal is the fact that you don’t need to select a way of writing things.

    In the C++-based MFC (Microsoft Foundation Class Library) and the Java-based AWT (Abstract Window Toolkit), it’s normal to package event processing by overriding.

    However, in these types of programming frameworks, the system for receiving events from the OS is not a direct callup method. As a result, some of the elegance is lost, but by calling up setupEventListener within initialize the JavaScript-side events are set.

    I’m no HotRuby expert, so perhaps there’s a slicker method out there (perhaps processing within “super?”).

    However, I feel like our reasons for writing in Ruby and not JavaScript have become clear. When all the objects appearing in a game are expressed as classes, it’s quite elegant and simple to write as event listeners overriding in classes.

    I feel like we’ve approached our goal here. If we make incompatible Scenes, Groups, and Labels functional in Ruby, it’s not that difficult to make an HTML5 game on Ruby and enchant.js.

    I’ve only just started to read the HotRuby source code. If you know of a more elegant way of handling it, please let me know!

  • Comments Off
  • Filed under: Report
  • enchant.js on Ruby? An experiment…

    JavaScript is a terrific programming language, but it has its limits. In particular, class definitions can be a bit troublesome. This bothers more than a few people. enchant.js’s Class.create reduces the problem, but it’s still not ideal.

    But Japan has its own kickass programming language: Ruby.

    One day I thought to myself: enchant.js is already quite easy to use, but wouldn’t Ruby make it even easier? In order to use Ruby in a browser you can try stuff like JSRuby or HotRuby. Of course you can also use JRuby in Java and express as an applet, but this won’t work on smartphones.

    In both cases there doesn’t appear to be a prototype out yet. However, it appears that JSRuby attempts to use the Ruby interpreter in JavaScript, and that HotRuby uses YARV from Ruby 1.9 in JavaScript, with the Ruby compiler on the server.

    JSRuby still lacks some essential constructions, and the appeal of Ruby doesn’t fully come through. With that in mind, this time I used HotRuby and tried to see what would happen when I plugged enchant.js into it.

    For starters, I installed HotRuby to the server. For HotRuby to work I had to first install Ruby 1.9.0. It had to be 1.9.0, specifically. Otherwise, VM: Instruction will not be available for use.

    This is an important class that calls up the YARV compiler from Ruby. After this, all I had to do was install HotRuby on the web server.

    Next up was the actual Ruby code connecting. This turned out to be rather tricky.

    In the case of HotRuby, you first send the Ruby code to the server, compile and receive the YARV interim code. We’re still at the testing stage now, so I decided to basic enchant.js initialization on the JavaScript side.

     enchant(); //Initialize enchant.js
    window.onload=function(){
    game = new Game(320,320);
    game.preload("andy.gif"); //Load Android image
    game.onload = function(){
    andy = new Sprite(16,16); //Make Android sprite
    andy.image = game.assets["andy.gif"];
    andy.setXY = function(x,y){this.x=x;this.y=y;} //Make setter to easily call up from Ruby
    game.rootScene.addChild(andy);
    ruby = new HotRuby(); // Initialize HotRuby
    ruby.runFromScriptTag('http://shi3z.yier.in/compileRuby.cgi'); //Call YARV compiler installed in server
    setTimeout(function(){ //Executes when compile is finished
    game.rootScene.addEventListener('enterframe',function(){
    // Directly calls up compiled interim code object
    ruby.invokeMethod(ruby.topSF.localVars[2], "enterFrame",
    [], ruby.topSF, "VM_CALL_ARGS_SPLAT_BIT" , false);
    });
    },1000);
    }
    game.start();
    }

    When this experimental code is executed, the actual Ruby code should turn out something like what you see below.

    <script type="text/ruby"></script>

    When executed, I got the following screen.

    The Android icon gradually moves to the right as time passes. The Ruby-side “andy” object’s enterFrame method is being called up from game.rootScene.addEventListener(‘enter frame’….) on the JavaScript side.

    By the way, HotRuby is quite interesting when considered in the context of a hypothetical Ruby device.

    If you display Ruby in the Safari console, you can understand visually how the internal YARV data is put together.

    For instance, all classes you create are stored in ruby.classes. If you look into each class in more detail, you find that they are stored in the parent class.

    However, because of native access you can access the JavaScript-side object via a global variable called $native.

    However, the appeal of enchant.js lies in its callback-based event model. If you want to do callbacks carefully, you’ll probably have a hard time without compensating in HotRuby.js.

    It’s necessary to set the Ruby side to “divide up this object, this method, to this event,” and kick this into the JavaScript side.

    If you do this, it becomes comparatively easy to use enchant.js on Ruby. Anyone up for the challenge?

  • Comments Off
  • Filed under: Report
  • Greetings! Alan here.

    If you want to learn programming, HTML5 and JavaScript game development is your best bet for getting started.

    Why? Because you can pick up object orientation…a particularly dull aspect of programming…with startling ease. Consider the game “Aegis Commander.”

    In this game you attempt to shoot down missiles from the decks of the Aegis.

    Everything you see displayed on this screen is an object.

    What’s more, it’s ridiculously easy to write a program that uses these objects.

    For instance, smoke appears behind intercepted missiles. Here’s how that smoke class is defined.

    Smoke = enchant.Class.create(enchant.Sprite,{ //Belongs to Sprite class
    initialize:function(x,y){
    enchant.Sprite.call(this,16,16); //Initializes Sprite at 16x16
    this.image = game.assets['smoke.png']; //Sets image file
    stage.addChild(this); //Brings up smoke on stage
    this.x = x-6; //Sets initial coordinates
    this.y = y-4;
    this.scaleX=0.25; //Displays smoke smaller than actual size
    this.scaleY=0.25;
    this.addEventListener('enterframe',this.move); //Animates every other frame with move method
    this.cnt=0; //Resets countdown
    },
    move:function(){
    this.cnt++; //Updates countdown
    if(this.cnt%4==0){ //Animates smoke only once in 4 frames
    this.frame++;
    }
    if(this.cnt&gt;16){ //After 16 frames, self-destructs and removes this object
    this.removeEventListener('enterframe',this.move);
    stage.removeChild(this);
    delete this;
    }
    }
    });

    And that’s it.

    This was thrown together in just about 2 hours to make it in time for a weekly publication. As a result, there was no refactoring, etc…and yet we still ended up with this wonderfully simple expression.

    It wasn’t long ago that it was well nigh impossible to simply program something like smoke puffing up behind a missile.

    Truth be told, I’d be too chicken to try something like this in C++. I know what can happen with malloc and free cost, and the resulting fragmentation.

    However, you don’t need to worry about any of that with today’s JavaScript. Elaborate care is taken to ensure storage of memory on potential user devices, and whereas in the past it was all but essential to write memory control to avoid compromising performance, in JavaScript there’s no need to stress about hardware issues. It will perform just as you wrote it.

    Keio University SFC professor Toshiyuki Masui called this hardware-worry-free programming style “Luxury Programming.”

    With JavaScript and HTML5, this sort of “Luxury Programming” is even possible on cell phones. I’ve been programming for a long time, and this amazes me.

    In the old days programmers were locked in a constant battle with hardware, and the ability to use a machine to its limits was a sign of skill.

    enchant.js was created to easily develop games using HTML5 and JavaScript along the lines of simple BASIC games. However, because web browsers and hardware have evolved so much, you can now easily write without worrying about the processing that would have been hell on BASIC.

    Of course, this doesn’t mean that we’re completely free of limits. But up until now it was practically impossible to experience the process of creating a complicated, object oriented game like this.

    For example, if trying to learn object orientation with Ruby or Python, the “object” in object orientation didn’t feel like a box with numbers in it or a vessel to put a method in.

    At its heart object orientation was born from an image of objects exchanging messages and in the process acting harmoniously.

    What we call methods today used to be called “messages,” and were born from an image of messages sent between objects.

    The connection between words and images is particularly important for beginners. It is far easier to understand “objects” as things like explosions and missiles, rather than something intangible.

    Class succession and polymorphism, duck typing, and other difficult-to-grasp concepts become clearer in games.

    Moreover, without any particular trickery, the code you write becomes the image you see. “It turned out just as I expected.” This is exactly the experience we want beginners to have.

    A game programmer can be born in just half a day, and his or her skills can grown from there. Think of this as the fast lane towards becoming an HTML5/JavaScript programmer.

    Here at ARC, we’ve seen complete amateurs able to write programs that functioned just as they hoped after less than a day of studying JavaScript programming.

    The act of turning programming into a puzzle, a fun riddle to be solved, allowed them to make programming their own.

    We’re currently investigating the possibility of creating educational programs to help beginners learn programming basics through enchant.js.

    We’ll give an educational event or two a try. If it goes well, we’ll open the program up so that anyone can host an event for their friends and coworkers in their hometown.

    In any event, JavaScript is super easy and fun. That much is clear.

  • Comments Off
  • Filed under: Report
  • Greetings! enchant.js evangelist Eric here.

    Just returned to the comforts of Holiday Inn after day two of New Game Conference. The day saw the handing out of the last of our swag, the shuffling feet of programmers hung over from last night’s blue cocktails, and quite possibly the weirdest cupcakes I’ve ever beheld.

    In case you can’t tell from the photo, they’re glittering. Yeah. I’m not sure how many edible substances *glitter.* Perhaps we’d best save that discussion for another day.

    In any event, vampire cupcakes or not, the day was a good one! It got started with a keynote from Paul Bakaus, CTO of Zynga Germany.

    Paul took us through his own experiences attempting to develop an HTML5 game engine, beginning at a time when no such thing existed. The lack of competition made his work that much more difficult. Vast strides have been made in Canvas, WebGL, and more, but there’s still considerable room for improvement. Paul discussed how web developers rarely make good game developers (and vice versa) and speculated on some of the reasons why HTML5 has not been more widely adopted (his theories: Devs don’t want to learn it, and companies don’t want to ditch versions of IE below 9). HTML5 wasn’t created with games in mind, and as a result the HTML5 game developer’s situation is an exciting, fun, but painful one.  In elaborating on the challenges ahead, he touched on the example of 3D, showing how overdeveloping is not always good. Consider this realistic take on a certain Sesame Street character:

    Later, we checked out “The State of HTML5 Games in Asia” by Robbert Van Os and Chen Qi of spilgames.

    The pair discussed their experiences marketing games internationally and the pitfalls involved in localizing. They boasted the first HTML5 game portal in China, a hugely difficult task given that Facebook is banned outright, the “Great Firewall” makes local hosting a necessity, and fragmented nature of the market. Still, the huge user base…one that is rapidly adopting smartphones…makes the challenge worth it. HTML5 has the potential for hugely expanded opportunities in the future, the pair said.

    Finally, we sat in on “Paladin: 3D Gaming on the Open Web” by Alan Kligman and Bobby Richter.

    The pair shared their own HTML5 game development journey, which all began with a JavaScript demo animation entitled “Flight of the Navigator.” Demos often pushed forward web innovation, they said, but games push it even further. With that in mind, they are actively pursuing Paladin, a project with Mozilla to weaponize the web platform for 3D gaming. At the moment it’s in pre-alpha, but by the end of the year it should be developed enough to make an actual game with it. Alan and Bobby gave us a glimpse of things to come with their minigame “RescueFox.”

    Besides all that, it was a day of chatting, listening, and evangelising like a fanatic!

    For those of you in Boston, be sure to come listen when we speak at this month’s Boston HTML5 Game Development Meetup! Until then, beware of sparkling cupcakes.

  • Comments Off
  • Filed under: Event
  • Greetings! enchant.js evangelist Eric here!

    As you can see in the pic above, I’m currently lurking at the Yerba Buena Arts Center in San Francisco, an art museum cheerfully doubling as a convention center for New Game Conference! Fellow enchant.js-er Hidemy is fighting the good fight alongside me.

    Day 1 started bright-eyed and bushy-tailed at 7 a.m., a grueling situation made less so by the free breakfast.

    There were shiny little stickers scattered hither and yon.

    And naturally, our own swag was amongst the mix!

    Not to mention our logo lurking in the corner of the official game slides, right next to IE, the other gold sponsor…

    The day started with a bang courtesy of Richard Hilleman, creative director at EA, and his keynote “Finding the Missing Pieces: Completing the HTML5 Gaming Platform Picture.”

    A running theme throughout the day was the ongoing challenges laced amongst all the potential of HTML5 gaming. Richard postulated that two developments are key to making the system work: a Killer App, and that hard-to-define “magic” that makes users embrace a new system. Richard pondered whether or not the hugely popular “Angry Birds” might be that killer app. The potential is there, but in his view, the real game-changing pieces are still to come. HTML5’s potential lies in time…the ultimate asset for a user.

    Next, we check out a presentation from Moblyng COO Justin Quimby, who talked about “Hard-won Lessons from the Trenches.”

    After three years of experience, Justin stressed that HTML5 has huge potential but a long way to go. Android and iOS devices are flooding the market, but the testing level for speed and performance remains uneven. He argued for the need for higher standards and more universal quality across the spectrum of devices.

    After a bit of a break, we checked out Bocoup programmer and evangelist Darius Kazemi’s “Fieldrunners HTML5: Bringing a Hit iOS Game to the Web.”

    Darius explored the myriad challenges in porting an iOS hit into HTML5, a process that was projected to take 8 weeks but ended up requiring 12. After rewriting some 24,596 lines of code, Darius urged programmers facing the same task to think hard about their target platform and audience. He reminded us of a tradeoff: highest quality, or widest audience? How can we strive for both?

    Onan Games’s Miguel Angel Pastor covered a similar topic in his “From Apple Store to CWS.”

    Miguel used a platform called Mandreel, the handiwork of his 5-man company (which is also responsible for hit games like Kroll and Bug Village). Again, the porting process was fraught with difficulties, and Miguel closed with a “wish list” of features to solve various HTML5 logistical problems.

    The day ended with a short session from appMobi’s engineer Sam Abadir and his talk on “Extreme Mobile HTML5 Canvas.”

    He discussed how browsers were not built for gaming, and how HTML5 was primarily envisioned as a mobile platform. He revealed how DirectCanvas was created as a temporary stopgap measure, and then introduced his browser extension Mobius (available at appmobi.com/documentation)

    Through it all, we were busy evangelisin’ away on enchant.js, before, during, and after the sessions. Look how serious we were! Ahem.

    The day ended with booze galore at the official conference party, including a blue cocktail in honor of sponsor Microsoft. Hmm…where’s our enchant.js bubbly?

    Stay tuned for a peak into day 2!

  • Comments Off
  • Filed under: Event
  • enchant PRO Beta 2 + 9leap app updated!

    Greetings! Ryohei here.

    We just released enchant PRO Beta 2. Here’s the lowdown on what’s new:

    • Added collada.pro.enchant.js plugin for reading collada format 3D model data
    • Now support lighting and camera position changes for 3D drawing

    Check out the SDK download here (zip format)。You can find the source code at github.

    We’ve also updated the 9leap game app 9leap Beta using enchant PRO SDK!

    You can also check out and test play games made using SDK on the 9leap app!

  • Comments Off
  • Filed under: Release Note
  • Greetings! Ryohei here.

    Check out the official enchant.js site for our just-released Reverse-Lookup Reference!

    • Development Basics
    • Reverse-Lookup Reference
      • Words of Caution
        • Basic enchant.js Template
      • The Basics (Drawigin)
        • Making/Deleting a Scene
        • Making an Image
        • Making Text
        • Making Sound
      • The Basics (Control)
        • Loading Materials
        • Processing Frames
        • Processing Touch (Click)
      • Maps
        • What are Maps?
        • Making a Map
        • Looking for Obstacles on Maps
      • Sprites
        • Moving Sprites
        • Rotating/Expanding/Contracting Sprites
        • Making Sprites Transparent
        • Using the Canvas with Sprites
        • Collision Detection and Sprites
      • Text (Label)
        • Changing Text Color, Font
        • Moving Text
        • Making Text Transparent
      • Other
        • Changing Scene Background Color
        • Changing Game fps
        • Changing Game Screen Magnification
        • Changing Scene Displayed During Loading
        • Preloading Materials

    enchant.js Reference

    Please note that the Japanese file is now called enchant-ja.js.

    If you see bugs in the source code, errors in the translation, or anything else, please drop us a line. You can use issues in github or write a comment on this blog.

  • Comments Off
  • Filed under: Announcement
  • Greetings! Fushimi of the enchant.js/enchant PRO development team here.

    We are in the process of updating enchant PRO SDK and the 9leap app based on all the feedback we’ve received since the October 21 release. Unfortunately, despite having announced a November release date for the final version, we’re still working out the kinks. With that in mind, we’ll release a β2 version (vo.6.0)  on November 1, and the formal version on December 1st.

    Our sincere apologies to fans awaiting an official release. Until December, please send us your opinions and ideas for improvements!

  • Comments Off
  • Filed under: Announcement
  • enchant.js meetup! held in Tokyo.

    21 Oct.
    Enchant.js meetup that was held in Tokyo
    This meetup came to more than 180 visitors.

  • Comments Off
  • Filed under: Report
  • Greetings! Ryohei here.

    I just got back from the Japan Android Meetup, Okinawa’s 13th Workshop, where I had the honor of presenting!

    Date and Time: 2011/10/15 13:00 to  17:00
    Members: 40 人
    Location: IT College of Okinawa (1-1-77 Higawa, Naha-shi, Okinawa)
    URL : http://groups.google.co.jp/group/android-group-okinawa

    1:00 – 2:00 Introduction
    2:00 – 2:30 Live Coding
    2:30 – 4:30 Programming Time
    4:30 – 5:00 Presentation

    那覇のまんなかを走るモノレール「ゆいレール」で会場へ
    I rode the Naha monorail “Yuirail” to the event site.

    会場はこちら!
    This way to Android!
    開発タイム
    Development time after a one-hour presentation.
    いつもより短い2時間の開発タイムなのに、ゲームが完成したひともたくさん!
    Even with only two hours, many participants were able to share a complete game!
    こちらはクマがバナナを取るゲーム
    A banana-hunting game.

    @hanachin_ submitted his finished game to 9leap. In just two hours, he made a complete, sharable game. Wow!

    Read the rest of this entry »

  • Comments Off
  • Filed under: Event
  • 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!

  • Comments Off
  • Filed under: Tutorial
  • enchant PRO Beta release

    Ubiquitous Entertainment Inc. is proud to announce the beta release of “enchant PRO” on October 21.

    “enchant PRO” is native app development environment for Android devices based on the open source HTML5 game engine “enchant.js.” In addition to enabling development of Android apps with the same ease and simplicity the made “enchant.js”  a hit following its April release, it also takes full advice of the camera, gyros, and other key features of Android devices.

    The new platform means that AR games and non-game applications which would have been difficult or impossible with just “enchant.js” are now at your fingertips. Several businesses have already announced planes for non-game releases using “enchant PRO.”

    In addition to expanding the features of “enchant.js,” “enchant PRO” will also sell business licenses for corporate users. Non-profit and personal use will also be available under a free “Community License.”

    We also have an iPhone/iPad version under development.

    Please enjoy a look at “enchant Pro” in action by downloading the “9leap” app fom the Android Market. “enchant PRO” also includes the AR marker reader technology “KART” from Koozyt, Inc, allowing anyone to easily create a program with AR markers!

    Download the SDK, document sample, and 9leap app from the official enchant PRO website.

  • 2 Comments
  • Filed under: Announcement
  • 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!

  • Comments Off
  • 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.

  • Comments Off
  • 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!

  • Comments Off
  • 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
  • enchant.js meetup! vol.1

    We’re proud to announce the first-ever meetup for enchant.js users!

    Day and Time: Friday, October 21, 7-10 p.m.
    Space Available: 40 attendees
    Location: Tokyo (Akihabara area, exact location TBA)

    We’re currently determining the exact meeting site. We’ve already had 10 applicants since making our initial announcement, so be sure to get your application in before the event fills up!

    We’ve prepared 8 short presentations of 10-15 minutes each in hopes that attendees will leave with increased knowledge of and confidence in enchant.js!

    We’re currently looking for speakers as well, so if you have something you want to talk about, feel free to fill it out on the application form or shoot an email to inbound@enchantjs.com.


    http://atnd.org/events/20675

    The official enchant.js hashtag on Twitter is #enchantjs. We haven’t made a big deal of it in the past, but please feel free to use the hashtag to find the latest news, and for feedback and support! You can see it at the right side of the blog.

    In addition, each time a study session for enchant.js, HTML5, or JavaScript is held, we’re eager to release special goodies and offer our support, so please drop us a line! We’ll already heard from several groups, and have some exciting events in the works!

  • Comments Off
  • Filed under: Event
  • We’re pleased to announce an enchant.js workshop in Okinawa, sponsored by @yamanetoshi.

    Date and Time: 2011/10/15 13:00 to  17:00
    Members: 40 人
    Location: IT College of Okinawa (1-1-77 Higawa, Naha-shi, Okinawa)
    URL : http://groups.google.co.jp/group/android-group-okinawa

    More more information and to register, please see the atnd page.

  • Comments Off
  • Filed under: Event
  • Greetings! Ryohei here.

    On the 27th I presented at the 21st HTML5, etc Study Group on “enchant.js + PRO.” Here are some some slides.

    “The HTML5, etc Study Group” is run by the html5j community. Already some 21 sessions have been held, filled to capacity each time by HTML5 enthusiasts. This time there were nearly 100 attendees.
    I picked up the latest from GREE, Mobage, Amega Pigg, Kayac, and other technology on the cutting edge. I found DeNA presentation on animation control technology particular useful. In mobile you can achieve 300ms just by loading jQuery-min.js… Apparently DeNA’s development uses the “jsDeferred” technology.
    Before presenting enchant.js, I asked, “How many of you have heard of enchant.js?” About 2/3 of the people in the room raised their hands.
    After the presentation, I received lots of feedback about ways to improve the system.
    We’re eager to hear from you anytime with your enchant.js opinions and feedback!
    Please check out the following links for more details on the event:

    A special thanks to the event organizers, participants, and especially CyberAgent, who provided the event space!

  • 2 Comments
  • Filed under: Event
  • 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