RSS2.0

Hyzobox Script Basics

Monday, December 14, 2009

This article explains the basics of Hyzobox script. It describes the parameters of Hyzobox.createInstance method and shows how you can render the games asynchronously (for example after document loaded event).

Hyzobox makes it very easy for publishers to embed Hyzonia games. You just copy four lines of codes from publishers control panel and paste it in your HTML page:

<script type="text/javascript" 
   src="http://www.hyzonia.com/hbox.axd?gt=popndrop"></script>
<script type="text/javascript">
    Hyzobox.createInstance("popndrop", "paradise.hyzonia.com")
      .render();
</script>

Usually you don't need to modify this code unless you are interested in more advanced features of Hyzobox. One popular example is Integration Services, by which you can automatically login your users into the games.

In this article we explore the basics of Hyzobox script in more details.

To embed a game first you have to load Hyzobox base script in your page by:
<script type="text/javascript" 
   src="http://www.hyzonia.com/hbox.axd?gt=popndrop"></script>

Note that this script receives a gt (game type) parameter. Knowing the game type an enhanced version of the script will be loaded. At the time being all game types (PopNDrop, HiddenObjects, BubblePopper, Fishing, UFOs, FunkyMonkey, Shop) use the same base. If you want to have more than one game in a page, you don't need to load this script twice. gt is not case sensitive.

Hyzobox.createInstance() function creates an instance of Hyzobox object. It takes three parameters: game type and the instance name of the game and options. Instance name is usually in this format: [name].hyzonia.com. Note if you are developing a game at Island level, here you should pass the full URI of your Island. By default game type and game instance name are not case sensitive. Options is a JSON object. It is optional. See an example of how it is used here.

Hyzobox.createInstance() returns a reference to the Hyzobox object it creates. You can assign it to a variable:
var hb = Hyzobox.createInstance("popndrop",
   "paradise.hyzonia.com");
Hyzobox object supports a plug-in model, it is possible to load new functionalities for it later (after it instantiated). Depending on the loaded features, Hyzobox instance supports a variety of methods and attributes.

The most important method of Hyzobox object is render(). render() adds the instance to the HTML page. When you call render() with no parameter it uses document.write() to write a div and an iframe. It adds the game instance at exactly the point it was called.

For example:

<script type="text/javascript">
    Hyzobox.createInstance("popndrop", "paradise.hyzonia.com");
</script>

<div id='gameContainer'>
 <script type="text/javascript">
    hb.render();
 </script>
</div>

Here the game will be inserted in the 'gameContainer' div.

This behavior is not always preferred. In some cases you may want to render Hyzobox object after the page is loaded or an event is triggered.

You can pass a reference to an HTML element to render() method. In this case render() uses document.createElement() to create and insert div and iframe inside the given element and DOM. For example:

<div id='gameContainer'>
</div>

<script type="text/javascript">
    var hb = Hyzobox.createInstance("popndrop",
      "paradise.hyzonia.com");
    hb.render(document.getElementById("gameContainer"));
</script>

The output of this code snippet is similar to the previous one, it adds the game inside the 'gameContainer' div. Note that render(refToHTMLElement) could be called at anytime.


Bookmark and Share
Read more...

Chapter 3: Visual Objects and Mechanics

Sunday, November 29, 2009

In the previous chapter we talked about the conceptual design of the fishing game we are developing for Hyzonia. In this part we discuss the game play and we develop a working prototype of the game.

The main purpose of a Hyzonia advergame is to make the users engage with the advertised contents. Advergames should be easy to play; they should not have a very complicated game flow. In general they should not require a particular platform to run. Most of the time your audience is a wide range of internet users, not hardcore gamers.

The content of this article doesn’t describe any particular feature in Hyzonia Game Services platform. Here we build almost all the logics and UX of the game. This will be a JavaScript game and we heavily use jQuery. JavaScript using jQuery is a very fast and developer friendly platform. If you are a web designer you don't need to acquire a new skill to develop a JavaScript based game. On the other hand it will help us to make the games easily customizable (we will dig into customization in a later chapter).

The objects that we are developing here could be reused in many other JavaScript games.

We chose a classical game development approach for making this game; we are going to have a game timer that ticks several times a second and all the magic happens during each tick.

In our implementation the GameTimer class has an array of MovingObjects. In each tick the timer calls move() method of each MovingObject. The move method updates the position of the object and draws it on the screen.

GameTimer

GameTimer is a singleton object.
The most important methods of GameTimer are:
  • start()
  • stop()
  • pause()
  • addMovingObject(movingObject)
  • funcs: an array of callback functions. These functions will be called at each tick.
  • frequency: in miliseconds
  • tick(): private

Current implementations of JavaScript in browsers don't support threading and parallel programming. It means that all the time that it takes for exestuation of the callback functions that run at each tick must be less than the frequency of the timer; otherwise the user will experience freezing and delays.

ViewPort

A game may have many view ports. Each view port has its own set of MovingObjects. The game can have one active view port at a time. All visual objects must belong to the active ViewPort to be rendered on the screen. This game has only one view port.

The ViewPort object has these members:
  • size: this width and height of the view port
  • jq: a reference to the jQuery object of the parent HTML element of the view port (all visual objects in the ViewPort must be child elements of it)
  • addMovingObject(movingObject)
  • And some attributes related only to this game like sea level.

MovingObject

  • position: the x, y position of the object, relative to its view port.
  • size: the width and the height of the object.
  • v: the instant velocity of the object relative to its view port.
  • jq: a reference to the object's jQuery object (visual representation of the object).
  • t: time (automatically assigned by GameTimer).
  • getRect(): returns a Rect object describing the surrounding rectangle of the visual object.
  • contains(x, y): finds whether point x, y is inside the object (x and y are relative to the object's view port. It will be used for a simple collision detection.)
  • _updatePosition(): it is virtual method, by default it adds the instant velocity to the position of the object on each tick. We override this method in child classes to control the motion of the objects.
  • move(): moves the object to its current position.
  • _onMoved(): it will be called after the object is rendered in the screen at its current position.
Boat, Fish and Rod inherit from MovingObject.

In this game the player has to catch fishes using a fishing rod. The length of the thread of the rod increases as long as the left mouse click in down (so the player can catch fishes in deeper positions). It begins to retract as soon as the user releases the left button. Its length changes between a minimum and maximum value. You can think of many mathematical functions to control the length of the thread. The range of the function should be between min and max of the thread. We chose a simple trigonometry function, arc tangent. The change of the return value of arc tangent function slows down as its argument grows to bigger numbers.

Arctangent function

We attach a time property to rod. Rod time changes between 0 and 5 and its length changes between 0 and a coefficient of 7π/16. arctan(0) = 0 and arctan(5) = 7π/16.

User Input Handlers

GameControlsState class contains all the data about the current state of controls: the location of the mouse, the buttons that have been pressed but not yet released, etc. Event handlers change the state of this object. Later at each tick, each callback function checks if its controls have been triggered or not.

For example _updatePosition() method of Boat looks like this:
_updatePosition : function() {
        if(GameControlsState.keyBoard.left) {
            this.position.x -= 5;
        }
        if(GameControlsState.keyBoard.right) {
            this.position.x += 5;
        }
}

It means that at each tick of GameTimer, the boat moves 5 pixel to the left if left arrow key is down. Because tick is called 30 times a second, the small delays between each tick is unnoticeable for a player. Unfortunately JavaScript doesn’t support multithreading. You have to limit the amount of computation in each tick. User feels the delays if the computation takes more than 30 milliseconds.

Depending on your game you may want to choose a different event handling pattern.

Fish

The Fish object inherits from the MovingObject therefore all we need to make it behave like a fish is to define few more properties and a custom moving function by overriding "_updatePosition" function, Fish has the following attributes:
  • isTrash: if true, it means that the object is a trash (trashes have no use for the player, we will talk about the difference between Fish and Trash and the need for trash objects in a later chapter)
  • movingDirection: the direction in which the fish moves, it can be from right to left "rtl" or left to right "ltr".
  • mouth: the mouth is a rectangle that defines the mouth area of the fish in which the fish can be caught.
  • isHooking(x,y): this function takes the hook's coordinates and finds whether the hook is inside the fish's mouth.
  • hook(): once the rod hooks the fish, it calls this function. This way the act of hooking will be controlled by the rod not the fish. After this call the fish can do any necessary action like performing a fishing animation.
  • switchImageToVertical(): it is a private function. To make a better fishing animation, we rotate the fish image vertical direction as it is being dragged by the rod's hook. The function creates this animation using spriteAnimation jQuery plugin.





Two kinds of sprite animations we use for a fish: swimming and fishing. Note that the fish rotates around an axis that is located at its mouth.

Fishing Rod

Another important object in our fishing game is the rod that the player will use to catch the fishes. The hook is a part of the rod object and it is responsible for catching the fishes. The hook is a property of the rod which moves down and up. While the hook is moving we continuously check if the hook intersects with any fish by calling the fish's "isHooking()" function. This way the act of fishing will be controlled by the rod.

The rod goes through three main phases: moving down and up looking for fish, catching a fish and going back to the boat (retracting) with a fish.

By overriding the "_onMoved()" function of the movingObject class inside the rod, we can check for fishing events:
  • When the rod is fully retracted and has a fish: it means that we should add the fish to the players bucket and do all the related events Like (increasing score, removing the fish from the ViewPort, …). This state is particularly important for Hyzonia advergames, this is where the player makes a progress in this game. All Hyzonia games must work with a type of Hyzonia Quest. From a very abstract point of view Hyzonia expects players continuously progress in the Quests and win them. We will discuss it in details in chapter 5.
  • When the hook of the rod intersects with a fish: we fires the hooking events.

Config

If you look at the code you will notice that in several places we use Config object. Config represents the static configuration of the game and is a singleton name value collection in JSON format. The attributes of this object will be customizable. This is a common feature in all Hyzonia games. We talk about customization in details in a later chapter, for now we just describe the most important attribute of Config in this game:

  • LIST_OF_FISHES: An array that defines the types of fishes the game has. Each element of the array is a fish data object that has the following properties:
    • isTrash
    • size: the size of the fish image.
    • movmentImage: the URL of the sprite animation of the fish in swimming state.
    • imageUrl: the URL of the sprite animation of the fish in fishing (hooking) state.
    • dir: swimming direction, "rtl" or "ltr".
    • swimDepth: an array of numbers that represent the y positions in which the fish can appear in.


We place the "LIST_OF_FISHES" array in the Config file. Later this file can be exposed to Publishers to enable customization of the game (for example using LIST_OF_FISHES they can customize the picture of the fishes).


Here is the prototype of this game. You can download the source code. We kept the code simple and clear. Therefore it lacks lots of small FX and fixes, but it's easy to follow the logics.


"GameTimer" and the "MovingObject" classes are very handy and can be used in implementing many kinds of games. Such these generic classes makes development of JavaScript based games easy and neat.

Here we also used our "sprite animation" jQuery plugin to create the animations (swimming and fishing); this way the animation is separated from the other logic of the game.

In the next chapter we introduce Hyzonia Game Client Services. These services can be consumed by game clients to communicate with Hyzonia.


Bookmark and Share
Read more...

New loading pane for Hyzonia games

Tuesday, November 24, 2009

In order to better handle graphic rich games, we added a loading feature to the games. Using this feature the user can only start playing when the game finishes loading all its necessary objects. This way the user cannot try to play a game that is not fully functional yet.

This document describes the customizable elements of the "loading" feature.


The loading pane like other parts of Hyzonia games is customizable; Publisher can customize the style of the loading page very easily using the web forms that are accessible in his advergame control panel. If you are not familiar with basic customization for Hyzonia games you can read more in Hyzonia Docs.


The loading page is composed of two HTML DIV elements nested in each other; the parent DIV is the background, customizing it can be done by editing the "loading-div" class, while the child DIV contains the loading dialog where the 'loading…' text appears. This DIV is customizable by editing the "loading-dialog" class.

Both of those classes are added to the look customization section in docs.hyzonia.com.

Note in Blow the Bubbles, Hit the Monkeys, Blow the Balloons and Shoot the UFOs (generally if the game has a separate customizable CSS for Dialog Boxes) there are two places where the loading page appears. Hence two files Game Theme and Dialog Boxes needed to be edited by the same content.

The following is the default style of the loading pane elements:

  • loading-div

    Description
    Changes the style of the loading pane. This pane appears when the game starts till all the game elements are loaded. The background is a "DIV" element, you can use any CSS instruction to style it.
    Code
    .loading-div
    {
    background-color: #aaaaaa;
    }
    


  • loading-dialog

    Description
    Changes the style of the loading pane dialog. This dialog contains the loading text, normally it is "Loading…". The dialog is a "DIV" element; you can use any CSS instruction to style it.
    Code
    .loading-dialog
    {
    background-color:#ffffff;
    color: #000000;
    margin:auto;
    top:50%;
    }
    


Bookmark and Share
Read more...

JQuery Sprite Animation Plugin

Tuesday, November 17, 2009

Since our team uses animation a lot for creating JavaScript games, we decided to encapsulate one of our frequently used JavaScript classes "spriteAnimation" and have it available for other users. One option was to have it as a jQuery plugin since jQuery is widely used and many developers are comfortable working with it. Creating the plugin was easy since it uses JavaScript extendability features which we have already used before in our internal classes. The plugin is now published at jQuery.com in the Plugins section under the name of "jamalm12" that is Me! and here is what the plugin does.


jQuery.spriteAnimation-0.1.0.js

jQuery.spriteAnimation-0.1.0.min.js

Demo



Overview


Create quick sprite animation by applying an image and sprite options. You can specify sprite's options like "frameWidth", "startFrame", "endFrame", "direction" and others. The animation is applied to an element by one line of code. You can use this plugin as an alternative to the "gif" animation, using this plugin you can control your animation behavior from your JaveScript code, like defining the animation delay, having an infinite loop animation or you can specify the number of loops.


Usage


To create a sprite animation using jQuery Sprite Animation you need first to creat
an image that contains the frames of the the animation like the image below.




Have a DIV element in your page and assign the sprite image as background to it.


<div id="sprite1" style="height:85px;width:85px;background-image:url('http://fs.hyzonia.com/hyz.islands/PopNDrop/common/css/arrows.png')"></div>



Call the $().spriteAnimation() function for the DIV.


$(document).ready(function() {
$('#sprite1').spriteAnimation({
numberOfLoops: -1,
direction: 'ltr',
startFrame: 0,
endFrame: 36,
interval: 20
});
});



Options


numberOfLoops

Specify the number of times the animation will be repeated. This attribute is optional, the defualt value is -1 (infinite loop).
imageSrc

If imageSrc was defined in the options object, the plugin assign the background-image
automatically to the element. Otherwise the plugin trys to create the animation
with the current background image.
direction

Specify the direction in which the frames will be moved. This attribute is optional,
the default value is "ltr".
frameWidth

Specify the offset that we apply on each timer tick to create the movement feeling.
This is usualy the width of a single frame of the total frames that makes up the
animation image. This attribute is optional, if it was not specifyed automatically
detect the container element width and assign it as frame Width.
startFrame

The startFrame value is set to -1 as default. This value indecated the frame that
the animation will start from.
endFrame

The endFrame value is set to -1 as default, this value is expected to be set always
and not to be left to default.
interval

The time delay between the frames, This attribute is optional, the default value
is 50 (20 Hertz). Note to stop the animation call the function without parameters.
i.e. $('#sprite1').spriteAnimation()

Bookmark and Share
Read more...

Chapter 2: Game Objects Conceptual Design

Tuesday, November 10, 2009

Developing an Advergame for Hyzonia

In the previous chapter we introduced a kind of casual fishing game that we are going to develop using Hyzonia platform as a sample. In this chapter we will describe the game from an abstract aspect; this will help us to understand the game logic, the main actors and what objects are needed to implement the game for Hyzonia platform.

From a game developer point of view, Hyzonia is a platform that makes building advergames easier and routine. Hyzonia allows the developer to focus on developing the game itself. The developer should think about the game rules and the game play rather than spending time trying to implement features that are not related directly to his specific game (like receiving advertisements, generating reports, etc.). Those functionalities can be implemented using Hyzonia tool called Hyzonia client library and Hyzonia Game Services that we will explain them more in the next chapters.

From a very abstract standpoint a Hyzonia game is made of three layers:
  1. Game Client

    This layer consists of game logic, user experience, visual effects, etc. A Game Client can be made in variety of platforms like Flash, Silverlight, or Java (any platform that can communicate with XML or JSON web services). In Hyzonia we admire JavaScript, in this tutorial we build the client using JavaScript by the help of Hyzonia JavaScript Client library; this library can be used for general games purposes tasks, like having a timer or moving objects in the screen to create game animation. The game client layer is responsible for the following main functionalities:

    • Game Play: Managing the game logic
    • UI: Managing the visual objects and interacting with the player.
    • Game Services Client: Facilitating the communication with the game services
  2. Game Server
    • Game Services: Game Services were built to help the developer to create Hyzonia compatible games easily, the services are XML Web Services that were developed using ASP.NET and can be consumed by any Web compatible technology.
      To make using these services easier to a wider range of developers, the game services can be consumed using any of the following XML or JSONP.

      Hyzonia JavaScript Client library contains a proxy that can be used to facilitate the communication with theses services. Calling a Hyzonia Service using the client library is as simple as calling a JavaScript function.

      Some parts of the targeting job are managed by this component. For example when a player starts a game session, this component finds which ad materials (Items) and Quests are relevant to her.
    • Statistics: The statistics services provide game data that can be displayed in the game like Top Ten Players Scores, The prize of the day, the new prizes in the game….
    • Game Data: All the functionalities that are related to managing the players’ data, ads data, Quests and other related game information like login, registration...etc are implemented using this component. The data layer is commonly transparent for a Game Client developer.
    • Hyzonia Network Communication: The main rule is to communicate with Hyzonia advergames network, this layer communicates all the data related to ads, Campaigns and Quests to and from Hyzonia platform. It is a crucial part of a Hyzonia game, without it the game simply cannot make any money.
      This component is also hidden for Game Client developers.

  3. Hyzonia Advergame Network

    Games that are part of Hyzonia advergames network automatically receive Campaigns, ads and Quests from the network. Campaigns are made by advertisers who use the network to publish them to their targeted players audience. The role of an advergame is to make the engagement of the players with the ad materials happen. The network chooses and publishes the Campaign in the relevant games. Once a game was created using Hyzonia platform, the game dynamically communicates with the network. This does not require the developer to develop any special logic. Everything regarding this communication, receiving orders, targeting players and reporting, is transparent for Game Client developers.

Conclusion:
A casual (adver)game developer has to make Game Play and UI.
He will not care about ads, campaigns, reporting, data management, etc. these things will be provided by Game Services.


Conceptual design of the fishing game

In this tutorial we will focus on the UI, Hyzonia JavaScript Client Library and Hyzonia Game Services.

Here are the main objects for our fishing game:


  • Moving Object
    It encapsulates all the functionalities about animating a visual object in the View Port coordinate system. In our design, Moving Objects, View Port and Game Timer will work closely to move fishes, boat and fishing rod.
  • Fish
    image, position, containing item, isTrash
    move(), isHooked,create(), attachToHook()
  • Fishing Rod
    hook position, phase
    isHooked()
  • Boat
    move(dir), image, position,
  • Game Session
    Contains the data about Quest. A player will either win or lose a Game Session.
    sessionId, time left, items,
    endSession()
  • Player
    Player data will be maintained by Game Services.
    name, id, points,
    increasePoints(),
  • Bag
    items, size
    removeItem(item), addItem(item),
  • Quest
    toDo,
    canWin(), win()
    (see chapter I to read more about Quest and particularly Collect Some Items Quest)
  • Item
    Item is an playable advertismenet material. We will dedicate a whole chapter about the relationships among Items, Quests, Campaigns and Engagements.
    For now think an Item is made of: picture, name, description
  • View Port
    width, height, background, sea level,
    showDialog(dialogId)
  • Game Timer
    Manages the movement of the objects.
Later you will see that we add more UI functionalities to work with registration and login, and a few more features.

In the following post we will talk about visual objects and the mechanics of this particular game. We will make a working prototype of this game using JavaScript.

Bookmark and Share
Read more...

Introduction to User Integration in Hyzobox

Hyzobox allows Publishers to easily integrate Hyzonia customized game into their website. It is as simple as copying and pasting a few lines of JavaScript code into a web page. Using Hyzobox a Publisher can have more than one game in a single web page and visitors will remain in the same page of Publisher’s website while playing the game; the visitor will find the games part of Publisher’s website.

Without User Integration


You just need to copy the embedded script of your game (it can be found in Publisher Profile page) to any page in your website. But the players will have to log in using their Hyzonia account or register for a new account.



Figure 1: No User Integration
Hyzobox has its own Registration/Login form totally independent from Publisher website’s Registration/Login;
So even non-members of the website can play the game;
But, even if our members has logged in already in the website, they still have to register/login again in the Hyzobox to play;
Publisher will lose the opportunity to capture and add the new visitors to its members’ database.

Basic User Integration

Publisher can let your users play in a game directly without the need to create a new Hyzonia account. For using this functionality Publisher has to pass some data about the user (at least her email) to Hyzobox to authenticate the user:
<script type="text/javascript">
var options = {
aa : {
data: "{
em:'user@mywebsite.com',
nk:'user nick name',
dob:'dd/mm/yyyy',
g:'f(emale) or m(ale)',
country:'2/3 letter country code or full country name'
}"
}    
};
Hyzobox.createInstance("PopNDrop", "yourgame.hyzonia.com", options).render();
</script>


The script is tolerant about the format, you can pass the data in different formats. For more information see Hyzobox User Integration documentations.

Users, who are not currently signed in Publisher website (guests), will see a log in form that allows them to use their Hyzonia ID or create a new Hyzonia account. Publisher has an option to disable this functionality, meaning that a player must be signed in Publisher’s website in advance in order to be able to play the games. This way a Publisher keeps its games private for its registered members only.

This feature can be configured from Advanced Customization settings in advergame control panel:
"AA_SETTINGS": { "disableLogRegForms": true}
When Publisher disables log in and registration forms in the game, users will not be able to play unless they already have had an account in its website. Publisher can also configure the game to send anonymous users to a registration page in its website:
"AA_SETTINGS": {
"disableLogRegForms": true,
"loginUrl": "http://www.wingooli.com/login",
"loginLinkText": "Click to login",
"logRegDisabledError": "Login and registration forms have
been disabled in this game."
}



Figure 2.1: Using Basic User Integration Registration or login can be removed from the Hyzobox; so playing the game is limited to Publisher’s members only. If non-members want to play, they will be redirected to the registration page of before they are granted access. Publisher takes advantage of the traffic. As a result, its user database grows.



Figure 2.2: The same protocol applies if the Publisher has more than one advergame embedded in its website.
Members/Players don’t need separate registration/log in in order to play any games within your website.

Signed User Integration (advanced)

Publisher, by signing the data that he is passing to Hyzobox, makes sure that only users that he has approved are able to play in his games.

To use this feature Publisher has to sign the user data with a private key of RSA algorithm. And then pass the signature along with the user data to Hyzobox. Later the game will verify the signature and login the user.

A Publisher is able to use its own keys or Hyzonia can create a key pair for him.

The process of setting up a Signed User Integration is easy:
  1. Publisher has to create a private/public key pair or contact Hyzonia support if he doesn't know how then submit the public key to Hyzonia.
  2. It is possible to require the game to always expect a signature by configuring AA_SETTINGS in Advanced Customization options of advergame control panel:

    "AA_SETTINGS": {
    "optionalSignature": false }
    

  3. The player data (JSON serialized string) must be signed by the private key. The signing method depends on the technology the website is based on. Hyzonia support is able to help Publishers to configure their websites. Once the Publisher has the data signed, he has to add it to the options of Hyzobox script in its web page:

    <script type="text/javascript">
    var options = {
    aa: {
    data: "{ em:'user@mywebsite.com', nk:'user nick name',
    dob:'dd/mm/yyyy', g:'f(emale) or m(ale)',
    country:'2 or 3 letter country code or full country name' }",
    sign: "Base64 String representation of RSA Signature of data string"
    }
    };
    Hyzobox.createInstance("PopNDrop", "yourgame.hyzonia.com", options).render();
    </script>

That’s it. The rest of the job will be done by Hyzobox.

See also:

Related:

Bookmark and Share
Read more...