Papaya Social Game Engine SDK Manual
Papaya Social Game Engine SDK Manual
Papaya Social Game Engine SDK Manual
Social Game Engine SDK Manual ................................................................................................ 1 Version 1.5 (Modified 4 17th 2012) .................................................................................................. 1
Chapter1: Welcome ................................................................................................................................ 4 Chapter 2: Introduction ........................................................................................................................... 5 Fundamentals .................................................................................................................................................. 5 Built-in Virality and Social Features ................................................................................................................. 6 Monetization ................................................................................................................................................... 6 Chapter 3: Quick Start on Android ........................................................................................................... 7 Step 1: Set-up Environment............................................................................................................................. 7 Step 2: Drawing an Empty Screen ................................................................................................................... 7 Step 3: Drawing a Picture ................................................................................................................................ 8 Step 4: Drawing a Label ................................................................................................................................... 9 Step 5: Adding Another Picture and Moving It.............................................................................................. 10 Step 6: Event Handler .................................................................................................................................... 11 Step 7: Multiple Files ..................................................................................................................................... 12 Step 8: Alerts ................................................................................................................................................. 13 Step 9: Quitting an Application...................................................................................................................... 14 Chapter 4: Development Tools ................................................................................................................16 For Android .................................................................................................................................................... 16 For iOS ........................................................................................................................................................... 18 Chapter 5: game.config ..........................................................................................................................26 Chapter 6: Graphics System ....................................................................................................................28 Coordinates ................................................................................................................................................... 28 Node .............................................................................................................................................................. 28 Node Coordinates and World Coordinates.................................................................................................... 29 Scene ............................................................................................................................................................. 29 Sprite ............................................................................................................................................................. 29 Mask .............................................................................................................................................................. 29 Label .............................................................................................................................................................. 30 Action ............................................................................................................................................................ 30 Event .............................................................................................................................................................. 31 Views ............................................................................................................................................................. 31 Fonts .............................................................................................................................................................. 33 Chapter7: Menu .....................................................................................................................................34 Chapter 8: Media ...................................................................................................................................35 Creating Audio ............................................................................................................................................... 35 Createing Video ............................................................................................................................................. 35 Sound ............................................................................................................................................................. 36 Chapter 9: Files ......................................................................................................................................37 Chapter 10: Database .............................................................................................................................38 Chapter 11: Social ..................................................................................................................................39 Basics ............................................................................................................................................................. 39 Query Friends List .......................................................................................................................................... 39 Showing Avatar Image ................................................................................................................................... 39 Query Papayas (Virtual Currency) ................................................................................................................. 40 Friend Requests ............................................................................................................................................. 40 Using Leaderboards ....................................................................................................................................... 40 Updating a Players Newsfeed ....................................................................................................................... 40
Papaya Game Engine SDK Manual 2
Sending Notifications..................................................................................................................................... 41 Connection with Facebook ............................................................................................................................ 41 Other Social APIs ........................................................................................................................................... 42 Chapter 12: Selling Virtual Goods ...........................................................................................................43 Setting-up Your Game for Virtual Goods ....................................................................................................... 43 Integrating Virtual Currency into Your Game ................................................................................................ 43 Server-Server Callback ................................................................................................................................... 45 Difference of Revenue Share on Android and iOS ......................................................................................... 46 Chapter 13: Sensors ...............................................................................................................................47 Sensors Basics ................................................................................................................................................ 47 Sensor Detection ........................................................................................................................................... 47 Chapter 14: HTTP Server ........................................................................................................................48 Connecting to Server ..................................................................................................................................... 48 Downloading Pictures.................................................................................................................................... 48 Downloading Files ......................................................................................................................................... 48 Using POST..................................................................................................................................................... 49 Updating Game Script Automatically ............................................................................................................ 49 Chapter 15: Sprite Sheets .......................................................................................................................50 Step 1:Generate the large picture and the plist file ...................................................................................... 50 Step 2: Write code to draw texture ............................................................................................................... 50 Chapter 16: Icons and Welcome Screen ..................................................................................................52 Customizing Pictures and Icons ..................................................................................................................... 52 Live Wallpaper Icon (Android only) ............................................................................................................... 52 Chapter 17: Physics Engine .....................................................................................................................55 Setup.............................................................................................................................................................. 55 Start ............................................................................................................................................................... 55 Units .............................................................................................................................................................. 55 Gravity ........................................................................................................................................................... 55 Configuration ................................................................................................................................................. 56 Collision ......................................................................................................................................................... 56 Bodies ............................................................................................................................................................ 56 Joints .............................................................................................................................................................. 59 Chapter 18: Particle System ....................................................................................................................62 Chapter 18: Offers ..................................................................................................................................64 Chapter 19: PapayaAS ............................................................................................................................65 PapayaAS Basics............................................................................................................................................. 65 Data Type ....................................................................................................................................................... 65 Variable Types................................................................................................................................................ 66 Operators ....................................................................................................................................................... 66 Control Blocks ................................................................................................................................................ 66 Function ......................................................................................................................................................... 66 Class and Interface......................................................................................................................................... 67 Namespace, Prototype .................................................................................................................................. 67 Compilation Error .......................................................................................................................................... 67 Program Entry Point ...................................................................................................................................... 68 Chapter 20: Debugging ...........................................................................................................................69 Example 1: Null Pointer ................................................................................................................................. 69 Example 2: Array Index .................................................................................................................................. 70
Papaya Game Engine SDK Manual 3
Chapter1: Welcome
Thank you for choosing the Social Game Engine! The Social Game Engine is the first cross-compatible game engine of its kind on Android and iOS, and one of the fastest script based engines available. With the Social Game Engine, Papaya introduces a new-level of easy-to-use game creation packed with built-in features to effectively socialize and monetize your games. Weve already used the Social Game Engine to develop a number of commercially successful games at Papaya, and were sure that the Social Game Engine is the best tool for creating mobile social games thats available. The Social Game Engine is also 100% free. Whether youre developing for iOS or Android, we hope you enjoy using the Social Game Engine and look forward to your next smash hit! Sincerely, The PapayaMobile Team
Chapter 2: Introduction
Fundamentals
The Social Game Engine SDK contains compilers and a virtual machine, which allows you to program with a script language other than Java or C. Programming on Android with Java, C, or JNI can be rather tedious so weve built our engine to make programming much easier. Our engine doesnt require you to download the Android SDK or to install eclipse. If you want to get started right away, you can jump straight to Chapter 2. With the Social Game Engine, programs are written in a language very similar to ActionScript called PapayaAS. Since ActionScript is similar to Java, youll find it is very easy to familiarize yourself with the Social Game Engines language. The syntax is similar to ActionScript, but weve actually made it even more simple and easy-to-use. The Social Game Engine has its own compilers, and to program you will need to compile your ActionScript files using our compiler. After compiling, the binary files you create can be executed on our game engine. One of the major advantages of the Papaya Game Engine is its performance. The graphic APIs are implemented with C and OpenGL to give you the best performance without needing to learn the Android SDK NDK. The structure of the Papaya Game Engine is pictured below:
Python
Actionscript
bytecode
Engine
Monetization
Virtual Currency on Android
The Social Game Engine has a virtual currency system that allows you to sell virtual goods in your games and start making money from the word go. For every virtual good sold in your game, you earn a share of the revenue. Please refer to start_payment() and purchase_papayas() in the API Reference for more information. PapayaMobile also has a number of billing channels already set-up and ready for immediate use. Our billing channels help you monetize through in-game virtual goods purchases without worrying about managing the complicated billing processes because Papaya does it for you. Additionally, when your users purchase Papayas own virtual goods, e.g. Avatar Items used on the Papaya SNS, you will receive a share of the revenue.
d. Run install.bat first to download Android SDK. Then you will see this:
e. The folder android-sdk-windows contains the Android SDK. Note that Android SDK 2.2 is used. If you already downloaded another version of the Android SDK, simply copy it here.
#SCREEN_ORIENTATION_USER: 2 #SCREEN_ORIENTATION_BEHIND: 3 orientation=0 package_name=com.papaya.firstgame app_name=My first game script_name is the file to be compiled. app_name is the name shown on your phone. c. Compile: compile.bat tutorial; d. Run: run.bat tutorial.
var p = getscene();This is a global Scene created automatically. p points to the global Scene, ready to draw other Nodes.
p.addsprite() creates a new Sprite and adds it to the global Scene. Any Node to be drawn must be added to the global Scene or its parent must have already been added. x.size(w,h) sets xs size to w,h. screensize() returns the size of the screen. Without size(screensize()), the picture may be displayed smaller than the screen.
Note: By default, a node is drawn at 0,0 in the upper-left corner of the screen.
Papaya Game Engine SDK Manual 9
The Social Game Engine provides a rich set of Actions, including a Wave effect, Shaking effect and more. Refer to the API document for the full set of Actions.
If you run the above code you will see the picture blinks 10 times for 3 seconds once you touch it.
There are multiple Events you can handle. Refer to setevent () function in API doc for more details.
t2.addaction(repeat(moveby(4000,-600,0),imoveto(600,150))); function ff(x){ x.addaction(blink(3000,10)); } t2.setevent(EVENT_TOUCH,ff); If you want to add more files, they must be put in a folder and imported (You cannot import a single file). import label.label says import label.as inside label folder. We do not require a file to use the same name as the main class in it. Multiple classes within one file are allowed. Run it and this is the result:
Step 8: Alerts
In some cases you might want to display a pop-up dialog and give players the option to select from a number of choices. The following example will create a simple yes or no dialog. Modify the tutorial.as: import label.label; var p = getscene(); var t =p.addsprite("background.png").size(screensize()); p.addlabel("Hello, this is papaya engine","Arial",25); function hyes(x){ trace("alert yes"); } function hno(x){ trace("alert no"); } function hcancel(x){ trace("alert cancel"); } function halert(x){
Papaya Game Engine SDK Manual 13
c_alert(0,"This is an alert",0,"yes",hyes,"no",hno,"cancel",hcancel); trace("this is alert"); } var l = p.addlabel("click me to alert","Arial",25).pos(0,30); l.setevent(EVENT_TOUCH,halert); Run it and click the Label. This time a pop up dialog will appear instead of a drawing of a fish. You can tap yes, no, cancel or press the back key to close it. trace() function prints things to the screen and to the Android log. You can see the Android log in eclipse logcat.
hyes(), hno()and hcancel() are callbacks triggered when the button in the dialog is clicked. halert() is an Event handler as seen in Step5.
} var l = p.addlabel("click me to alert","Arial",25).pos(0,30); l.setevent(EVENT_TOUCH,halert); Run it and you will see that the yes button has become a quit button. When clicked, quitgame()is executed.
Now when you tap quit you will exit the game.
For Android
After you extract the Social Game Engine package, you will find the compile.bat, create.bat, http_server.bat, install.bat andrun.bat.
Installation
Run install.bat. and it will do the following: 1. Check whether the folder named android_sdk_ <platform>exists. If it doesnt exist, it will check whether the zip archive named android_sdk_ r07-<platform>.zip(.tgz for linux) exists. If this exists, it will be unzipped, and the zip archive deleted. Otherwise the zip archive will be downloaded and unpacked. 2. Check whether the folder named android-8 exists under the folder Android SDK. If it doesnt exist, it checks whether the zip archive named android-2.2_r02-<platform>.zip exists. If this exists, the zip archive will be unzipped, and then the archive deleted. Otherwise the zip archive will be downloaded and unpacked. Important Note: Before running, JDK must be installed correctly and added to your path on your computer. Your computer needs to be able to download files from the internet, otherwise the installation will not be executed.
Compile
compile.bat project-name [release] "release" indicates that the release version of the project will be compiled. If this isnt specified, a debug version will be compiled. The difference between release and debug is that the apk file of the release version is signed with a private key and you need to input the password for the key. Please remember the password.
Run
run.bat project-name The table below lists all of the supported run commands and explains their usage. Command project-name [release] [emulator-name] Description Runs a project. project-name indicates which project you want to run. "release" indicates that the release version of the project that will be run. If it isnt specified, a debug version will be run.
Papaya Game Engine SDK Manual 16
emulator-name means the name of the emulator on which you want to run the project. -avds -devices -targets -delete emulator-name -create emulator-name [skin [target [path [size]]]] Lists all available emulators Lists all connected devices Lists all available Android SDK's Deletes an emulator Creates an emulator The skin to use for this emulator, identified by name or dimensions. It is either <name> or <width>x<height> Target ID of the system image to use with the new emulator. Path to the location at which to create the directory for this emulator's files. The size of a new SD card image to create for this emulator. -log [emulator-name] View and follow the contents of the log buffers of specified device
Create
Run create.bat project-name. Then follow the instructions to create a new project.
HTTP Server
Run http_server.bat project-name It runs a local http server from where you can request images in your script(*.py or *.as) of a specified project. The root directory of the server is the directory of your specified project. Assuming your project is called tutorial the root directory of the server is /projects/tutorial/. Chapter 14 has an example using HTTP servers.
Syntax Highlight
For Ultraedit: Open your default wordfile. You can find your default wordfile by going to Advanced> Configuration > Editor Display > Syntax Highlighting A wordfile for Python called python.uew is required. You can find this easily by performing a search on Google. As of UltraEdit v15.00 or later, you can simply copy python.uew to the wordfile directory. Otherwise, after you open the wordfile in UltraEdit, copy the entire contents of the python.uew then go back to the default wordfile, which was already opened in UltraEdit. Then paste the contents of the clipboard (the python.uew wordfile) at the end of the default wordfile.
Papaya Game Engine SDK Manual 17
Note: Please make sure that the wordfile you pasted to the default wordfile does not have a duplicate language number. The language is specified by a /Ln where n has a value of 1 to 20. This is at the beginning of the line. The new highlighting language will not be available until you have restarted the application. Once you have restarted, the new highlighting language should be available in View > View As submenu. For Vim: 1. Navigate to $vim directory. 2. To switch highlighting on, put the ":syntax enable"command in your |vimrc| file. 3. Edit filetype.vim. Search *.as and delete it, using au BufNewFile,BufRead *.py,*.pyw, *.as setf python replace au BufNewFile,BufRead *.py,*.pyw setf python 4. Copy python.vim into syntax directory
For iOS
The Social Game Engine SDK for iOS is distributed as a compiling tool, several header files, two library files for both simulator and device, and one resource bundle file. Assume that the downloaded SDK package is extracted to PapayaGameSDK/ folder.
Step 2: Add Social Game Engine files into your Xcode project
a. Open finder and navigate to PapayaGameSDK/ folder b. Select PapayaGameSDK/ folder in finder, and drag it into the project navigator of Xcode
c. Add your bundle file generated by compile.sh. In this example, the bundle file is tutorial.bundle. Drag it into the project.
compile.sh is similar to compile.bat for Android. The project folder is exactly the same as in Android. If you have a project folder projects/tutorial for Android, you may make the same project folder on Mac. Run sh compile.sh --ios tutorial and then the tutorial.bundle will be generated. tutorial.bundle contains game script, assets, and game.config: all things specific to the game. Note: icons folder used in the Android project folder is not supported. Please create icons in the Xcode project.
b. Locate the option Other linker flags, double click the row, and then add -ObjC and -lstdc++ in the pop up dialog:
c. After clicking Done, the Other Linker Flags will be the same as below:
b. Click+ button and add eight more iOS dynamical frameworks: OpenGLES.framework,QuartzCore.framework,AVFoundation.framework, OpenAL.framework,AudioToolbox.framework,StoreKit.framework, libsqlite3.dylib and libz.dylib
b. Add the following lines of code to application:didFinishLaunchingWithOptions: [PapayaGameEngine initWithBundleName:@"tutorial.bundle" sandbox:NO]; Note: replace tutorial.bundle with your bundle file name.
Chapter 5: game.config
In each project folder such as projects\tutorial, there must be a game.config file. Here is an example: script_name=sx.as base_url=http://192.168.1.22:8080/papaya/ social_key=54SO2c8ZwFLINBtn offer_key=cpIqhELQdsykjqcp orientation=0 package_name=com.papaya.spritesheet_xml app_name=Spritesheet_xml tab_name= Spritesheet_xml social_game=1 force_update=1 error_if_update_fail=1 version_code=1 version_name=1.0 wallpaper_enable=1 wallpaper_desc=show spritesheet wallpaper_name=spritesheet region=China install_location=0 skip_reg=0 source_name=abc custom_value =defg script_name: the main file of your source code. There is only one main file. Other files used are imported into the main file. base_url: the url to your own HTTP server. Details are in Chapter 14 HTTP Server. social_key: Each app has a unique social key to distinguish which one is generating revenue. Details are in Chapter 12: Selling Virtual Goods. orientation: 0 means landscape, 1 means portrait. package_name: the package name of your app. app_name: the app name shown on phone screen. tab_name: the String shown on the top of the entrance page. social_game: 0 means a network is not required; players can enter the game without an internet connection. 1 means players cannot enter game without an internet connection. force_update: 1 means force downloading the latest game script before entering game. Your game codes are compiled into a script, a binary file. If you put the script in the root folder of your HTTP server, it is automatically downloaded before someone enters the game. Please pay attention to two important things:
Papaya Game Engine SDK Manual 26
First, if force_update is 1, players will wait for the download to complete. Second, if force_update is 0, players can enter immediately with the old script, but the new script is still downloaded automatically so the next time the user enters, the new script will be used. More details are available in Chapter 14: HTTP Server-updating game script automatically. error_if_update_fail Used together with force_update. If the update is forced but failed due to the network, error_if_update_fail==1 prevents the player from entering the game. version_code: the version number required by Android Market. Each time a new version of the game is submitted, this version number must increase by 1. version_name: also required by Android Market. wallpaper_enabled: 1 means the games scene can be set as the phones wallpaper. If this is 1, you need also set the following 2 options. wallpaper_desc: the description of the wallpaper. You will see it in your phones wallpaper settings (Go to desktop and click settings). wallpaper_name: the name of the wallpaper, also shown in the phones wallpaper settings. region: If this is China, Papaya servers in China are connected; otherwise servers in the US are connected. Note that if you use the China servers, you must also get the social_key,offer_key from our Chinese website, http://cn.papayamobile.com/offer/apps. install_location: 1 means storing the App in the external SD card, 0 otherwise skip_reg: 1 means skip registration, then you can test it without the internet source_name: used to differentiate multiple sources of the App. Can be got by sysinfo(INFO_SOURCE_NAME) custom_value: used for different versions of the App. Can be got by sysinfo(INFO_CUSTOM_VALUE)
y The z axis is used for 3D effects, but objects cannot be drawn at arbitrary z coordinates. You can only specify object order along the z axis. The maximum of x or y is an integer equal to the pixels on the screen, which depends on the screen size of the end user device. v_root().size() can get the width and height of the screen.
Node
Everything rendered with OpenGL must be a Node. node() function returns a new Node. A Node can be the parent of other nodes. Any change in size, position, or color applies to every child. For example, if a is the parent of b and c and we ask a to move then b and c will move together with a. Node parent
Node child
Node child
Node child
Node child
Node child
Node child
Node child
Scene
Scene is used in rendering the background for an app. var p = getscene() will return a global Scene for OpenGL rendering. Then you can add other nodes to the Scene. Currently, only one Scene can exist.
Sprite
Sprite is the object to be rendered. var t = p.addsprite("111.png",ARGB_8888) creates a Sprite with a picture as the texture. Texture can be changed later. t.texture(222.png); Or t.addaction(itexture(222.png);); Some arguments can be used in addsprite() and texture. If ALPHA_TOUCH is given, the transparent part of the Sprite will not trigger a touch Event. var t = p.addsprite("111.png", ALPHA_TOUCH);
Papaya Game Engine SDK Manual 29
SVG
SVG can also be drawn directly. svg2bitmap(c_res_bytes(1.svg), ARGB_8888) c_res_bytes() gets an Array representation of the picture; svg2bitmap() uses the Array to draw.
Mask
Mask is the object to mask a sprite to constrain drawing area. var m = mask ("111.png") creates a Mask with a picture as the texture. var s = sprite ("target.png") s.setmask(m) bind a Mask to a Sprite
Notes, you must provide a picture which alpha value has only two values ( 0 or 1). The mask would let the target sprite draw where the mask alpha value equals 1 and not draw where 0. A mask is same with sprite but it cannot work without binding to a sprite.
Label
Label holds the text to be rendered. p.addlabel("Hello","Arial",30) shows a word with the font type and size.
Action
Action specifies the movement or transformation an object is going to take. t.addaction(moveto(1000,100,100)) asks t to move to position (100,100) on the screen from its original position, and the whole actions takes 1 second. Refer to our API Reference for details. Actions can be combined together by sequence() or spawn().
Event
Event allows the Node on the screen to do something when it is touched or a key is pressed. function f(x){ x.addaction(blink(3000,10)); } t.setevent(EVENT_TOUCH,f); This says when t is touched, t blinks 10 times within 3 seconds. You can add multiple events to a Node. Refer to API Reference for how each Event occurs.
Views
Although Scene, Sprite, and Label are rendered by OpenGL, Views are not. Views are special components in an app, which include the following: 1. Input Box 2. Chat View 3. Web View 4. Papaya Web View 5. Map View (not in this version, coming soon) Input Box This is for players to enter text. var input = v_create(V_INPUT_VIEW,0,100,300,100); v_root().addview(input); The above codes add an input box to the screen. v_create() is for creating Views. The four integers say creating the View with origin (0,100), width 300 and height 100. The origin is the upper left corner. v_root() returns the default root of all Views. Any View to be shown must be added to it. input.text() returns the content in the input box. The following codes show a practical example: var scene = getscene(); scene.addlabel("get text",null,30).setevent(EVENT_TOUCH,gettext); var input = v_create(V_INPUT_VIEW,0,100,300,100); v_root().addview(input); function gettext(x){ trace(input.text()); } When the label get text is touched, the input content can be got. Note: Call getscene() before adding Views, otherwise OpenGL Scene overshadows all Views. Chat View This is for displaying a Chat window and lets multiple users enter messages. var chat = getchatview(30,80,0xffffff,0x7CCD7C,0x00CED1,0xEEC900,0xEEC900); //creates the View. 30 is fontsize; 80 is fonts alpha value; 0xffffff is color of system message; 0x7CCD7C, 0x00CED1, 0xEEC900, 0xEEC900 are colors for 4 people.
Papaya Game Engine SDK Manual 31
chat.attr(ATTR_BG_COLOR,0x191970); //sets the background color of the View (not the font color); default is black. v_root().addview(chat.pos(0,0,400,300));//draw the View export("chatmessage",chatmessage); function chatmessage(content){ trace("content:",content); chat.text(content); chat.text(content,0); chat.text(content,1); } The API export() provides a callback for the game engine. Here we provide the "chatmessage" callback, which is called after Players enter something into the Chat View. What players entered is in the content variable. Developers can then change content format or judge whether it is valid. Finally, the API chat.text() adds the newly entered message into the Chat View. To make a real application, you may need to use http_request() to send the content to your own server in "chatmessage" callback. And periodically fetch new messages from the server to add to the Chat View. Web View This is for opening a web page in games. var web = v_create(V_WEB_VIEW,0,100,800,400); v_root().addview(web); web.openurl("http://www.google.com"); The above codes create a Web View with origin (0,100), width 800, height 400, and open Googles web page. Papaya Web View This View is for Papaya SNS pages var web = v_create(V_PPY_WEB_VIEW,0,100,800,400); v_root().addview(web); web.openurl("static_home"); Available pages links are: static_home static_friends static_photos
static_newavatarnavi
static_leaderboard
static_achievement
static_mycircles
static_getpapayas
CameraView This view is created when developers need cameraview as background. V_GL_VIEW_T is transparent, while V_GL_VIEW is not. In addition, developers need addscene() instead of getscene() before drawing. var v1 = v_create(V_CAMERA_VIEW); var v2 = v_create(V_GL_VIEW_T); v_root().addview(v1); v_root().addview(v2); var scene = addscene(); scene.addsprite("background.png");
Fonts
Fonts are customizable. Put the Font file like STHUPO.TTF in folder projects\your-project\fonts\. If there isnt a fonts folder, create one. Then call addlabel() like this: node.addlabel("hello","fonts/STHUPO.TTF",80); Your Fonts will be drawn.
Chapter7: Menu
When you press the Menu key on your Android phone, the pop-up menu in the bottom of the screen appears. The Social Game Engine also has the same function. Create a Menu: varm = newmenu( String title, func action, bitmap icon, [string submenu_title1, func action1, string submenu_title2 ,action2 ...] ) titleis the text shown on the Menu. action is the function triggered when the Menu is clicked. Can be null but is not optional. icon is the icon of the Menu. submenu_title1 is the text on submenus. Submenus cannot have icons. To display: setmenu(m1,[m2,...]) sets passed in Menus to be displayed. openmenu()shows all Menus that you passed into setmenu().You may call this after closemenu() is called. To hide: closemenu()closes the Menus after you call this. menuvisible()1 means the Menus are shown.
Chapter 8: Media
Creating Audio
Normally, Audio is created like this: var a= createaudio(0.mp3); Audio files 0.mp3 must be in res folder like pictures. To play it once: a.play(); To loop it: a.play(-1); To pause: a.pause(); After being paused, the audio can be restarted by a.play(); To stop: a.stop(); After being stopped, the audio must be restarted by a.preparetoplay()and then a.play().
Createing Video
Normally, Video is created like this: var a= v_root().createvideo(0.mp4); Video files 0.mp4 must be in res folder like pictures and you must create and destroy it before you call getscene() function. Destroy video player: a.removefromparent(); To play it once: a.play(); To pause: a.pause(); After being paused, the video can be restarted by a.play(); To stop: a.stop(); After being stopped, the video can be restarted by a.play().
Sound
We also provide another suite of APIs for playing audio. You may prefer this to createaudio if: 1. The audio files are small. Memory is a big concern because Sound objects can have a maximum of 1M of memory. 2. You want a mix of the same audio file. One Sound object can create multiple Player objects. varsound = createsound(0.mp3); This creates a Sound object. It represents an audio file. Before playing it you need to: varplayer = int rate]) sound.play( [int loop , int leftVolume, int rightVolume, int priority,
This creates a Player object, specifying how this sound is to be played. Loop it if loop==1. leftVolume controls the left channel; rightVolume controls the right channel; leftVolume and rightVolume takes values 0-100. Priority specifies the priority for which sounds will be killed if a memory limit is reached. All Sound objects can have a maximum of 1M of memory. When the limit is reached, some Sound will be killed. The lower the priority is, the more likely that it will be killed. ratecontrols the speed. rate==10 means the natural speed of the audio file. Value can be 5-20. To pause: player.pause() To resume: player.resume(); To stop: player.stop(); After its stopped, it cannot be resumed. You must create a new Player by sound.play(). To set volume: player.setvolume(int leftVolume, int rightVolume); leftVolume controls the left channel; rightVolume controls the right channel; leftVolume and rightVolume takes values 0-100.
Chapter 9: Files
File APIs allow for the storing of simple records. For large records, database APIs are recommended. To open a file: If the file is in the phones storage (usually an SD card) var handler = c_file_open("test"); test is the file path. If the file is in projects\your-project\res folder var handler = c_res_file("test"); This opens the file projects\your-project\res\test. Whether you open it with c_file_open or c_res_file, you can always use the same following operations. To check whether a file exists: c_file_exist (handler) Read, write, delete, and other operations are done by c_file_op. Read: c_file_op ( C_FILE_READ
, handler
C_FILE_READ says this is a read operation. Similarly for write: c_file_op ( C_FILE_WRITE
, handler
Basics
Check whether the application is connected to Papaya Social Network: ppy_connected() Get the current users name in Papaya Social Network: ppy_username () Get the users id in Papaya Social Network: ppy_userid ()
Friend Requests
ppy_query(send_friend_request,dict,callback, param) This sends a friend request to a user. Receiver must be given in the 2nd parameter dict. You may construct dict like this: var d=dict([[uid,12345]]) meaning that the request is sent to the user with id 12345. ppy_query(list_friend_requests, null,callback,param) This gets all friend requests of the current player. Results are in the callback function callback(requestId, ret_code, response, param) response contains the results, a Dict like this: ,status:value, data:*,rid:Request.id,name:username, uid:userid} ]} You may call response.get(data)[0] to get the 1st request, and response.get(data)[0].get(uid) to get the 1st requests sender
Using Leaderboards
A Leaderboard is a page displaying the ranking of all users who play your game. People can see who plays which game by clicking on that person, building community interactivity into your game. Leaderboards are one way to increase exposure for on the Papaya Social Network and they help to add new users. ppy_setscore (newscore , board_id)
This changes the users score to newscore in the Leaderboard. board_id says which board is to be updated. Currently there is only one board for all games. Well leave this argument here to extend later. ppy_updatescore ( interval , board_id )
If interval is positive, add it to the users score; if it is negative, reduce the users score.
Newsfeeds show what a user is doing. The persons friends can see your game if you post something to his or her homepage. This is a unique way for your games to get exposed and boost their virality.
Sending Notifications
Notifications are shown in a special Notification page, and on the Home page in the Papaya SNS there is a section showing how many new Notifications there are. Sending Notifications about your game is also a useful promotional method, similar to Newsfeeds. var d = dict([[message,this is game A], [uid,1234], [url, http://xxx] ]); ppy_query(send_notification, callback, null); This code sends a Notification to User 1234.
start_payment()draws this dialog. "buy", the name of this payment shown in the dialog. It cannot be null or . "buyvirtualgoods",the description shown in the dialog. It cannot be null or . ,the icon URI, the icon shown on top of the dialog
Papaya Game Engine SDK Manual 43
1, the price. How many Papayas you charge them Paycallback, the callback when the payment is finished. param, will be passed into paycallback. paycallback must have the form: function paycallback(pid, ret, tid, receipt, param) pid , a unique id of the payment, ret , 1 if succeeds, Tid ,a unique id of this transaction, receipt, an encrypted string for certification. param, passed in from paycallback. receiptis computed by our server: receipt = md5(userid + '-' + tid + '-' + app_secret) Then your application can send the tid, userid and receipt to your own server. Your server can use the same md5 approach to check whether the payment is actually done through the Papaya Social Network server. app_secret is the app_secret shown after you register your app.
Verify User ID
You may also want to certify that the user has actually logged into the Papaya Social Network before any payment starts: var data = ppy_session(); var session_secret = data[0]; var session_receipt = data[1]; session_receiptis computed by Papaya server, session_receipt= md5(userid + '-' + session_secret + '-' + app_secret) Then your app can send userid,session_secret to your own server. Your own server can check whether the
Papaya Game Engine SDK Manual 44
Server-Server Callback
When players make a purchase in your game, the transaction is sent to the Papaya server to be authorized. After that, the Papaya server will call back to your own server with information about the transaction. This is more secure and robust than server-client callback. To use it, you need to: 1. Set up a HTTP server that responds to Papayas callback request 2. A callback url provided in Papaya developer website. http://papayamobile.com/offer/apps If you have registered your game, click into it and find Social features. You will see a Social Callback URL. If the callback url is http://callback.com/, we shall inform you every user's consumption as following: 1. For Android: Request the callback url with POST data like "tid=xxx&uid=yyy&papapas=zzz&signature=wwwww&time=vvv&name=xxx&desc=xxx&payload=xxxx", the signature is the md5 hash of "-" connected values of tid, uid, papayas and the app secret your application provided in Papaya developer website. For example, if tid is 123, uid is 456, papayas is 1000 and app secret is ABCDEFGH, the signature will be e83d745b389898171c8e60e1926982a3. In Python, you may get the signature by: import md5 signature = md5.md5('123-456-1000-ABCDEFGH').hexdigest() name, desc are the same things passed into start_payment(). payload is the param passed into start_payment(). For iOS: Only some arguments in POST data are different. "tid=xxx&uid=yyy&itemid=zzz&quantity=111&receipt_data=wwwww&sandboxCallback=xxx&time=vvv itemid is the ID of this purchase item on the App store; receipt_data is a receipt from Apple. sandboxCallback is also from Apple. You may use receipt_data and sandboxCallback to verify the payment with Apple. 2. If your server receives the callback request, and the callback content is right, please return a single character string '1' as response. 3. If the response is not '1', our server will retry performing callback up to 10 times in a small amount of time.
You may transfer to your PayPal Account. If you havent entered your PayPal Account, please click Account Info tab, or go to http://papayamobile.com/offer/account. After you click Transfer button, we will start handling your request. The required revenue will be transferred to your PayPal early in the following month. If you have games that use our Chinese server, please manage your income here: http://cn.papayamobile.com/offer/transfertopaypal .
Sensor Detection
To detect location: c_sensor(SENSOR_LOCATION, whereami); Callback should be: function whereami(sensor_type, latitude, longitude) latitude and longitude are integers. To detect acceleration: c_sensor(SENSOR_ACCELEROMETER, acce); function acce(sensor_type, x, y, z); x,y,z are integers 0-1000.
Connecting to Server
Your game has to know which server to connect. This is done by modifying game.config: script_name=social.as base_url=http://192.168.1.15/ This url sets the root path of your server.
Downloading Pictures
base_url tells the server the address. Now you can connect to it in the game code. For example, to draw a picture downloaded from the server: var t = p.addsprite(); t.addaction(sequence(request("1.png"),itexture("1.png"))); 1.png is a picture file on the server. It must be in the HTTP root folder, as follows:
Request is an Action for download via HTTP. Itexture is an Action that sets a Nodes texture immediately.
Downloading Files
You can also download files besides pictures. For example, you can download a text file named data in the root folder. http_request("data", callback); functioncallback(request_id, ret_code, response_content){ trace("res: ", response_content); } Callback specifies what happens after a download is finished. request_id is a unique id of this request ;
Papaya Game Engine SDK Manual 48
Using POST
The only difference from GET is one more argument for data passed to server. This data can only be a String or a Dict. http_request("data", callback,mydata); or http_request("data", callback,dict([[1,10],[2,20]])); Callback has the same form: functioncallback(request_id, ret_code, response_content) Response_content is also a String.
The plist file is a XML file like the right one. The small textures are indexed by 0.png, 1.png and so on. Write the code: var scene = getscene(); load_sprite_sheet("planet.plist",0,hPlist); function hPlist(filename,result,param){ trace("plist callback"); scene.addsprite("planet.plist/0.png").pos(100,100); } The function is load_sprite_sheet(plistfile[, 0/1, callback, param]) plistfile: 0/1: callback: param: file name of the plist file 0 means the plist file and picture are local. In this case, they must be in projects/xxx/res/ 1 means the two files are to be downloaded from HTTP server. this function is called when the texture is loaded, either from local or server. parameters passed to callback.
planet.plist is the plist file name. hPlist is a callback invoke when the large picture is loaded and ready to draw texture. The callback has 3 parameters, filename is the plist file name; result == 1 means success, 0 means failure; param is the same thing passed in during calling load_sprite_sheet. "planet.plist/0.png"points to the first small texture. You may find these names in the plist file. Compile and run. You will see the first small texture is displayed.
or
And the icon is like this : Both are customizable. For the entrance page, you can substitute the image on the top. Create an images/games folder under your project folder (if your project is a demo, the folder is projects/demo/images/games, and put 1 image in: enter_game_banner.jpg. Note that the name cannot be changed. For example, dont change enter_game_banner.jpg to enter_game_banner.png. Note: the size of enter_game_banner.jpg must be 580*180. You must make your own image into the same size. Customizing the Icon: For Android, Create an icons folder under the project folder (like projects/demo/icons), and put in a new icon.png there. Note the name icon.png cannot be changed. For iOS, Do it in an Xcode project.
To customize the icon, put a wallpaper_icon.png in projects/demo/icons. Also do not change the file name. Change game.config to this:
Then you will see Papaya game Wallpaper in the live wallpaper settings:
Start
physics.start() Call this before any of the following functions.
Units
A Physics Engine simulates the physical world, so the internal units are meters, Newton force, and so on. You can set the internal pixels-per-meter ratio that is used in converting between onscreen coordinates and simulated physical coordinates, by calling: physics.scale(ratio) If ratio is 30, then 30 pixels are treated as 1 meter in the program. This setting should be done only once, before any physical objects are instantiated. Changing this ratio has no visual effect but will effect the accuracy of the physical model. Our engine works best for objects whose sizes are within range [0.1meter 10meter]. The default ratio is 30 meaning that the optimal objects should have screen sizes within range [3-300 pixels], corresponding to the physical world [0.1 10 meter]. 30 should work for most typical Android apps. For higher-resolution devices like iPad, or iPhone 4, you may wish to increase this value to 60 or more. The Newton Force Ratio cannot be set. It is always 100:1, meaning that 100 in source codes correspond to 1 Newton.
Gravity
Gravity is a vector. The default value is (0, 98), meaning that in x-axis, there is no gravity; in y axis, gravity is 9.8m/ s2. The ratio is 10. You can set it by calling: physics.gravity( 0, 100)
Set it to 10m/ s2 in y axis. This setting should be done only once, before any physical objects are instantiated.
Configuration
physics.positioniterations(number) This sets the number of iterations when the engine computes positions. The engine does some iteration to simulate the physical positions. The larger the number is, the more accurate the results are, but also the more computation overhead there is. Default value for the number is 8. It should be good for general cases. physics.velocityiterations(number) This sets the number of iterations when the engine computes velocity. The larger the number is, the more accurate the results are, but also the more computation overhead there is. Default value for the number is 3. It should be good for general cases. Note: Inaccuracies may occur when there are overlapping objects. In that case, if you are not satisfied with the visual results, you may change the iterations with the two APIs.
Collision
If you want to do something when a collision occurs, setup an Event handler like this: physics.setevent(EVENT_PHYSICS_CONTACT,callback[, param]) or node.setevent(EVENT_PHYSICS_CONTACT,callback[, param]) callback must have the form: function callback(eventType,node1, node2, param, normal_impulse,tangent_impulse) eventType can be: CONTACT_TYPE_BEGIN , CONTACT_TYPE_END , CONTACT_TYPE_PRESOLVE , CONTACT_TYPE_POSTSOLVE Check API_Reference for details when these eventTypes occur.
Bodies
Creation
Bodies are physical objects. To add physical features to pictures or labels in your game, first construct a Node, then bind the Node to a Body. Only Nodes whose sizes are not zero can be bound to a Body.
Papaya Game Engine SDK Manual 56
var ground = scene.addsprite(ground.png); // construct physics.bindbody(ground,BODY_TYPE_STATIC,density,friction,restitution,shape);/ /bind shape is an Array specifying vertices of this picture. This must be given by programmers since the engine cannot recognize the bounds of a picture. The vertices must be given in clockwise order and in Node coordinates (not world coordinates). For the triangle below,
(0,0)anc
If it is drawn by var triangle = scene.addsprite('triangle.png').anchor(50,50)
hor
point
anchor point is set to (50,50), meaning the geometric center of the triangle. Then 3 vertices in Node coordinates are anchor points Node coordinates are always(0,0).
Even if the triangle is stored in a rectangle bitmap, since you want it to be a triangle in the physical world, you need to specify the shape with 3 vertices (clockwise order): var shape = [0,-35, 37,30, -37,30] ; Check API_Reference for other parameters of physics.bindbody().
Body Type
When physics.bindbody() is called, a Body type like BODY_TYPE_STATIC can be passed in. If only one argument is passed, like physics.bindbody(ground,BODY_TYPE_STATIC); then by default this Body is a dynamic Body. Body types can also be changed afterwards by body.bodytype(type). There are 3 Body types: BODY_TYPE_STATIC They dont move or interact with others. Examples are walls and grounds. BODY_TYPE_DYNAMIC Affected by gravity and collisions. BODY_TYPE_KINEMATIC- They can move but not affected by gravity. If you want a Body to be dragged, its type must be BODY_TYPE_KINEMATIC. Otherwise when you drag it, it will fall because of the gravity.
Body configuration
You must change Bodies features on Nodes. node.bodytype([type]) type can be BODY_TYPE_STATIC, BODY_TYPE_DYNAMIC, BODY_TYPE_KINEMATIC Change the sleeping mode node.sleepingallowed([flag]) Even if you may have called physics.start([nosleep]), you can still change some Bodys sleeping mode here. flag ==1 means the Body can go to sleep when there is no interaction; flag ==0 means the Body cannot sleep. Change the active state node.bodyactive([flag]) flag ==0 means the Body is to be inactive, meaning that the engine does not compute for it and it has no iteraction with other Bodies. flag ==1 means the Body is active. Change the awake state node.awake([flag]) Bodies can go to sleep when there are no interactions. You may call body.awake(1) to wake them up. Calling body.awake() with no arguments returns current state, 0 or 1. Set the Body to be a bullet node.bullet([flag]) flag==1 means the Body is to be a bullet. Bullets are subject to continuous collision detection, rather than periodic collision detection at world time steps. This is more computationally expensive, but it prevents fast-moving objects from passing through solid barriers. By default, Bodies are not bullets. Set the Bodys sensor node.setsensor(flag) Bodies can be divided into rigid and non-rigid Bodies. By default they are all rigid. Calling setsensor(1) would set Bodies to be non-rigid. Rigid Bodies bounce off when colliding, while non rigid ones enter one another when colliding. Note that if you set collision Event handler on rigid Bodies, only CONTACT_TYPE_BEGIN , CONTACT_TYPE_END occur. There are other configuration APIs, please check API_Reference for details.
Moving Bodies
To move Bodies, you need to add Force or Impulse. node.applyforce(force_x, force_y, coordinate_x, corrdinate_y) This sets a Force at world coordinates [coordinate_x, corrdinate_y] (not Node coordinates). force_x, force_y are x and y components, both in 0.01 Newton, meaning that 100 in source codes is1 Newton. If the target point is the body's center of mass, it tends to push the body in a straight line; otherwise, the body spins about its center of mass. node.applylinearimpulse(impulse_x, impulse _y, coordinate_x, corrdinate_y) This sets an Impulse at world coordinates [coordinate_x, corrdinate_y].
Force vs. Impulse An impulse is meant to simulate an immediate "kick" to the body, while Force is something exerted over time.
Joints
Joints are used to assemble complex game objects from multiple rigid bodies. For example, join the limbs of a ragdoll figure, or the wheels of a car. Our engine supports different joint types. Some can be powered by motors, and others are subject to various physical restrictions in their ranges of motion. The simplest type is revolute joint, joining two objects at a single revolute point. To construct a Joint, you need first construct 2 Bodies, and of course bind them to 2 Nodes, and then use the 2 Nodes to construct.
Revolute Joint
var myJoint = physics.createjoint(JOINT_TYPE_REVOLUTE, node1, node2, 200,300 ) node1, node2 are to be joined. (200,300) is the world coordinated specifying at which point the two Nodes join.
Motors
myJoint.enabledmotor([flag]) This specifies whether Motor is to be used. flag==1 means enabling Motor. myJoint.maxmotortorque(torque) After Motor is enabled, you can apply a torque to the Joint and let two Nodes rotate. torque has unity of 0.01 Newton. If you dont set this, by default maximum torque is very little; you may need to set to a large value if there is no visual effect. myJoint.motortorque() This function returns the current torque value.
Rotation limits
To constrain the rotation ranges of 2 Nodes joined by Revolute Joint, you need to set a limit. myJoint.enablelimit([flag]) This sets whether a limit is to be used. flag==1 means limit is enabled. myJoint.limits(from, to) This sets the rotation limit. from, to are in degrees, (-45,45) etc.
Distance Joint
var myJoint=physics. createjoint(JOINT_TYPE_ DISTANCE,node1,node2, node1_x,node1_y, node2_x,node2_y) This creates a Distance Joint. It joins 2 Nodes at a fixed distance. node1_x,node1_y is the point at node1 to be joined; node2_x,node2_y is the point at node2 to be joined. They are also world coordinates.
Papaya Game Engine SDK Manual 59
Configuration
myJoint.length([value]) This sets the fixed length, the distance of 2 Nodes joined points. value is in pixels. myJoint.frequency([value]) This sets how quickly the Joint responds to changes in distance. Although Distance Joint joins Nodes at a fixed distance, it does not mean the distance is always stable. It may increase or decrease, while the Distance Joint guarantee Nodes will go back to the fixed distance. Visually, Nodes seem to be bouncing back and forth. If the frequency is high, the Joint responsds more quickly and Nodes seem to be bouncing fast. value is in 0.01 Hz. 100 means 1 Hz. myJoint.dampingratio([value]) This sets how elastic the Joint is. frequency() sets how quickly the Joint responses, this sets how much it responds. A larger ratio means it responds less and seems more elastic. value can be integers from 0 to 100.
Prismatic Joint
A PrismaticJoint joins 2 Nodes in one axis. 2 Nodes can only move along the single axis, like pistons. myJoint = physics.createjoint(JOINT_TYPE_ PRISMATIC, node1, node2, node1_x, node1_y, axisX,axisY ) This creates a Prismatic Joint. Note that orders matter here. node2 moves around node1, with (node1_x, node1_y) as the origin and (axisX,axisY) as the direction. node1_x, node1_y are Node coordinates, not world coordinates.
Motors
Compared to a Revolute Joints Motor which is driven by a torque force, a Prismatic Joints Motor is driven by a linear force. myJoint.maxmotorforce(value) This sets the maximum linear force. value is in 0.01 Newton. 100 is 1 Newton. myJoint.motorspeed(value) This sets the speed along the Joints axis. value is in pixels per second.
Linear Limits
To enable a limit on the linear motion myJoint.enablelimit(1) To set the limit myJoint:limits( 100, 200 ) 100,200 are in pixels.
Papaya Game Engine SDK Manual 60
Friction Joint
A Friction Joint is a special kind of revolute joint that resists motion, or is sticky. APIs are similar as in Revolute Joint. myJoint = physics.createjoint(JOINT_TYPE_FRICTION, node1, node2, 200,300 )
Weld joint
A Weld Joint welds two bodies together at a specified point in world coordinates: myJoint = physics.createjoint(JOINT_TYPE_WELD, node1, node2, 200,300) This joint does not move or rotate at all. However, due to mathematical approximation, this joint may appear slightly soft during motion. If you want to rigidly bond multiple Nodes together, you may want to specify them as Children within a single complex Node, rather than using Weld Joints.
Wheel joint
A Wheel Joint combines a prismatic and a revolute joint, like a wheel mounted on the shock absorber of a car. Most of its properties are inherited from the standard Prismatic Joint; the difference is that the Node at the end of the axis is allowed to rotate. myJoint = physics.createjoint(JOINT_TYPE_WHEEL,node1,node2, node1_x, node1_y, axisX,axisY ) Motors and Limits for the Wheel Joint are the same as the Prismatic Joint.
Pulley joint
A Pulley Joint joins two Nodes with an imaginary rope whose length remains constant. If one body is pulled down, the other one will move up. The total length of the pulley rope is conserved according to the initial configuration. myJoint = physics.createjoint(JOINT_TYPE_PULLEY, node1, node2, node1_x, node1_y, node2_x, node2_y, node1hang_x, node1hang_y, node2hang_x, node2hang_y, ratio) node1_x,node1_y,node2_x,node2_y are 2 Nodesjoining points in Node coordinates. node1hang_x,node1hang_y,node2hang_x,node2hang_y are points in world coordinates where 2 Nodes hang from the rope. ratio sets which side of the rope moves faster than the other side. length1 + ratio * length2 == constant
tangent_accel_var: variance in acceleration along the tangent line max_radius: initial max radius for rotation max_radius_var: variance in max radius for rotation min_radius: min radius for rotation rotate_per_second: initial rotate speed in degrees per second rotate_per_second_var: variance in rotate speed position_type: can be one of POSITION_FREE, POSITION_RELATIVE, POSITION_GROUPED Each key sets a feature of the Particle. Some features have an initial and a variance value, like start_particle_size, start_particle_size_var They are used to calculate the current values dynamically. currentValue = initialValue + random * varianceValue is a random number between -1.0 to 1.0 An example, to create a fire Particle system, var fire = node.addparticle(PARTICLE_FIRE) fire, the return value is also a Node, containing all Particles. Or var d = dict([ ["max_particles",250], ["angle",90], [angle_var,10], [duration, -1], [start_color_red,194], [start_color_green,64], [start_color_blue,31], [start_color_alpha,255], [finish_color_alpha,255], [start_particle_size,54], [start_particle_size_var,10], [finish_particle_size,-1], [position_var_x,40], [position_var_y,20], [emitter_type,PARTICLE_MODE_GRAVITY], [speed,-60], [peed_var,20], [particle_life,3000], [particle_life_var,1500], [blend_additive,1] ]); var fire = node.addparticle(d); Note: Not all keys need to be set. Some features do not matter. For example, there is no rotation here, so max_radius does not appear. Some features can go with the default values, like gravity_y with default 98, so that is does not appear too.
PapayaAS Basics
In this manual we will only discuss the differences between PapayaAS and ActionScript. If you are unfamiliar with ActionScript, please refer to an ActionScript manual first. Details of ActionScript grammar and syntax are not explained in detail here. Essential ActionScript 3.0 by OReilly is highly recommended. Two general comments on coding style: 1. Please add ; whenever it should appear: var a = 1; return 1; 2. Do not put everything in one file. import can be used to access another file.
Data Type
Int: Any number is treated as an integer. var a = 100; const b = -200; Floating point and Number are not supported and will not be necessary in Android games. And there is an upper bound of integers, MAX_INT= 0x3fffffff. String: String is quoted by double quotes. var a = asfasdfd, const b = tttt; Please do not use single quotes. Boolean var a = true; var b = false; true evaluates to 1, false to 0. Array var a = [1,2,3]; var a = new Array(1,2,3); Both these statements createan Array with 3 elements. new Array(10) create an array of size 10. These statements are the same as ActionScript, but related functions will not be the same. Please refer to our API document for collection types. We have built-in Set, Dict, Array, and a rich function set.
Variable Types
Variables can be declared with types. var a:int However, the compiler does not perform type-checking, similar to Flex Builder standard mode.
Operators
~, >>>, ===, !==, >>>= are not supported. Others are the same as ActionScript.
Control Blocks
If If(a==1 && b>=2){ } else if(a>=3){ } else{ } FOR for(var a = 1; a<2;a++){ break; continue; } Note for(i in array) , for each(i in array) that is not supported, in cannot be used in loops. WHILE While(a>1){ } DO do{ }while(a>1) Break, continue do not go to arbitrary labels. Labels are not supported. Switch, try, throw, with statements are not supported.
Function
function f(a,b=1,z){ return 1; } Functions can be nested, but nested functions cannot be accessed from an outside scope. function f(a,b){ a = 1;
Papaya Game Engine SDK Manual 66
function g(I,j,k){ a = 2; Error! } } If you want to access outside variables, pass them in as arguments. The standard nested function design may increase memory consumption for some uncommon functionality. We decided to design it simply for the embedded environment.
Namespace, Prototype
These are not supported.
Compilation Error
We do not report every error according to ActionScripts specification. We report the following: 999: Access to Array %s must have one integer index
Papaya Game Engine SDK Manual 67
1006: 1023: 1024: 1038: 1039: 1042: 1044: 1049: 1119: 1120: 1125: 1131: 1136: 1138: 1139: 1151: 1152: 1172: 1190: 1193: 1203:
A super expression can be used only inside class instance methods. Incompatible override Overriding a function must use override attributes Target of break statement was not found Target of continue statement was not found this keyword can only be used in instance methods Interface method %s not implemented by class %s Illegal assignment to variable %s specified as constant. Access of possibly undefined property %s Variable %s is not defined Methods defined in an interface must not have a body Class must not be nested. Incorrect number of arguments, expected %d Required parameters are not permitted after optional parameters Variable declarations are not permitted in interfaces A conflict exists with definition %s A conflict exists with inherited definition %s Definition %s could not be found Base class was not found, not defined as class, or is not a compile-time constant Interface definitions must not be nested within class or other interface definitions No default constructor found in base class %s
fetch attribute of None means there is a null pointer. PC=10 tells you the location. Then stop run.bat command, and type command: compile.bat -PC 10 test You will see:
This tells you the null pointer is in test.as file, line 2. a.stop() generates the null pointer exception.
Then stop run.bat command, and type command: compile.bat -PC 27 test You will see: