Writing videogames with titanium appcelerator

12,338 views

Published on

Creating a simple videogame is a fun way to start learning the titanium appcelerator APIs.

this talk by alessio ricco was presented at the Mobile Developer Conference WHYMCA in Milan May 20th 20011

Published in: Technology
5 Comments
8 Likes
Statistics
Notes
No Downloads
Views
Total views
12,338
On SlideShare
0
From Embeds
0
Number of Embeds
1,630
Actions
Shares
0
Downloads
135
Comments
5
Likes
8
Embeds 0
No embeds

No notes for slide

Writing videogames with titanium appcelerator

  1. 1. Developing a videogame with Titanium Appcelerator Creating a simple game is a fun way to start learning the Titanium Appcelerator APIsalessio.ricco@gmail.com
  2. 2. Appcelerator: Native DevelopmentNative developmentEasy to useMultiplatform (iOS/Android/Blackberry (very soon))JavascriptExtensible with modulesAnalyticsSocial Networks API (twitter, facebook, foursquare, yahoo)Complete native API and controls coverageFull HTML5 and CSS3 supportRich Media and Device Capabilities Supported
  3. 3. … and videogames ?GoLingo -- http://www.golingoapp.com/SwarmSG -- http://swarmsg.com/NeighborSmash -- http://enbo.pl/titanium/neighbour-smash.zipBustinOut -- http://boydlee.com/assets/bustinout/app.js… and …TwinsMatcher (http://itunes.apple.com/us/app/twinsmatcher/id429890747?mt=8)
  4. 4. TwinsMatcher: FeaturesBuilt 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)
  5. 5. TwinsMatcher: Game Rules250 seconds to clear a12x9 board full of iconstouch an icon and its twinto make them disappearthe icons must be adjacent orseparated by empty spacesshaking your device will shuffle the icons
  6. 6. TwinsMatcher: the flow
  7. 7. TwinsMatcher: the files structure
  8. 8. TwinsMatcher: App.jsapp.js is your applications root execution contextapp.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
  9. 9. TwinsMatcher: Win,View & ...The following are the major design componentsin Titanium:Windows host one or more ViewsViews draw content on the screenWidgets are special types of views that perform specific actions like buttonsvar win = Ti.UI.createWindow();var view = Ti.UI.createImageView({ image:"myimage.png", width:24, height:24});win.add(view);win.open();
  10. 10. Appcelerator: factory patternTitaniums UI APIs have a factory-style interfaceTi.UI.createView({ height:400, backgroundColor:red});When creating your own functions, you might want to take this convention one step further by adding theTitanium base class to the end of your component type. So you might have function names that followthe convention "create"+business view type+Titanium base component:e.g. : createMainApplicationWindow
  11. 11. TwinsMatcher: Game.jsThe gameplay is managed handling 5 events:on window load: initialize game structures and componentson window focus: arrange the icons, paint the board, start the gameon windows click: manage icons selectionon shake event: shuffle the iconstimer: check if the available time expired, if so the game ends
  12. 12. TwinsMatcher: ingredientsA 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 leaksA quick shuffle algorithmA quick path finder algorithmA great graphic designer !
  13. 13. TwinsMatcher: how to drawno 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)...
  14. 14. TwinsMatcher: how to drawImageView 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;}
  15. 15. TwinsMatcher: how to draw// Create SCORE labelvar 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 boardvBoard.add( lblScore );
  16. 16. TwinsMatcher: how to play sounds1) Initializing sound in app.js2) Playing background music3) Assign the music array as window parameter4) Play/Stop sound when its needed
  17. 17. TwinsMatcher: init sounds// sound files arrayvar 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 loopsoundmusic[SOUND_MUSIC].setVolume(MUSIC_VOLUME);soundmusic[SOUND_MUSIC].play();soundmusic[SOUND_MUSIC].looping = true;
  18. 18. TwinsMatcher: stop musicfunction stopMusic (i) { // get current window var win = Titanium.UI.currentWindow; if (win == null) {return;}; // sound array sound = win.sound; // stop music sound[i].stop();}
  19. 19. TwinsMatcher: onClickwindow click event is used to find the icon coordinates on the boardwin.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)...
  20. 20. TwinsMatcher: onClickfunction onIconsSelected( ) {…// verify the clicked icons: are they of the same kind?if(( sameKindOfIcon( r0,c0,r1,c1 )) {// find a path between the iconsvar path = pathFinder( r0, c0, r1, c1 );if( path != null ) { // GREAT ! onShowPath( path, r0, c0 ); // update score, remove the icons ...} else {lblTips.text = "Cant find a path";playSound( SOUND_ONPATHNOTFOUND );}} else ...
  21. 21. TwinsMatcher: Animationfunction onShowPath( path, r0, c0 ) {playSound( SOUND_ONPATH );// show the path between twinsfor( 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 timeoutsetTimeout(function() { for( var o in path ) { var icon = icons [ path [ o ].r ] [ path [ o ].c ]; removeIcon( icon ); } onCheckEndGame( );},100);}
  22. 22. TwinsMatcher: database initSQLite3 is version 3 of SQLites SQL-based relational database management system (RDMS), chosen by Apple, Google and RIM to provide local data storage on their mobile devices.App.jsvar 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)););}
  23. 23. TwinsMatcher: db.executefunction 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;}
  24. 24. TwinsMatcher: iAdfunction 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 );}
  25. 25. TwinsMatcher: Custom FontsExample in settings.jsvar 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>
  26. 26. TwinsMatcher: Twitteroauth-adapter by David RiccitelliProvides 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 );
  27. 27. TwinsMatcher: Facebookvar btFacebook = createButton(TOP,"facebookScore");// open feed publish dialog if clickedbtFacebook.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 );}
  28. 28. TwinsMatcher: Facebook login var fbButton = Titanium.Facebook. createLoginButton({ style:wide, top:TOP, height:30, width:300 }); win.add(fbButton);
  29. 29. Thank you !TwinsMatcher is available on AppStorehttp://itunes.apple.com/us/app/twinsmatcher/id429890747?mt=8concept by alessio riccodeveloped by emanuele fusco and alessio riccoinfo and contacts: alessio.ricco@gmail.com

×