Docstoc

writing-videogames-with-titanium-appcelerator

Document Sample
writing-videogames-with-titanium-appcelerator Powered By Docstoc
					      Developing a videogame with
         Titanium Appcelerator
  Creating a simple game is a fun way to start learning the Titanium
                           Appcelerator APIs




alessio.ricco@gmail.com
Appcelerator:              Native Development

Native development
Easy to use
Multiplatform (iOS/Android/Blackberry (very soon))
Javascript
Extensible with modules
Analytics
Social Networks API (twitter, facebook, foursquare, yahoo)
Complete native API and controls coverage
Full HTML5 and CSS3 support
Rich Media and Device Capabilities Supported
… and videogames ?
GoLingo -- http://www.golingoapp.com/
SwarmSG -- http://swarmsg.com/
NeighborSmash -- http://enbo.pl/titanium/neighbour-smash.zip
BustinOut -- http://boydlee.com/assets/bustinout/app.js

… and …


TwinsMatcher
  (http://itunes.apple.com/us/app/twinsmatcher/id429890747?mt=8)
TwinsMatcher: Features
Built with Titanium Appcelerator in 2 weeks.
main features:

-   handmade ugly graphics
-   timers
-   custom fonts
-   facebook and twitter integration
-   music and sound effects
-   simple animations
-   iAd
-   database (sqlite)
-   gestures (shake)
TwinsMatcher: Game Rules
250 seconds to clear a
12x9 board full of icons

touch an icon and its twin
to make them disappear

the icons must be adjacent or
separated by empty spaces

shaking your device will shuffle the icons
TwinsMatcher: the flow
TwinsMatcher: the files structure
TwinsMatcher: App.js
app.js is your application's root execution context
app.js serves as the entry point for your application.
app.js is the best candidate for init code

//   DEFINE CONST AND GLOBAL VARS
//   INIT DATABASE
//   INIT MUSIC FILES
//   INIT APPLICATION WINDOWS
//   DEFINE APPLICATION EVENTS
//   SHOW THE MAIN WINDOW
TwinsMatcher: Win,View & ...
The following are the major design components
in Titanium:
Windows     host one or more Views
Views       draw content on the screen
Widgets     are special types of views
            that perform specific actions
            like buttons
var win = Ti.UI.createWindow();
var view = Ti.UI.createImageView({
  image:"myimage.png",
  width:24,
  height:24
});
win.add(view);
win.open();
Appcelerator: factory pattern
Titanium's UI APIs have a factory-style interface
Ti.UI.createView({
    height:400,
    backgroundColor:'red'
});




When creating your own functions, you might want to take this convention one step further by adding the
Titanium 'base' class to the end of your component type. So you might have function names that follow
the convention "create"+business view type+Titanium base component:

e.g. : createMainApplicationWindow
TwinsMatcher: Game.js
The gameplay is managed handling 5 events:

on window load: initialize game structures and components

on window focus: arrange the icons, paint the board, start the game

on windows click: manage icons selection

on shake event: shuffle the icons

timer: check if the available time expired, if so the game ends
TwinsMatcher: ingredients
A View containing the icons (vBoard)
A 12x9 matrix of game icons (preloaded)
A 12x9 matrix of selection icons (preloaded)

preloaded sounds and icons to prevent
   memory leaks

A quick shuffle algorithm
A quick path finder algorithm

A great graphic designer !
TwinsMatcher: how to draw
no need to draw, everything is done “programmatically”


function initIcons() {
   icons = new Array( MAXROW );
   for( var r = 0; r < MAXROW; r ++ ) {
      icons [ r ] = new Array( MAXCOL );
      var rr = getRowPixel( r );
      for( var c = 0; c < MAXCOL; c ++ ) {
         var cc = getColPixel( c );
         icons [ r ][ c ] = buildIcon( "path", rr, cc );
         vBoard.add( icons [ r ][ c ] );// add icon to view
...(to be continued)...
TwinsMatcher: how to draw
ImageView Factory call example (board icons)


function buildIcon( url, top, left ) {
    var icon = Titanium.UI.createImageView( {
                    image : getIcon( url ),
                    width : iconW,
                    height : iconH,             c	
  
                    top : top,
                    left : left,
                    visible:false
             } );
    return icon;
}
TwinsMatcher: how to draw
// Create SCORE label
var lblScore = Titanium.UI.createLabel( {
   text : '0',
   color : textColor,
   font: labelFontBig,
   top : 2,
   height : labelFontBig.fontSize + 8,
   left : LEFTPOS,
    width : WIDTHPOS
} );
// Add SCORE label to the board
vBoard.add( lblScore );
TwinsMatcher: how to play sounds
1) Initializing sound in app.js

2) Playing background music

3) Assign the music array as window parameter

4) Play/Stop sound when it's needed
TwinsMatcher: init sounds
// sound files array
var soundfiles=["sound/click.mp3", …,"sound/bgmusic.mp3"];
// build sound object (preload at inizialization)
var soundmusic = [ ];
for( var sf in soundfiles ) {
    soundmusic.push(
    Ti.Media.createSound( {
    sound :       Titanium.Filesystem.getFile
    ( Titanium.Filesystem.resourcesDirectory, soundfiles [ sf ] ),
    preload : true } ) );
}
// play background music in loop
soundmusic[SOUND_MUSIC].setVolume(MUSIC_VOLUME);
soundmusic[SOUND_MUSIC].play();
soundmusic[SOUND_MUSIC].looping = true;
TwinsMatcher: stop music
function stopMusic (i) {
     // get current window
     var win = Titanium.UI.currentWindow;
     if (win == null) {return;};
     // sound array
     sound = win.sound;
     // stop music
     sound[i].stop();
}
TwinsMatcher: onClick
window click event is used to find the icon coordinates on the board


win.addEventListener( “click”, function( e ) {
   ...
   var x = e.source.left + 5; // click event property
   var y = e.source.top + 5;      // click event property
   var r = parseInt( getRow( y ) , 10 ); // board coordinate
   var c = parseInt( getCol( x ) , 10 ); // board coordinate
   if( board [ r ][ c ]== null ) { return; } // no icons
   if( choiceIndex == - 1 ) { // no other icon selected
         playSound( SOUND_ONCLICK1 ); // click sound
         doSelectIcon( r, c );   // show the icon as “selected”
         return;
   }
   ...(to be continued)...
TwinsMatcher: onClick
function onIconsSelected( ) {
…
// verify the clicked icons: are they of the same kind?
if(( sameKindOfIcon( r0,c0,r1,c1 )) {
// find a path between the icons
var path = pathFinder( r0, c0, r1, c1 );
if( path != null ) {
    // GREAT !
    onShowPath( path, r0, c0 );
    // update score, remove the icons
    ...
} else {
lblTips.text = "Can't find a path";
playSound( SOUND_ONPATHNOTFOUND );
}
} else ...
TwinsMatcher: Animation
function onShowPath( path, r0, c0 ) {
playSound( SOUND_ONPATH );
// show the path between twins
for( var o in path ) {
      var icon = icons [ path [ o ].r ]
                         [ path [ o ].c ];
      icon.image = getIcon(board [ r0 ][ c0 ] );
      icon.visible = true;};
// remove icons on timeout
setTimeout(function() {
    for( var o in path ) {
          var icon = icons [ path [ o ].r ]
                             [ path [ o ].c ];
          removeIcon( icon );    }
    onCheckEndGame( );
},100);
}
TwinsMatcher: database init
SQLite3 is version 3 of SQLite's SQL-based relational database management system
    (RDMS), chosen by Apple, Google and RIM to provide local data storage on their
    mobile devices.


App.js
var db = Titanium.Database.open( 'twinsmatcher.db3' );
if (db == null) {
Ti.API.info("cannot open db");
} else {
var result = db.execute('CREATE TABLE IF NOT EXISTS [score] ( id
   INTEGER PRIMARY KEY AUTOINCREMENT, [created] TIMESTAMP DEFAULT
   (0), [level] BIGINT DEFAULT (0), [score] BIGINT DEFAULT
   (0));');
}
TwinsMatcher: db.execute
function setScore(level, score) {
    var result = db.execute( "insert into score(level,score,created ) values
    ( ?,?,? )", level,score, fetch_unix_timestamp( ));
}


function getScore(level) {
    ...
    rows = db.execute( "select    max(score) as maxscore from score where
    level=?", level );
    if( rows.isValidRow( )) {    score= rows.field( 0 ) }
    ...
    rows.close( );
    ...
    return score;
}
TwinsMatcher: iAd
function iAdWindow(win) {
     iads = Ti.UI.iOS.createAdView({
      width : 'auto',
      height : 'auto',
      bottom : - 100,
      zindex : 100,
      borderColor : '#fff',
      backgroundColor : '#fff'});
     iads.addEventListener( 'load', function( ) {
       var t1 = Titanium.UI.createAnimation( { bottom : 0, duration : 750 } );
       iads.animate( t1 );
     } );
     iads.addEventListener( 'error', function() {
        win.remove(iads);
     } );
    win.add( iads );
}
TwinsMatcher: Custom Fonts
Example in settings.js
var musicSwitchLabel = Titanium.UI.createLabel( {
      text: “background music”
      font : { fontFamily : “customfont.otf”,
                 fontSize : 28 };,
...
} );
win.add( musicSwitchLabel );


info.plist must be customized and placed in the project root
<key>UIAppFonts</key>
<array>
<string>customfont.otf</string>
</array>
TwinsMatcher: Twitter
oauth-adapter by David Riccitelli
Provides a JavaScript library for use within Appcelerator Titanium
   mobile (iPhone, iPad, ...) projects in order to establish OAuth
   protocol-based communications to services such as Twitter.

http://code.google.com/p/oauth-adapter/

var btTweeter = createButton(TOP,"tweetScore");
btTweeter.addEventListener('click', function(){
   var tweet = makeTwitterStatus( shareMessage(), '' ) //message
   twitter( tweet );
});
win.add( btTweeter );
TwinsMatcher: Facebook
var btFacebook = createButton(TOP,"facebookScore");
// open feed publish dialog if clicked
btFacebook.addEventListener('click', function()
{
var data = {
      link: APPSHORTURL,        // link to appStore
      name: customer_name,
      message: shareMessage(), // message to publish
      caption: customer_name,
      picture: app_logo,        // app icon url
      description: APP_DESC
};
Titanium.Facebook.dialog("feed", data, FBshowRequestResult);
});
win.add( btFacebook );
}
TwinsMatcher: Facebook login

           var fbButton =
           Titanium.Facebook.
             createLoginButton({
               style:'wide',
               top:TOP,
               height:30,
               width:300
           });
           win.add(fbButton);
Thank you !
TwinsMatcher is available on AppStore
http://itunes.apple.com/us/app/twinsmatcher/id429890747?mt=8



concept by alessio ricco

developed by emanuele fusco and alessio ricco




info and contacts: alessio.ricco@gmail.com

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:30
posted:2/18/2012
language:English
pages:29