Flash 10 Multiplayer Game Essentials - Hirematada Prashanth - E-Book

Flash 10 Multiplayer Game Essentials E-Book

Hirematada Prashanth

0,0
23,50 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

In Detail

Multiplayer web-based games are more popular than any others, and developing your own is an exciting challenge. But developing multiplayer games is a complex task. There are few resources that explain how to build multiplayer games from the ground up.

This comprehensive guide is packed with practical examples and insights into basic and fundamental knowledge for developing real-time multiplayer games in Flash.

This book starts with the essential ingredients to develop Flash games using Flash Builder 4 and AS3, followed by the basic Flash programming that you need to know in order to write any Flash game. You will learn the basic features that a developer must implement for any multiplayer game. The chapters discuss the challenges you will face when developing a multiplayer game. You will learn to leverage the PulseUI framework to quickly develop a multiplayer game along with all the required screen management. The simple, but powerful, Pulse API model required for multiplayer game development is thoroughly explained as well. As you go through these concepts, you will learn to implement them using code examples.

The last section takes you through four multiplayer game implementations of increasing complexity: first a simple turn-based TicTacToe, followed by a multi-player Jigsaw, a card-based racing game, and finally a complex space racing game.

A development guide for all your multiplayer games

Approach

The book provides all the essentials needed to implement a fully featured multiplayer game in Flash. It begins by dissecting a basic hello-world example providing its code and an insight into each feature that is required. Following the book is easy because of the excellent illustrations and working code samples. Four complete game implementations with increasing complexity are discussed; each example is presented with detailed design, implementation code, and screenshots.

Who this book is for

This book discusses essentials for beginner to intermediate Flash Developers who have perhaps created a game or two in Flash and want to take the next step, and create something that can be played by two or more players over the internet. This book will appeal to professional and amateur developers with an inclination to build synchronous multiplayer games with Flash. No prior knowledge of networking or server-side programming is required.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 345

Veröffentlichungsjahr: 2010

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Flash 10 Multiplayer Game Essentials
Credits
About the author
About the reviewers
Preface
What this book covers
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Getting Started
Development environment
Pulse SDK
Installing Flash Builder 4
Downloading the Pulse SDK
Installing Pulse SDK
Post-installation checks
Running the samples
Starting the server
Starting the client
A high-level architecture of multiplayer game server
Simple deployment architecture
Enterprise deployment architecture
The session server process
The balancer process
Server game programming
Zero server-side programming
Network programming paradigm
Client-to-client interaction
The server modules
Game server modules
Persistence
Session and session manager
Avatar manager
Lobby and room manager
Friends
Chat
Object synchronization
Object serialization
Security
Connection management and message dispatcher
Message
The game client
The overall structure of a multiplayer game
The main game loop
Processing messages from the server
The programming API
Summary
2. Game Interface Design
Overview of Pulse library components
The Pulse API design
Creating the Hello World sample
Setting up the project
The Hello World specification
The schema file
Code generator
Project directory structure
Introduction to PulseUI
Screen management in PulseUI
The PulseGame class
Exploring the Hello World sample
HelloGame.as
The login screen
The screen class
The skinner class
The outline class
Player registration
Exploring the game server deployment
Registration and login
Registration
The login
Dealing with multiple logins
Guest logins
Summary
3. Avatar and Chat
Introduction to Pulse modeler
Example schema
Design of a game avatar
Modeling the avatar
Avatar display in Hello World
Customizing Player Display
Avatar-related APIs
PulseGame client APIs
Pulse game client callbacks
Friends management
Friends in Hello World
The friends API
Customizing friends display
The chat feature
The chat API
Chatting in Hello World
Customizing chat display
Implementing high scores
High scores in Hello World
Skinning the user interface
Skinning for Hello World
Summary
4. Lobby and Room Management
Introduction to lobby and room management
Modeling game room
Game room management
Seating order
Room states
Player states
Kicking out a player
Room types
Audience
Room properties
The lobby screen implementation
Lobby screen in Hello World
Customizing lobby screen
Customizing game room display
Filtering rooms to display
Lobby and room-related API
New game screen implementation
New game screen in Hello World
Customizing the new game screen
New game room API
Designing the game screen
Implementing the game screen
Customizing the game screen
Summary
5. Game Logic
Gameplay implementation
Modeling game states
Game states types
Game states in Hello World
Code walk-through
GameStateSprite class
General flow of events
Game state schema
Adding a new game state
Updating game state
Removing a game state
Game state API
Miscellaneous classes
The Button Effect class
The Slider class
The ShakeEffect class
Summary
6. Multiplayer Game Example: Tic-tac-toe
Running the game from sample directory
The Pulse UI framework
Setting up the project
Getting started: Modeling the game
Project directory structure
Code walk-through
TictactoeGame
Overriding the constructor
Overriding the initNetClient method
Implementing a turn-based game
Sending and receiving player actions
TictactoeSkinner
TictactoeNewGameScreen
TictactoeGameScreen
Initializing the game screen
Displaying player turn
Letting the player make the move
Who won?
Finding the winner
Other screens and features
Lobby screen
Chat
TopTen
Registration screen
Summary
7. Multiplayer Game Example: Jigsaw
Setting up the project
Files in the project
The game graphics
DisplayManager
Managing pieces—Group
The PieceSprite class
Creating a piece
Dragging of pieces
Checking for matches
Multiplayer and networking
Code generation
Screen classes
The JigsawGame class
Overriding the constructor
Overriding the initNetClient method
Server communication
The JigsawSkinner class
The NewJigsawGameScreen class
The JigsawGameScreen class
Summary
8. Card-based Racing Game Tutorial
Implementation
Graphics
The map and frog movement
The step class
The frog class
Card management
Screen management
Class Skin
Class JJF
Class NewGame
Multiplayer design
Card distribution
Frog position
Assigning player color
Schema
Gameplay implementation
Assigning colors
Determining the initial frog positions
Getting the initial three cards
Playing the game
Summary
9. Real-time Racing Game Tutorial
Game design
The game client
The main game loop
The spaceship class
Controlling movement
Skinning the ship
The racetrack module
Mapping coordinates
Loading quadrants
The mini-map class
The Radar class
Implementing items
Detecting collisions
Implementing the shield
Finishing the race
Multiplayer implementation
Designing the schema
The ShipMask class
The ShipPos class
The item class
The ShipWin class
Assigning ship color
Putting items on the map
Ship prediction and interpolation
Winning the race
Summary
A. Introduction to FlashBuilder and AS3
Installing Flash Builder 4
AS2 versus AS3
Exploring Flash Builder 4
Hello World!
Defining a class
Classes—defining game objects
Creating game objects
Variables and properties
Magic numbers and constants
Methods
Property and method access
Taming the inheritance monster
Interface class
Static properties and methods
B. Graphics Programming in AS3
Flash object hierarchy
Object
EventDispatcher
DisplayObject and DisplayObjectContainer
InteractiveObject
Sprite, in detail
Which way is up?
Let the fun begin
Events
Timers
Trace
Embedding pictures
Mouse events
What do we need to handle mouse events for?
How to register for a mouse event
What are the events we can handle in Flash?
Handling mouse events in many objects
Where is the Mouse?
Drag-and-drop
Keyboard events
Arrow key handling: The basics
Arrow key handling: The professional way
Labels, text fields, and sprite buttons
Filters: Adding effects to sprites
Transparency: Playing with the alpha channel
Cool fading screens
Cutting up assets
Index

Flash 10 Multiplayer Game Essentials

Flash 10 Multiplayer Game Essentials

Copyright © 2010 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, Packt Publishing, nor its dealers or distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: July 2010

Production Reference: 1020710

Published by Packt Publishing Ltd. 32 Lincoln Road Olton Birmingham, B27 6PA, UK.

ISBN 978-1-847196-60-6

www.packtpub.com

Cover Image by Vinayak Chittar (<[email protected]>)

Credits

Author

Prashanth Hirematada

Reviewers

Ali Raza

Bruce Wade

Acquisition Editor

David Barnes

Development Editor

Dhwani Devater

Technical Editor

Pallavi Kachare

Copy Editor

Lakshmi Menon

Indexer

Rekha Nair

Editorial Team Leader

Akshara Aware

Project Team Leader

Lata Basantani

Project Coordinator

Jovita Pinto

Proofreader

Aaron Nash

Production Coordinator

Alwin Roy

Cover Work

Alwin Roy

About the author

Prashanth Hirematada, ia the founder of Gamantra, a game technology company focused on Network engines and server platforms. Prior to founding Gamantra in 2006, he was a Chief Architect at Shanda Interactive Entertainment Ltd., where he was responsible for creating a common game development platform for all MMOG initiatives at Shanda. He joined Shanda in 2004 through Shanda's acquisition of Zona, Inc., a MMOG game technology company, headquartered in Santa Clara, USA. At Zona, as a Technical Chief Architect, he was responsible for server-side architecture and implementation of MMOG framework. Prior to joining Zona in 2001, Prashanth worked in various Silicon Valley based technology start-up companies developing software at various levels for well over seven years.

His master's thesis was a distributed implementation of the Message Passing Library (MPI) on a heterogeneous network of workstations including Solaris, HP-UX, OpenStep, and Windows-NT. He received his MS in Computer Science from the California State University, Sacramento, California, in 1994 and his BS in Computer Science from Bangalore University, Bangalore, India in 1992. You can contact him at <[email protected]>.

This book would not have been possible without the constant blessings, encouragement, and belief received from my parents throughout my entire life. I would like to acknowledge the constant support of my loving wife, Jessie who puts up with all my long hours in front of the computer. I also thank Tony Chen and Wilson Wu for their dedicated support with the implementation of GNet and Pulse SDK.

About the reviewers

Ali Raza is a fresh and invigorated aspirant in the field of design, development, and authoring. He became part of the IT field from quite an early age and worked up from designing business cards, flyers, books, websites, digital maps, software interfaces, and almost all design-related things to audio and video editing, animation, and even minor 3D modeling in Autodesk Maya. Later, playing with code became his passion, which compelled him to work in various programming languages including C++, Java SE, Actionscript 3, and PHP.

Ali is pursuing a Master of Science degree in Computer. He is also an Adobe Certified Instructor, Adobe Certified Expert, and Sun Certified Java Programmer.

He is currently a senior developer at 5amily Ltd, a London-based, forthcoming genealogy-related social networking rich Internet application. Previously, he has worked with different national and international advertising, telecommunication, and IT firms.

Ali is authoring Adobe Flex 3 with AIR exam guide from the platform of ExamAids. He is also a regular author in Flash and Flex developer magazine and writes project-based articles, predominantly on Data Visualization, and also loves writing book reviews.

In his spare time, you will find him either engulfed in design and development related books or envisaging the accomplishment of a series of certifications in ACE Flash and ACE Dreamweaver after his masters. You can contact him at <[email protected]>.

I would like to express my gratitude to the packet publishing for bringing unique titles. I would also like to thank to Dhwani Devater and Jovita Pinto.

Bruce Wade got started in software development using Flash early on in his web development career. After going to school for game programming he quickly found himself leveraging Flash for online game development. He works around the clock implementing new Flash games and tools for his website Warply Designed, which is dedicated to independent game developers.

I would like to thank all the authors for the sleepless nights I had reading their books to help improve on my skill sets.

Preface

There are plenty of Flash games on the web, but what about multiplayer Flash games and moreover real-time multiplayer games? Not that many!

The Pulse SDK presented in this book abstracts the standard set of features required for any multiplayer game, which is leveraged throughout the book. As you will see, writing multiplayer becomes quite straightforward with all the standard set of features such as room and lobby management, friends, top ten, registration, among others, all taken care of, allowing the developer to focus only on the game.

What this book covers

The reason that one does not see that many real-time multiplayer games is due to the fact that development and deployment requires a great deal of knowledge about networking and server programming. The developer must also be well aware of the performance bottlenecks along the way when the game is played by several thousands of players at the same time. There is also the issue of dealing with the database in order to save the scores, achievements, friends, and other attributes of a player.

All of these present a high barrier for the developer attempting to write a multiplayer game.

This book presents all the features required for any multiplayer game, their design and implementation. All of the implementation presented in this book is based on the Pulse SDK framework.

Chapter 1, Getting Started, sets up all the required software, namely, Flash Builder 4 and Pulse SDK. We will also fire up the game server and test drive a few multiplayer game samples. The server and the client may be run all on one machine and on separate physical machines. We will go through the high-level design and architecture of a game server and its modules that must be implemented in order to support any typical multiplayer game. We will also see an enterprise architecture that is capable of serving thousands of concurrent players.

We will also touch upon the communication paradigms between game clients, namely peer-to-peer and the client-server architectures. The book follows the client server exclusively.

Throughout the book, we will work at a higher level of abstraction in developing our games. To make things even simpler, we will use a paradigm and a set of APIs provided by Pulse SDK that does not require us to write a single line of code on the server and yet we will implement, turn-based and non turn-based games, puzzle games as well as fast action racing games.

Chapter 2, Game Interface Design, mainly deals with the game UI required by a typical multiplayer game. The UI is leveraged by the Pulse UI framework bundled along with Pulse SDK. From Login screen, lobby screen for creating a new game room, game screen itself. The UI also involves friends display, players display within the game room, chat, and more. The chapter is presented with the Hello World sample in the backdrop. The complete source code for Hello World sample comes with the Pulse package, so you can modify the sample and experiment as you progress through the chapter.

Chapter 3, Avatar and Chat, starts to model our game objects starting with avatar for the game. We will explore what it means to model the game entities. We will learn how to design the avatar in this chapter. We will explore the different kinds of objects (entities) that may be modelled within the Pulse Modeller, also the property types that may be defined within each class (entity). We will also explore the game UI in greater detail as related to the friends display and player display. We will also see how we can customize them from the default behaviour as offered by the Pulse UI framework. You will learn the Pulse APIs that deal with customizing the avatar for the player, making friends, and chat.

Chapter 4, Lobby and Room Management, discusses the central feature to any multiplayer games, lobby and room management. You will continue to use the Pulse Modeller to design the rooms that is required for the game. We will learn about the different room properties and their status during its existence. We will also see how players may join, leave, or kick a player out of a room. Again we will leverage the Pulse API to manage all these features within our game.

Chapter 5, Game Logic, is the heart of the game—the game itself! We will review all the different Pulse game state APIs that deal with implementing the game logic. We will learn how we can design the game states required for the game via the Pulse Modeller and use them through an innovative set of Pulse APIs. We will see how we can use the unique set of APIs that makes any game logic implementation possible without writing a single line of server code.

Chapter 6, Multiplayer Game Example: Tic-Tac-Toe, has the complete source for Tic-Tac-Toe included in the Pulse package; in this chapter, we will do a complete walk-through of the code. Tic-tac-toe is of course a real-time multiplayer game. Multiple clients may connect to the server, create a room or join a room, and play the game. We will go through the different screens such as login screen, lobby, top-ten, and registration. The game is implemented in completeness, and includes friend-making and chat.

Chapter 7, Multiplayer Game Example: Jigsaw walks through a non-turn-based game, a multiplayer jigsaw (unlike tic-tac-toe, which is a turn-based game), where multiple players collaborate to solve the same jigsaw puzzle. The player matching the most pieces wins. The chapter will walk you through in detail to first make the client part work, leaving the multiplayer implementation to the latter part of the chapter.

The walk-through includes cutting any given picture into jigsaw pieces and then managing them during game play. We will learn how to detect the correct matching pieces when they are next to each other. We will also see how all the matched pieces are kept synchronized among all the players that are currently playing the game.

Chapter 8, Card-based Racing Game Tutorial: Jump Jump Frog, is a fun card-based racing game. The chapter will teach you a commonly occurring game implementation, namely card distribution. Here we make heavy use of unique game state concept available in Pulse SDK. Similar to other game implementation tutorials in this book, we will first start with the design of the schema for the game and then we will learn the graphics part of the game client and finally explore the multiplayer implementation.

Chapter 9, Real-time Racing Game Tutorial: AstroRace, teaches to implement the most exciting game genre, a racing game. We will see what we need to design in the schema for the game. The exciting game to play has its challenges set for the developers. In this game, the players will race against one another in a spaceship. Along the racetrack the players will have avoid items that may work against them or pickup items that will help them get faster to the finish line.

Appendix A: This part of the book introduces Flash Builder and coding in AS3. It is a great start for those programmers who are novice AS3 programmers. Here the basic AS3 syntax is presented in a relatively few number of pages, letting starters get proficient in flash programming in a short amount of time. For those of you getting into object oriented programming for the first time, this appendix is a great start.

Appendix B: Having a good handle on the AS3 syntax, this appendix presents the basics of flash graphics programming. It starts with the basic building block, sprite. Readers will also learn to draw and move them around on stage. In depth discussions of essential techniques to any flash game development such as events, timers, event listeners, mouse and keyboard handling are also presented. Interesting things like transparency, added cool effects to sprites are also part of this exciting appendix. Plenty of examples with complete code that will jump start you into your next game development.

Who this book is for

This book is written for game developers that are either starting out with game development in Flash or professional game developers wanting to write the next hot real-time multiplayer game.

If you are starting out new in Flash, you will find the appendix very useful as they teach working with Flash Builder 4, learning to program in AS3, and lots of programming examples required for game programming, including sprite basics, keyboard and mouse handling, and a lot more.

Professional game developers, who are comfortable writing single player games, find it challenging when it comes to multiplayer games, a lot of distracting tasks to take care of before a line of code for the game is written. Armature multiplayer game developers would appreciate the challenges that befall when writing their first game. The book discusses each of the challenges.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book on, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Note

Downloading the example code for this book

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Getting Started

This book is all about creating synchronous multiplayer flash games! Multiplayer games are different from single-player games in that every multiplayer game must have a certain feature set, such as lobby and room management, chat, friend making, etc., not to mention the game itself. This book explores the features and challenges that lie in developing a typical multiplayer game and its deployment. It also presents an object-oriented framework that makes it easy to manage the various user interface screens as well as exchange game state information among players while playing a game.

We begin our journey by downloading and installing the required software: Flash Builder 4 and Pulse SDK.

The reader is expected to have basic AS3 programming skills and a working knowledge of either Flex Builder 3 or Flash Builder 4. Those readers who have recently entered into the world of Flash may find the two appendices useful.Appendix A provides a quick overview of developing AS3-based code in Flash Builder 4 IDE as well as giving a brief overview of AS3 language itself, along with the object-oriented concepts.Appendix B covers Flash graphics programming in AS3 required for gaming in general. The graphics programming discussions are purely AS3 based, as it does not involve the use of creative series (CS) tools. This is excellent for traditional programmers who like to do everything in code.

In this chapter, we will cover the following topics:

Downloading and installing Flash Builder 4Downloading and installing Pulse SDKRunning the multiplayer game sample HelloWorldHigh-level architecture of a multiplayer game deploymentNetwork programming and simple client-server implementation

Development environment

To develop a flash-based multiplayer game as discussed in this book, the following are necessary:

Flash AS3 development Environment, such as Eclipse, Flash Builder 4, or Flash DevelopPulse SDK

In this book, we will use Adobe Flash Developer 4 to manage our game project and to write all the code. However, you may very well use any other IDEs that you are familiar with.

In order to aid us in learning to develop multiplayer games in a relatively short amount of time, we will make use of Pulse SDK throughout this book.

Pulse SDK

Pulse SDK is a commercial middleware product developed by Gamantra that helps speed up the development of a multiplayer game. It offers an innovative API that does not require any server-side programming and offers, among other features, room and lobby management, high scores, in-game registration, chat, and persistence. It allows game developers to work at higher levels, focusing on game implementation rather than working at lower-level networking and server implementation.

Pulse includes a generic server on which you can write a wide variety of multiplayer games. It is the aim of Pulse to simplify the multiplayer game development, and for this reason, we don't deal with the server-side programming. However, for the development of more sophisticated games such as MMORPG and virtual world implementation, which require server-side logic, the versions of Pulse that offer server-side SDK would be more suited. These are not discussed in this book.

Pulse SDK does not offer any additional low-level graphics libraries on top of Flash. However, it does offer a high-level networking API and a generic server. It includes a simple game screen management component, which is ideal for rapid prototyping of Flash-based multiplayer game. The Pulse SDK is a simple yet powerful developer API that integrates with a powerful Pulse deployment platform.

Installing Flash Builder 4

A trial version of Flash Builder can be downloaded from the Adobe site for free at http://www.adobe.com/products/flashbuilder/. Unlike traditional tools from Adobe, such as the CS series, Flash Builder is aimed at traditional programmers who love to write code instead of using designer-oriented tools. The IDE includes a powerful editor with auto-completion features for faster coding, a debugger, and a profiler. The integrated compiler allows developers to produce a compact swf file for immediate deployment.

Downloading the Pulse SDK

To download the SDK, browse to http://forum.gamantra.com and register. Once you register, you will see the download discussion topic on the front page of the forum. Click on it and go to the latest post, which contains the newest version of the SDK.

The SDK is a free trial version that you may use to create a complete multiplayer game. The main difference between a trial version and a paid version is that in a trial version the persistence is disabled and the number of concurrent players is limited to four.

The downloaded file is a self-extracting executable. Once you start the setup file, it will first extract a .jar file within it, which performs the actual installation. For this reason, you need to have Java Runtime installed on your computer prior to firing up the installation.

If you have trouble starting up the installation executable, make sure that you have the JRE installed on your computer and that .jar is associated with java.exe.

Installing Pulse SDK

Installation of Pulse SDK is as follows:

On starting the installation program, you will see the following welcome screen:Clicking Next will take you to a standard UCLA screen.Select the choice I accept the terms of this license agreement and click on Next:In the installation path, which is the next screen, specify where all the contents of the package should be installed on newer Windows systems, such as Vista or Windows 7. Unless you are the administrator, it is best to install on a simpler path, as shown in the next screenshot, and avoid installing it among Program Files or even on the C drive. After setting the installation path, click on Next.On the confirmation window for the installation path, click on OK and this will start installing the files and set the environment variables.The next screen will confirm the shortcuts to add. You may leave them as they are or change them to suite your needs. Clicking on Next will take you to the final screen.

Post-installation checks

To make sure that the installation was successful, you need to verify the directory structure where you installed the package. The root-level folders must look similar to the following:

The bin folder contains several batch files, including one to start the server and another for generating class code files for your game, which we will see in greater detail in this chapter.

The doc folder contains the development guide and API guides for Pulse. The frameworks folder contains the PulseUI package that helps you jumpstart your multiplayer game development by providing you all the standard game screens and their flow management. If you want to quickly build a game prototype, PulseUI will greatly reduce the development time and help you focus solely on your game implementation. The complete source for PulseUI is also available, so you can tweak the parts you want to suite your needs.

The lib folder contains all the swc files that you will need to include in your game project, which we will soon discuss in this chapter. Finally, the sample folder contains the following three samples:

HelloWorldTic-tac-toeJigsaw

For each sample, the compiled swf and source files are available. We will do a walk-through for each of these samples later in the book.

The two environment variables that all of Pulse SDK depends on are GAMANTRA and GNET_JAVA. Upon installation, GAMANTRA should point to the root installation folder and GNET_JAVA must point to the JRE folder, such as C:\Program Files\Java\jre6. If you don't see them set properly for any reason, you may manually set them appropriately.

From here on we will use $ to mean the pulse root installation folder; for example, the tic-tac-toe sample is found in $\samples\tictactoe.

Running the samples

Once you have verified the installation, we are now ready to fire up the server and take the samples for a test drive.

Starting the server

Starting the server is quite easy and there are two ways to fire it up. One way is from the Windows start button; navigate to All Programs | Gamantra | Pulse and select Start Pulse Server. Another way to fire up the server is by launching the batch file $\bin\start_pulsar.bat. This will launch the server in a console window. If you don't see the window, it may be because it is minimized. Make sure you check the taskbar for the new console icon. The console should look similar to the following screenshot:

Starting the client

The free trial version allows you to start one, and only one, sample at a time. If you want to try out another sample, you need to restart the server and then fire up another sample. For example, if you want to try out HelloWorld, you may start multiple client instances of HelloWorld, and next if you want to fire up tic-tac-toe, you need to restart the server and then fire up the tic-tac-toe instances.

To start the HelloWorld client instances, start the server and then open the HelloGame.swf found in the folder $\samples\HelloWorld\bin\hw. You may open it with either an Internet browser or Flash Player. You may also open several instances of them.

To fire up the jigsaw sample, you need to open the file JigsawGame.swf found in $\samples\jigsaw\bin\jig, and the tic-tac-toe sample may be started by opening the file TictactoeGame.swf in $\samples\tictactoe\bin\tictactoe.

A high-level architecture of multiplayer game server

For the curious minds who like to know what happens behind the scenes of a multiplayer game, the following illustration shows how individual Flash-based game clients communicate with one another via the game server.

Simple deployment architecture

The architecture is a simplified one that does not show a typical industry strength deployment with load balancers and separate login server, and others. However, the architecture shown here is still capable of serving thousands of concurrent players:

Depending on the type of game, the performance of a single-server architecture can support anywhere from a few hundred to a few thousand concurrent players. Notice the word concurrent, which means playing at the same time as opposed to the number of registered accounts or some other metrics.

What largely affects and limits the performance is the number of messages that the server has to relay to all the players within the same game room. What constitutes a message could be anything that others need to know when a player does some action. For example, a player picks up an item off the ground, a player chooses a card, the player hits the gas driving a car, etc. A server that's hosting a card game would serve more concurrent players than, for example, a racing game. As you will see in the very last example presented in this book, in a racing game the rest of the players must know at all times where you are, by the second or in a lesser interval. This means that messages must be sent up to the server at rapid intervals and the game server must reply to all other players within the room as quickly as possible.

What was just described is only the gameplay part of messaging. But there are others; for example, when someone created a room, joined a room, chats, etc. These messages also become significant when there are more and more players actively connected to the game server and not necessarily playing the game.

Besides game message communication, there is a lot that the game server must do as a commercial deployment, such as storing the account information of players in a persistent database, managing rooms in a lobby, maybe managing multiple lobbies, monitoring chatting activity, keeping track of high scores, sometimes hosting AI bots to play with players, and validating players' moves and making sure no one is cheating with a hacked client, and so on.

If you are planning to write a multiplayer game, you have to deal with all the previous items and much more as opposed to a single player game, where much of the work is actually dealing with writing the game and nothing else. This point is exactly what discourages many game developers from ever writing a multiplayer game. Fortunately, the situation is not that bad, as there are several commercial APIs or SDKs that take care of all these issues and let you focus on the game. Some well-known SDKs are Pulse, which we will use in this book, ElectroServer, and SmartFox. There are also some open source ones such as Red5. Adobe also has a solution in the market—the Flash Media Server— which you could use to implement games on, but it is mostly designed and suited for hosting video or image-sharing services.

If you were to write a game server on your own, you would need to be very familiar with the network protocols such as TCP or UDP. You also need to know how best to write all the bookkeeping and services on the server side as well as deal with the database.

Enterprise deployment architecture

The simple architecture works well if you are writing one game and your traffic is around a few thousand players. But what if you are planning to write and deploy tens or even hundreds of games? Then how would the server deployment architecture look like that can sustain it?

Referring to the following figure you will notice a few things. There is more than one game server; here each game server is responsible for handling all the events for rooms belonging to a set of lobbies.

You will also notice there are a few other processes such as the session server and the balancer. These processes assist game servers in keeping the load balanced among the game servers, or in Session Server's case, take some of the load off the game server. You will also notice that there is an additional DB called Auth DB so that the authentication traffic can be separated out from the game-related persistence traffic hitting the database. The database itself may be scaled using clustering techniques available in MySQL and other commercial products.

The session server process

These processes serve as the connection point to the player clients. Once the connection is made to the session server, the player will remain connected to the session server until the player logs off. All data packets sent by game clients are received by the session server and are then routed to the appropriate game server. In addition, the session server does all the final data broadcast to the clients. The data broadcast is a fairly heavy duty for a large number of players and increases exponentially with the increase in the number of players.

The rationale for splitting this functionality away from the game server is to free up the CPU cycles on the game server for the game logic. The session server is also the point where the players get authenticated.

There can be as many session servers as the deployment requires. If a session server goes down, all the players connected to the session server will need to log in again.

The balancer process

The balancer is the first point of contact for all player clients trying to log in, the balancer simply responds to the clients with the IP address of the least loaded session server.

There can be as many balancers as required. If a balancer process goes down, a backup balancer could take over without affecting any players.

Server game programming

The multiplayer game programming usually involves writing code at two places, one of them being obvious, the client, where all the action happens for a player and where the player interacts with the game client. The other is the server, where all the validation and synchronization of game states sent up by the clients takes place.

At the heart of game development and deployment, the game logic is what differs from game-to-game; the rest of the functionalities discussed in the next few chapters, such as lobby and room management, registration, friends, and so on, remain constant.

Zero server-side programming

Although game server-side programming makes it easy to write complicated game logic and offers greater security, for simpler and casual games, with Pulse SDK, complete game implementation may be achieved without writing a single line of server-side code specific to the game.

The server in this case is a generic server implementation that provides the basic interaction among player clients. For simple games such as chess, tic-tac-toe, multiplayer jigsaw, and even racing games, the generic server works well. The downside of it is security, because there is no special logic specific to the game to detect cheats by a modified or a hacked client, making it harder but not impossible.

Network programming paradigm

The most basic implementation to communicate between two computers is sending messages between the computers. The networking standard was set in place in the late 70s by the International Organization for Standardization (ISO). Things have not changed significantly since then in terms of the low-level communication protocol. However, the speeds of the hardware that enable such communication have risen significantly, and it has been adopted across the globe.

There are several ways a programmer can tap into these lower-level software layers, the most basic one being sockets. They are the portal through which a computer sends and receives data from another. A distributed memory is an alternative architecture, but is typically suited for computing nodes that are physically close to each other, such as within one computer system. The distributed memory architecture best suited for solving one single problem by massively parallelizing the solution is not suited for long-distance communication to implement a multiplayer gaming.

Remote Procedure Call (RPC) is another programming model that may be adopted to implement multiple client interaction; in fact, Adobe's Media server solutions provides this model. Underneath it, however, the actual data communication happens via the socket implementation. RPC provides an easy-to-use programming model for programmers, but lacks the speed of using direct sockets.