You are on page 1of 70

Social Game Engine SDK Manual

Version 1.5 (Modified 4 17th 2012)

Papaya 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

Papaya Game Engine SDK Manual

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

Compiler Graphics Library Papaya Social Network Billing Channel

bytecode

Engine

Papaya Game Engine SDK Manual

Built-in Virality and Social Features


The Social Game Engine comes with built-in virality enhancing features that promote your game on the Papaya Social Network. When a user downloads a game with Papayas Social Features integrated, they have the option to join Papayas thriving social network, the Papaya SNS. Over 50 million users interact with each other on Papaya by chatting, posting status updates, sending messages and sharing and reviewing games. On any game with Papaya (including all games developed with the Social Game Engine) tapping the Menu button gives users immediate access to the Papaya SNS. The ability to access a real social network for mobile is the foundation for your games virality, driving the viral spreading of your game in a community of users that love to play and socialize. Built into the Social Game Engine are numerous social features that tap into Papayas social graph and help promote your game across our network through viral channels. To learn more about utilizing the social power in the Social Game Engine, please jump to Chapter 11 which discusses Papayas Social Features in-depth.

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.

In App Purchase on iOS


Apples policy does not allow cross-game virtual currency. You can; however, still sell individual game virtual goods using our billing API built on iOSs in-app purchase. For more details about selling virtual goods, please go to Chapter12.

Papaya Game Engine SDK Manual

Chapter 3: Quick Start on Android


Note: Quick start on iOS will be added soon.

Step 1: Set-up Environment


a. Make sure JDK is installed and configured. If not, download and configure JDK. b. Download the Social Game Engine SDK from http://www.papayamobile.com/developer/engine/. c. Extract the contents to a folder. Lets assume the folder is F:/gsdk.

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.

Step 2: Drawing an Empty Screen


a. Create a file named tutorial.as in F:/gsdk/projects/tutorial/ var p = getscene(); b. Then modify game.config in F:/gsdk/projects/tutorial/ script_name=tutorial.as base_url=http://192.168.1.22:8080/papaya/ social_key=54SO2c8ZwFLINBtn #SCREEN_ORIENTATION_LANDSCAPE: 0 #SCREEN_ORIENTATION_PORTRAIT: 1
Papaya Game Engine SDK Manual 7

#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.

This will give you a blank screen:

var p = getscene();This is a global Scene created automatically. p points to the global Scene, ready to draw other Nodes.

Step 3: Drawing a Picture


a. Add these lines: var p = getscene(); var t =p.addsprite("background.png").size(screensize()); background.png is the file name of a picture. Pictures referred to in your game should be under F:/gsdk/projects/tutorial/res/.

Papaya Game Engine SDK Manual

b. Run it, and youll see the picture:

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.

Step 4: Drawing a Label


1. Add these lines: var p = getscene(); var t = p.addsprite("background.png").size(screensize()); p.addlabel("Hello, this is papaya engine","Arial",25); This adds a Label to the global Scene with the specified font type and size.

Note: By default, a node is drawn at 0,0 in the upper-left corner of the screen.
Papaya Game Engine SDK Manual 9

Step 5: Adding Another Picture and Moving It


Lets perform two actions. First we will move a picture by -600,0 in 4 seconds. If the picture is originally positioned at 600,150, it will move to 600+(-600), 150+0 = 0,150. Next, we will move it immediately to 600,150. The picture will do the first action, then the second, and then back to the first, repeating forever. Example: var p = getscene(); var t = p.addsprite("background.png").size(screensize()) p.addlabel("Hello, this is papaya engine","Arial",25); var t2 = p.addsprite("fish.png").pos(600,150); t2.addaction(repeat(moveby(4000,-600,0),imoveto(600,150))); The picture is added to the scene positioned at 600,150, on the right side of the screen.

Papaya Game Engine SDK Manual 10

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.

Step 6: Event Handler


Handling Events require two things. First, there is the Event you want to handle. Here we have EVENT_TOUCH, which occurs when you touch the screen. Second, you need to define what you want to do when the Event occurs. Here we use addaction() to make the picture do an Action when the Event occurs. Example: var p = getscene(); var t = p.addsprite("background.png").size(screensize()); p.addlabel("Hello, this is papaya engine","Arial",25); var t2 = p.addsprite("fish.png").pos(600,150); 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 run the above code you will see the picture blinks 10 times for 3 seconds once you touch it.

Papaya Game Engine SDK Manual 11

There are multiple Events you can handle. Refer to setevent () function in API doc for more details.

Step 7: Multiple Files


In the same folder as tutorial.as, create a folder label. Inside the folder label, create a file label.as. class Label{ var text = "Hello, this is papaya engine"; } Modify tutorial.as. import label.label; var p = getscene(); var t =p.addsprite("background.png").size(screensize()); var label = new Label(); p.addlabel(label.text,"Arial",25); var t2 = p.addsprite("fish.png").pos(600,150);
Papaya Game Engine SDK Manual 12

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.

Step 9: Quitting an Application


You might have realized by now that the game were creating cannot be exited. Lets modify the dialogue to allow an exit: import label.label; var p = getscene(); var t =p.addsprite("background.png").size(screensize()); p.addlabel("Hello, this is papaya engine","Arial",25); function hquit(x){ quitgame(); } function hno(x){ trace("alert no"); } function hcancel(x){ trace("alert cancel"); } function halert(x){ c_alert(0,"This is an alert",0,"quit",hquit,"no",hno,"cancel",hcancel); trace("this is alert");
Papaya Game Engine SDK Manual 14

} 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.

Papaya Game Engine SDK Manual 15

Chapter 4: Development Tools


Note: The development environment on Android and iOS are different.

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 1: Create a new Xcode project


a. Run your Xcode b. Select File > New > New Project at the top of screen.

Papaya Game Engine SDK Manual 18

c. Select Window-based Application, then click Next.

d. Input your product name and company identifier, click Next.

Papaya Game Engine SDK Manual 19

e. Select you project path, click Create.

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

Papaya Game Engine SDK Manual 20

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.

Step 3: Tweak Build Settings


a. Select the target of your application and activate the tab Build Settings:

Papaya Game Engine SDK Manual 21

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:

Step 4: Update settings of Build Phases


a. Activate the tab Build Phases of you application target and expand the section Link Binary with Libraries. The two library files of the Social Game SDK are added automatically after Step 1.

Papaya Game Engine SDK Manual 22

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

Step 5: Setup the Social Game Engine SDK


a. Open the application delegate file of you project, and add the following lines of code into it: #import "PapayaGameEngine.h"

Papaya Game Engine SDK Manual 23

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.

c. Add the following lines of code to applicationWillResignActive: [PapayaGameEngine applicationWillResignActive:application];

Papaya Game Engine SDK Manual 24

d. Add the following lines of code to applicationDidBecomeActive: [PapayaGameEngine applicationDidBecomeActive:application];

e. Add the following lines of code to applicationWillTerminate: [PapayaGameEngine applicationWillTerminate:application];

Congratulations, your game is ready to be run!

Papaya Game Engine SDK Manual 25

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)

Papaya Game Engine SDK Manual 27

Chapter 6: Graphics System


Coordinates
The origin is the top-left corner. The x and y axis are as shown below: x

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.

Adapting to Different Screen Sizes


The Social Game Engine handles adapting to multiple screen sizes effortlessly. For example, if you write a program based on a 800*480 screen size, you will still get users using other screen sizes such as 480*320. Redrawing pictures and modifying your code to 480*320 plus all other resolutions would be quite a pain! The API v_scale(w,h) helps eliminate the re-sizing headache. You call v_scale(800,480)at the beginning of you program then everything is fine for both 800*480 and 480*320. v_scale(800,480) virtualizes the screen size to 800*480. The engine adjusts coordinates and picture sizes automatically afterwards.

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

Papaya Game Engine SDK Manual 28

Scene, Sprite, and Label are 3 special types of Node.

Node Coordinates and World Coordinates


Every Node has an Anchor point, which is the center of rotating, scaling, and other transformations. Coordinates of children are calculated based on the parent's Anchor point. Anchor point is initialized to 0,0, which is the upper-left corner for every Node. Example: var p = getscene(); //get the global scene var t = p.addsprite("xxx.png").anchor(50,50).pos(100,100); // this sets t's Anchor point to its physical center, and position the Anchor point at 100,100 var t2 = t.addsprite("yyy.png"); // t2's Anchor point is 0,0, corresponding to world coordinates 100,100 (added on the base of its parent t) t2.addaction(moveto(1000, 100,100)); //t2's Anchor point, its left-up corner is moved to 100,100 in Node coordinates, which is 200,200 in world coordinates. APIs node.node2world(x,y), node.world2node(x,y) are used to convert between the two. Coordinate values used in other APIs are all Node coordinates. Note: There are APIs like scale(), rotate() that change the shapes of Nodes. Keep in mind they dont change coordinates.

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().

Papaya Game Engine SDK Manual 30

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

Papaya Game Engine SDK Manual 32

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.

Papaya Game Engine SDK Manual 33

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.

Papaya Game Engine SDK Manual 34

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().

Papaya Game Engine SDK Manual 35

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.

Papaya Game Engine SDK Manual 36

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

, "This is a test file"

Here you must give the content to be written.

Papaya Game Engine SDK Manual 37

Chapter 10: Database


Database APIs allow storing key-value pairs. First, you must open a Database: var db = c_opendb([0/1,[name]]) 0, means only the current user can see this Database; 1 means other users can also see it after they log in. name,this is optional, its the name of this Database. To save: db.put(string key,Object value,[string key1, Object value1 ....]) Multiple key-value pairs can be saved in one call. Keys must be Strings. Values can be anything except your own classes. To get: db.get(string key,[string key1 ...]) Multiple keys can be passed which will return all values in an Array. If only one key is passed in, then the return value is not an Array with one element, it is just that value. To remove one key-value pair: db.remove(key) To delete the whole Database: db.destroy()

Papaya Game Engine SDK Manual 38

Chapter 11: Social


Social APIs give you access to users in the Papaya Social Network and form the basis for creating more socially engaging and viral games.

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 ()

Query Friends List


ppy_query("list_friends", null, hfriend, param); "list_friends" says this query is for friends list; null, the parameter of the query; hfriend, the callback when the query results are returned. The callback must be in this form: function hfriend(requestId, ret_code, response, param){ requested, a unique id of this request. ret_code, 1 means the query is successful. response, a dictionary containing the friends list. param, the same thing passed in ppy_query var flist = response.get("data")returns the friends data in an Array. flist[i].get("name"), returns one friends name. flist[i].get(avatar_version), returns the Avatar image version. flist[i].get(isplayer) returns 0 or 1. 1 means the friend has played the game; 0 means the friend has not played.

Showing Avatar Image


var scene = getscene(); scene.addsprite(avatar_url(userid, avatar_version)); userid is the Users id. avatar_version is got from ppy_query().

Papaya Game Engine SDK Manual 39

Query Papayas (Virtual Currency)


ppy_query("papayas", null, hpapayas, param); The callback has the similar form: function hpapayas(requestId, ret_code, response, param) response.get("papayas")returns the number of Papayas as an integer. Papayas are the virtual currency used in Papaya Social Network.

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.

Updating a Players Newsfeed


ppy_postnewsfeed (msg, link, bitmapBytes) This posts a newsfeed item in the users home page and all of his/her friends home pages. msg is the text to be shown. link can be a link to your website. Social Game Engine SDK opens the link when the newsfeed is clicked. bitmapBytes is an Array storing a Bitmap that is shown in the newsfeed. You may check API_Reference for details of bitmapBytes.

Papaya Game Engine SDK Manual 40

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.

Connection with Facebook


You may let players post status or pictures to their Facebook Wall. var d = dict([["name","Papaya"],["caption","come to play"], ["description","this is funny"], ["picture","http://xxxx"]]); facebook(FACEBOOK_POST,d,onPosted) If the player has not logged in, a Facebook window will be popped out for the player. After logging in, the callback onPosted shows info. function onPosted(ret,response) If ret is 0, it means the player just logged in. In this case, facebook(FACEBOOK_POST,d,onPosted) needs to run again to finish the post. If ret is 1, the post succeeds. Note that the picture to be posted must have a URL, so you may want to store the picture bytes on your server first. You may also get the players Facebook friends: var d = dict([["request","me/friends"],["fields","name,picture"]]); facebook(FACEBOOK_REQUEST,d,onFriendBack); The callback onFriendBack has the response, function onFriendBack(ret,response) If ret is 1, response has friends info in a JSON String. You may parse it like json_loads(response).get("data") The player can also upload picture to Facebook album, var d = dict([["caption","Pic in Papaya"],["photobytes",pic], ["request","me/photos"],["method","POST"]]); facebook(FACEBOOK_REQUEST,d,onPhoto,null,["publish_stream","user_photos","phot o_upload"]); pic contains the bytes of the picture. ["publish_stream","user_photos","photo_upload"] are permissions required by Facebook. You may get more info from Facebook Graph API doc, http://developers.facebook.com/docs/reference/api/

Papaya Game Engine SDK Manual 41

Connection with Twitter


You can do the following things: Update Status var d = dict([["msg","@PapayaGame You guys rock!"],["picbytes",pic]]); twitter(TWITTER_POST,d,onUp); pic contains the bytes of the picture to be posted. Get Friends var d = dict([["cursor",-1]]); twitter(TWITTER_FRIENDS,d,onFriends); Get Followers var d = dict([["cursor",-1]]); twitter(TWITTER_FOLLOWERS,d,onFriends); cursor value -1 is required for the first call, by twitter API. You may get info in https://dev.twitter.com/docs/api/1/get/followers/ids Get User Info var d = dict([["ids",friends]]); twitter(TWITTER_USERINFO,d,onInfo); friends is the same thing got from callback of TWITTER_FRIENDS or TWITTER_FOLLOWERS Send Direct Message var d = dict([["userid",friends[0]],["text","hello from Papaya game"]]); twitter(TWITTER_DIRECTMSG,d,onmsg);

Other Social APIs


Check API_Reference > Social section All social APIs have similar definitions.

Papaya Game Engine SDK Manual 42

Chapter 12: Selling Virtual Goods


If you design virtual goods and put them into your game, the Social Game Engine lets you easily sell them. The payment API and billing channels are already set-up and are ready for use immediately.

Setting-up Your Game for Virtual Goods


Before you can earn revenue with the Social Game Engine, you need to register your app on our website. After registration, you will find a social_key and an app_secret on the web page. Now add them to the game.config file: script_name=tutorial.as base_url=http://192.168.1.22:8080/papaya/ social_key=54SO2c8ZwFLINBtn social_key must be put here and compiled with your app. Well discuss how to use app_secret in the following section.

Integrating Virtual Currency into Your Game


Payment API for Android:
start_payment("buy", "buyvirtualgoods", "",1,paycallback, param);

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.

Payment API for iOS:


start_purchase(virtual good 1, 15, paycallback, param, 1) virtual good 1, ID of this purchase item on App store. It is required by Apple. 15, the quantity to sell paycallback, the callback when the payment is finished. param, will be passed into paycallback. paycallback must have the form: function paycallback(ret, tid, itemid, quantity, param) ret , 1 if succeeds, tid , a unique id of this transaction, itemid , ID of this purchase item on App store, quantity, quantity of this purchase param, passed in from paycallback. Note: There is no receipt here. This is because the purchase is done directly with Apple and there is no need to authenticate with the Papaya server.

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

user actually got session_receipt from the Papaya server.

Icons for Papaya Virtual Currency


If you want to display an icon for papayas (the virtual currency used on Papaya), there are big and small icons available for download on this webpage: http://papayamobile.com/offer/intro_engine

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.

Papaya Game Engine SDK Manual 45

Difference of Revenue Share on Android and iOS


The major difference is, on Android payments are collected by Papaya then transferred to developers. On iOS, payments initially go to developers, then developers transfer Papayas share to Papaya. The difference in revenue collection methods only exists to meet Apples policy and does not impact otherother features embedded in the Papaya Social Game Engine. Developers manage their revenue at http://papayamobile.com/offer/transfertopaypal, whether they have developed for Android or iOS. If the Pending earnings is positive, it means developers earned money on Android; if it is negative, it means developers earned money on iOS and need to transfer Papayas share to Papaya. In such a case where a balance is negative, Papaya will invoice you for the difference.

Alternative Payment method for iOS


If you would like to avoid being invoiced by Papaya and have Papaya pay you directly, Papaya offers a service to upload your game to a Papaya Third Party Developer Account on iOS. By opting for this, Papaya will automatically calculate your earnings in your Dashboard.

Transfering Income to a PayPal Account


If Pending earnings is positive, developers can transfer money to their PayPal account. Go to http://papayamobile.com/offer/transfertopaypal to check how much you have earned.

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 .

Papaya Game Engine SDK Manual 46

Chapter 13: Sensors


Sensors Basics
To add a sensor listener: c_sensor(SENSOR_TYPE, callback); To remove it: c_sensor(SENSOR_TYPE); SENSOR_TYPEcan be: SENSOR_LOCATION 0 SENSOR_ACCELEROMETER 1 SENSOR_MAGNETIC_FIELD 2 SENSOR_ORIENTATION 3 SENSOR_GYROSCOPE 4 SENSOR_LIGHT 5 SENSOR_PRESSURE 6 SENSOR_TEMPERATURE 7 SENSOR_PROXIMITY 8

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.

Papaya Game Engine SDK Manual 47

Chapter 14: HTTP Server


If you have a project named social, running http_server.bat starts a server with projects/social as its root folder. Files in projects/social can then be accessed via an HTTP request. This server is simple, and only supports HTTP GET, however, you can still use techniques like Apache to setup a complex one. Then, both HTTP GET and POST can be used.

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

ret_code== 1 means success ;response_content is the result, always a String.

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.

Updating Game Script Automatically


After you set up your own server, put the two files into the servers root folder, assuming that the project is a tutorial: tutorial tutorial.md5 There is an option in game.config: force_update: 1 means force downloading the latest game script before entering the game. Your game code is 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 things. First, if force_update is 1, players must wait while its downloading. Second, if force_update is 0, players can enter immediately with the old script, but the new script is still downloaded automatically the next time they enter. Our game engine knows whether the script is the latest because of the tutorial.md5. If you modify the code and recompile, the md5 file will be different.

Papaya Game Engine SDK Manual 49

Chapter 15: Sprite Sheets


load_sprite_sheet() is to draw textures contained in a single large picture. OpenGL, by default, treats each texture with size of (n and m are positive integers), even if the actual texture picture is smaller than that (in this case OpenGL puts padding in). If there are many small pictures, you can put them in a single large picture to save memory. Follow these steps to achieve this:

Step 1:Generate the large picture and the plist file


Use the tool Texturepacker (http://www.texturepacker.com/) to generate the files. First download and install the tool. There are several tutorials online for this including this one that we recommend -http://chris-fletcher.com/tag/texturepacker-tutorial/. The tool is very easy to use so you might not even need a tutorial. After you generate the files, there is an option to choose Data Format. We choose cocos2d in our example. In fact it doesnt affect the process. Among the generated files, there are two that we will use - a png file and a plist file.

Step 2: Write code to draw texture


Lets assume the project folder is projects\spritesheet_xml.Put the generated png file and plist file in projects\spritesheet_xml\res. The png file is something like the following, with many small texture pictures.

Papaya Game Engine SDK Manual 50

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.

Papaya Game Engine SDK Manual 51

Chapter 16: Icons and Welcome Screen


Customizing Pictures and Icons
To customize the entrance page, you may replace the default pictures and icons. By default, the entrance page looks like this:

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.

Live Wallpaper Icon (Android only)


In chapter 5, we talked about enabling the live wallpaper feature. By default you see the Papaya Wallpaper icon in
Papaya Game Engine SDK Manual 52

the wallpaper settings:

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:

Papaya Game Engine SDK Manual 53

Papaya Game Engine SDK Manual 54

Chapter 17: Physics Engine


Setup
Before working with the Physics Engine, call var physics = getphysics()

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)

Papaya Game Engine SDK Manual 55

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.

Papaya Game Engine SDK Manual 57

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].

Papaya Game Engine SDK Manual 58

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

Note: Distance Joint has no Motors.

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

Papaya Game Engine SDK Manual 61

Chapter 18: Particle System


To create a Particle system, node.addparticle([arg]) arg can be an integer, specifying which built-in Particle system to create; it can also be a Dict, specifying a Particle systems parameters. If arg is an integer, it can be one of the following: PARTICLE_FIRE 0 PARTICLE_FIREWORKS 1 PARTICLE_SUN 2 PARTICLE_GALAXY 3 PARTICLE_FLOWER 4 PARTICLE_METEOR 5 PARTICLE_SPIRAL 6 PARTICLE_EXPLOSION 7 PARTICLE_SMOKE 8 PARTICLE_SNOW 9 PARTICLE_RAIN 10 All are self explained. If arg is not given, Fire Particle system is created. If arg is a Dict, you need to give values to the following keys: max_particles: the maximum number of Particles in the system; actual number may be smaller at a time point blend_additive: if value is 1, enable blending angle: initial angle of each Particle angle_var: variance in angle duration: how long the Particle system lasts start_color_red,start_color_green,start_color_blue,start_color_alpha: initial color of each Particle finish_color_alpha: ending alpha start_particle_size: initial size of each Particle start_particle_size_var: variance in size finish_particle_size: ending size finish_particle_size_var: variance in ending size position_var_x, position_var_y: variance in position particle_life: how long each particle lasts, not the whole system particle_life_var: variance in life emitter_type: can be PARTICLE_MODE_GRAVITY or PARTICLE_MODE_RADIUS. PARTICLE_MODE_GRAVITY is for Particles that fall with gravity; PARTICLE_MODE_RADIUS is for Particles that rotate. gravity_x, gravity_y: gravity in x and y axis speed: initial speed speed_var: variance in speed radial_accel: initial radial acceleration radial_accel_var: variance in radial acceleration tangent_accel: initial acceleration along the tangent line
Papaya Game Engine SDK Manual 62

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.

Papaya Game Engine SDK Manual 63

Chapter 18: Offers


The Papaya Social Game Engine has integrated TapjoyTapjoy Offer Wall. Many of your users may wish to buy virtual goods, but perhaps do not have the means to do so. With the Offer Wall, you give users a way to purchase Papayas for free by simply downloading and playing other games. For every install, you will receive a share of the advertising revenue. You may show the Offer Wall like this: ppy_showoffers() Before using it, you need to add tapjoy_key=xxxx tapjoy_secret=xxxx in game.config. We will allow managing Tapjoy account on our website soon. Currently please contact blink@papayamobile.com if you want to have a tapjoy key.

Papaya Game Engine SDK Manual 64

Chapter 19: PapayaAS


PapayaAS is a language similar to ActionScript and is designed for easy-to-use and quick-to-learn game programming on Android. PapayaAS is similar in grammar to ActionScript, but eliminates unnecessary features or features that may hurt performance.

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.

Papaya Game Engine SDK Manual 65

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.

Class and Interface


class A{ var a = 1; static var b = 2; function f(a){ } static function g(){ } } Classes cannot be nested. Static variables and methods are associated with the class itself. private, public, internal, and final can be compiled but have no effect. Everything is made public. class B extends A{ override function f(a){ super.f(a); } } Similar toActionScript, static members are not derived. interface TT{ function f(a,b){} } class B extends A implements TT{ function f(a,b){return 1;} } There is no need to write dynamic to declare a class. All classes are dynamic. var a = new A(); a*name+ = t; is not supported. You may write a.name = t;

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

Program Entry Point


PapayaAS is similar to other script languages in that you can write whatever you want to do one line after another, as in our tutorial. We do provide another mechanism. Two special functions can be defined. initialize(), start() In most cases, pictures need to be downloaded online. In order to improve performance, our engine puts the script interpreter and the network operations into two threads. If you want to start execution after the download is finished, you can put the download in initialize(), and other codes in start(). Return -1 or 0 at the end of initialize(). By doing this, it is certain that all downloads are finished when your main codes start.

Papaya Game Engine SDK Manual 68

Chapter 20: Debugging


There is no step debugger currently. We use trace() to print things out, or use PC tool to get the error line.

Example 1: Null Pointer


Create a project named test. Here is the game.config script_name=test.as base_url=http://192.168.1.22:8080/papaya/ social_key=54SO2c8ZwFLINBtn orientation=0 package_name=com.papaya.test app_name=Test Create the main file, test.as, and write: var a = null; a.stop(); Null pointer is a usual bug, although in practice it may not be so obvious. Compile and run, then you will see:

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.

Papaya Game Engine SDK Manual 69

Example 2: Array Index


Add 2 lines to test.as. var a = null; a.stop(); var b = [1]; b[2] = 2; Then you have an Array index error. Compile and run then you will see:

Then stop run.bat command, and type command: compile.bat -PC 27 test You will see:

The Array index error occurs in test.as, line 5.

Papaya Game Engine SDK Manual 70

You might also like