Socialize Your Flash Game with OpenSocial

Socialize Your Flash Game with OpenSocial

here are many creative Flash games on the Internet. Most of them are single player games that are deployed on social networking sites such as Facebook or Myspace. This article helps Flash game developers become familiar with OpenSocial, so they can take full advantage of its social features, and gain a wider audience.

Why are Flash games so popular? One important reason is the easy-access and cross-platform capabilities. After development, you can play them anywhere, both locally or online. Also, you can play them without installing extra items. In addition, you can play Flash games on many types of phones or mobile devices. These features are the goal of OpenSocial. OpenSocial defines a common API that is supported by different sites such as MySpace, hi5, and Orkut (complete list here). Building your game on the OpenSocial API (a JavaScript API) allows you to release them to different social networking sites.

It’s easy to understand OpenSocial’s three main features:

  • People and relationships: The OpenSocial API allows you to obtain information from the person who is playing your game, such as name, gender, and age. When you use OpenSocial, your game no longer requires gamers to log in. Also, OpenSocial allows you to create a friendship network by providing the friends list of the current player along with the friends of the friends. If wisely used in your game (as in Friends For Sale), it increases the number of potential players dramatically.
  • Persistence: You can store data with the OpenSocial API. This allows you to implement load/save for your game, allow gamers to add a custom avatar, or let the players build their own level to share with friends.
  • Activities: Activities are log messages that are posted in your page that describe what you have done. With the API, you can write on a player’s page, which encourages sharing between friends.

Here are three main points to keep in mind before moving forward:

    • For the purposes of this article, Friendster and MySpace are considered the target containers in which you will deploy your sample application and debug. But you can choose any site that supports OpenSocial and has a developer-friendly interface.
    • The author recommends that individual developers, or small groups, use the Google Application Engine (GAE) for hosting Flash games. When you submit games to Flash game portals, there are no issues with hosting, because you simply upload the game. But most social networking sites do not provide upload or host services. However, GAE provides a total of 5 Gigabytes (for up to 10 projects; 500 MB each), so it is advisable to put your games there. GAE also provides an SQL-like database API—the so-called GQL.

You can completely ignore the Persistence feature of OpenSocial for two reasons. First, the GQL is more powerful than OpenSocial’s key-value. Second, the data stored in GAE is independent of containers. That makes it possible to combine the user data from different sites.

  • ExternalInterface is the new way to communicate with JavaScript provided in ActionScript 3.0. Check official documents here.

This article illustrates how to use OpenSocial and GAE through a simple Flash demo. Click here for the demo’s source code as a reference before reading. The entire tutorial contains four main parts:

  1. Hosting Your Game on Google Application Engine
  2. Configuring Your OpenSocial Application
  3. Calling the OpenSocial JavaScript API
  4. Using Persistent User Data for Comments (GQL implementation)

Hosting Your Game on Google Application Engine

Start from the GAE because you need to place all of the code and the SWF file here. Check the official getting started tutorial for reference.

Next, you need a Google account. To apply to the GAE service, click here. Then create an application for your game project. Name the URL for this project: http://your_app_name.appspot.com.

Second, you need to setup your development environment. Download and install Python 2.5 and the App Engine SDK.

Now you can follow the instructions in the getting started tutorial of GAE to build your own helloworld sample and get familiar with it. To host a Flash game, you need to set a static directory by inserting two lines in app.yaml just below the handlers:

- url: /static  static_dir: static	

If you put any.file in static dir, the URL http://your_app_name.appspot.com/static/any.file can access it.

Check Point 1: Put any Flash SWF file in a static folder and upload it with the appcfg.py command. Then, you need to test it to see if you can visit the Flash file with http://your_app_name.appspot.com/static/***.

Configuring Your OpenSocial Application

An OpenSocial application is defined by an XML file (the Main.xml file in the static folder). See Listing 1.

You can check the OpenSocial API Developer’s Guide for more information, but most of the code is self-explanatory. A JavaScript file (main.js) and a Flash object (demo.swf) with id demo.swf are inserted to the HTML content. The demo.swf is the Flash you want to show on the canvas and main.js is where you add the OpenSocial code. All the files (Main.xml, main.js, demo.swf) are placed in the static folder. As shown in Listing 1, the example GAE project name is flashsns. So the URL of these files is http://flashsns.appspot.com/static/***.

Check Point 2: Now you can find a container (Friendster or MySpace for example) to deploy your application. The URL to create an application is http://www.friendster.com/developer for Friendster. (For MySpace, it’s http://developer.myspace.com. You do need approval before you can create your application.) You need to fill out a form when applying for a new application. There is an OpenSocial App XML URL item as marked in Figure 1. Put the URL for Main.xml there (http://flashsns.appspot.com/static/Main.xml). The Canvas URL (http://widgets.friendster.com/app_name) is the public URL to access the application. The app_name is any name you like to identify the application.

Now use Canvas URL to test the application. If everything is OK, the Flash file appears on the page (see Figure 2).


Figure 1. XML URL: The XML URL is marked here.

Figure 2. Canvas URL: Use the Canvas URL to test the application.

Calling the OpenSocial JavaScript API

Now it’s time to call the OpenSocial JavaScript API and socialize your Flash.

Friends and Relationships

The ActionScript communicates with JavaScript using the Call and CallBack functions, which are provided with ExternalInterface. For example, when initializing, the information about viewer is loaded through the following code.

	if (ExternalInterface.available) {		ExternalInterface.call("loadViewer");		ExternalInterface.addCallback("onJSLoadViewer", onASLoadViewer);	}	

For simplicity, omit the error checking. ExternalInterface.calls, the loadViewer function written in main.js. The ExternalInterface.addCallback registers the onASLoadViewer function in ActionScript as a onJSLoadViewer function, which is available for JavaScript. Here’s the corresponding code in main.js:

function loadViewer() {	 var req = opensocial.newDataRequest();	 req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), "viewer");	 req.send(onLoadViewer);} function onLoadViewer(data) {	var person = data.get("viewer").getData();	var personname = person.getDisplayName();	var personid = person.getId();	thisMovie('demoswf').onJSLoadViewer(personname, personid);}

The above code illustrates the steps taken to request data with the OpenSocial API.In the loadViewer function, you need to:

  1. Create a request (opensocial.newDataRequest).
  2. Specify what kind of data you need (opensocial.IdSpec).
  3. Send a request and pass the callback function as a parameter.

Then, in onLoadViewer call back function:

  1. Get data when calling back.
  2. Call the ActionScript function to return data to Flash.

With this request, you obtain the user name and ID before the Flash content starts. Such a request also occurs in the demo application when you click the Get Friends button or ExternalInterface calls loadFriends. The request for the friend’s data is similar. But instead of using newFetchPersonRequest, you should use newFetchPeopleRequest, because you are asking for information about several people. The returning data is an array of person (see Listing 2).

Persistence

As noted earlier, use GQL to save the user data instead of the OpenSocial API. The next section puts this into context.

Activity

Activity in OpenSocial means anything the application posts on a user’s page. For example, activities include game progress or achievements earned in a game. But the application needs the user’s permission to post activities. The steps to post activities are straightforward (from theOpenSocial Developer’s Guide):

  1. Call newActivity to create a new activity with the given text as its title.
  2. Call requestCreateActivity to send the activity to the server, passing a callback function.
  3. In the callback function, handle an error if the server returns one.

Unfortunately, this feature is not very well supported. As tested, Friendster doesn’t implement it and error messages occur when posting activity in MySpace.

Check Point 3: Now you can use the OpenSocial API to load user and friends’ data from containers. The API is easy to use, but debugging is a problem. It is suggested that you use the Firefox’s Firebug plugin for Firefox to debug JavaScript code.

Using Persistent User Data for Comments

As stated previously, you should use the datastore service of GAE instead of the OpenSocial Persistence API.

First, you need to define a data model. Do this by deriving a new class from db.Model in the google.appengine.ext package.

from google.appengine.ext import db class Comment(db.Model):    uid = db.StringProperty()    content = db.StringProperty()		

The example’s Comment model pretty simple. It contains two strings for the comment and user id content.

Then, use the makeRequest OpenSocial API to access the GAE database (clicki here for introduction to makeRequest). To save a user’s comment, a Post request is made along with the content. Use the Get method to retrieve a comment (see Listing 3).

As in the loadFriends function, callback functions (onSaveComment and onLoadComment) are also provided as a parameter when making a request. You can check whether an error occurs and report it to front end Flash through ExternalInterface.

On the GAE side, a new RequestHandler class ApiServer is created to deal with the GET and POST access to http://flashsns.appspot.com/comments (see Listing 4).

The syntax of GQL is similar to SQL (check the reference here).

Check Point 4: The Save/Load was implemented with GQL for persistent user data. You can check all the saved data in the DataViewer section after logging in to GAE as admin. The logging function in GAE helps debug.

Finally, by following all the procedures, you have now integrated all three OpenSocial features (People and Relationships, Persistence, and Activities) for a Flash demo. You’ve hosted the entire project in GAE. Theoretically speaking, to make it run on different containers, the only step left is to submit the URL of the XML file, which describes the application. But because OpenSocial is constantly upgraded, the compatibility to the social network sites is inconsistent. Hopefully, things will improve soon.

devx-admin

devx-admin

Share the Post:
Web App Security

Web Application Supply Chain Security

Today’s web applications depend on a wide array of third-party components and open-source tools to function effectively. This reliance on external resources poses significant security

Thrilling Battle

Thrilling Battle: Germany Versus Huawei

The German interior ministry has put forward suggestions that would oblige telecommunications operators to decrease their reliance on equipment manufactured by Chinese firms Huawei and

iPhone 15 Unveiling

The iPhone 15’s Secrets and Surprises

As we dive into the most frequently asked questions and intriguing features, let us reiterate that the iPhone 15 brings substantial advancements in technology and

Performance Camera

iPhone 15: Performance, Camera, Battery

Apple’s highly anticipated iPhone 15 has finally hit the market, sending ripples of excitement across the tech industry. For those considering upgrading to this new

Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years,

Web App Security

Web Application Supply Chain Security

Today’s web applications depend on a wide array of third-party components and open-source tools to function effectively. This reliance on external resources poses significant security risks, as malicious actors can

Thrilling Battle

Thrilling Battle: Germany Versus Huawei

The German interior ministry has put forward suggestions that would oblige telecommunications operators to decrease their reliance on equipment manufactured by Chinese firms Huawei and ZTE. This development comes after

iPhone 15 Unveiling

The iPhone 15’s Secrets and Surprises

As we dive into the most frequently asked questions and intriguing features, let us reiterate that the iPhone 15 brings substantial advancements in technology and design compared to its predecessors.

Chip Overcoming

iPhone 15 Pro Max: Overcoming Chip Setbacks

Apple recently faced a significant challenge in the development of a key component for its latest iPhone series, the iPhone 15 Pro Max, which was unveiled just a week ago.

Performance Camera

iPhone 15: Performance, Camera, Battery

Apple’s highly anticipated iPhone 15 has finally hit the market, sending ripples of excitement across the tech industry. For those considering upgrading to this new model, three essential features come

Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years, as reported by energy analytics

Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW) of wind, solar, and energy

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and wind sources. This funding will

Renesas Tech Revolution

Revolutionizing India’s Tech Sector with Renesas

Tushar Sharma, a semiconductor engineer at Renesas Electronics, met with Indian Prime Minister Narendra Modi to discuss the company’s support for India’s “Make in India” initiative. This initiative focuses on

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of constructing residential and commercial buildings.

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These