typescriptでenchant.jsのハローワールドやってみた

mizchi/enchant-with-typescript https://github.com/mizchi/enchant-with-typescript
coffeescriptで書いた時と同じく、interfaceを書いて継承してモジュール定義、という流れ

src/types/enchant.d.tsが定義ファイル。プロパティを網羅できてないが、typescriptでenchant.jsやりたい人には便利だと思う。

感想

HaXeでやったときよりすんなりいった印象。

ただ、割とどうしようもない部分でへんなことしないといけなくて、例えば

interface Window {
  enchant: Function;
}
window.enchant();

enchantをmoduleにしてしまったせいで、関数としてcallできない事に気づいた。
かわりにwindow:Window のenchantを借りてきてFunction型にして初期化関数の呼び出しをしている。
型のinterface書くの、脳みそ止めてもできるのでアニメみながらやるといいと思う。

上手く説明できないのでここにmain.ts置いておく。

///<reference path='types/enchant.d.ts'/>
declare var enchant : enchant;

// In this context, enchant is module so it is not callable.
// Use window.enchant instead of 'enchant'.
interface Window {
  enchant: Function;
}
window.enchant();

module App {
  export class Bear extends enchant.Sprite {
    constructor(){
      super(32, 32);
      this.x = 8;
      this.y = 8;
      this.image = Game.game.assets['images/chara1.png'];

      var self = this;
      this.on('enterframe', () => self.update());
    }

    update(): void {
      var input = Game.game.input
      if (input.right) this.x += 2;
      if (input.left)  this.x -= 2;
      if (input.up)    this.y -= 2;
      if (input.down)  this.y += 2;
    }
  }

  export class Game extends enchant.Game {
    public static game: Game;
    constructor(){
      super()
      Game.game = this;
      this.fps = 24;
      this.preload('images/chara1.png');
      this.onload = () => {
        var bear = new Bear()
        this.rootScene.addChild(bear);
        var game = this;
      };
    }
  }
}

window.onload = () => {
  var game =  new App.Game();
  game.start();
};