pirates - report - 2004

Upload: dharmesh-malam

Post on 08-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/6/2019 Pirates - Report - 2004

    1/21

    Trading Game Report

    Pirates

    Spring 2005

    Dharmesh Malam

    Rikin Shah

    Chris Roebuck

  • 8/6/2019 Pirates - Report - 2004

    2/21

    P a g e | 2

    CONTENTS Goals ..............................................................................................................................................................................................

    The Game .................................................................................................................................................................................... 3

    Front-End Architecture ......................................................................................................................................................... 5

    Our Application ................................................................................................................................................................... 7

    Game Interface (Front End) ........................................................................................................................................... 8

    Map ......................................................................................................................................................................................

    Dynamic Frame ............................................................................................................................................................... 9

    Non-Dynamic frames .................................................................................................................................................... 9

    Game Interface (Back End) ............................................................................................................................................. 9

    Login and Messages ......................................................................................................................................................... 11

    Backend Architecture .......................................................................................................................................................... 13

    Components ........................................................................................................................................................................ 13

    The Components in More Detailed ............................................................................................................................ 15

    Backend Technologies Used ......................................................................................................................................... 18

    The Database ........................................................................................................................................................................... 20

    Conclusion ................................................................................................................................................................................ 21

  • 8/6/2019 Pirates - Report - 2004

    3/21

    P a g e | 3

    GOALS

    To keep the frontend and backend cleanly separated.

    To give the user an intuitive interface.

    To use standard and portable technology.

    To keep the system modular and extensible.

    THE GAME

    Upon starting the game, the player is given an island and a certain amount of each primitiveresource: wood, gold and food, the starting amount of these resources depends on the difficulty of the game (easy, medium, hard), which is chosen when a player creates a new game. The player canchoose which type of island they would like and there are three types of island: Farming, Industrial,Lumber. Each island type has its own advantages and produces things that are essential for theplayer to survive in the game.

    The farming island produces a certain amount of food per turn and is capable of producing silk,however the player must have reached a certain rank for this option to be available. Food isessential in the game, it is used as fuel which allows the players ships to travel further to possiblytrade with a larger number of players, if food runs out the player will lose an island. Spice is avaluable luxury item that can be traded with other players in return for large amounts of theessential resources.

    The industrial island gives the player jewelry and silk per turn and is used to build new pirate ships.Pirate ships come in 3 different sizes, in increasing order: Sloop Galleon, Frigate. Once again Galleonand Frigate ships will only be available to build once the player has acquired certain ranks.

    Finally the lumber island produces a certain amount of wood and gold per turn. If a players woodsupply runs out, this halts production of any ships or any other products that they were in theprocess of making. Gold is the main currency of the game, and is extremely valuable to the player,this is why it can only be produced once the player has acquired a high rank.

    Due to the nature of the island typ es, and what they can and cant produce, there is a need forplayers to trade amongst each other, either to survive in the game or to gain more resources in a

  • 8/6/2019 Pirates - Report - 2004

    4/21

    P a g e | 4

    view to winning the game. Players can trade with each other by sending their ships to other playe rsislands, and buying any goods from those islands. A player sells resources by setting how much of acertain resource they are willing to allow other players to buy from their island.

    Players can also gain control of a new island if it is not under the control of any other player and if they have enough gold to buy the island. Once in control of a new island, the player can againchoose the type of the island, give it a name and set the amount of resources they are willing to sellfrom that island.

    A ship can only be moved once per turn, resources can only be bought from one island per turn, aplayer can set how much of their resources they are willing to sell at any point during a turn. A turnis signaled when all players have pressed their end turn button, or when a timeout for that turnoccurs.

    A player gains rank according to the amount of turns they have been in the game for. There are 7different ranks, the higher the rank the more options are available to the player, for example only at rank 3 can you build the biggest pirate ship, at rank 4 and above the player can start producing set amounts of gold per turn.

    A log keeps a history of all the players moves and alerts players if any of their resources are low,Messages can also be sent to the user from the game, to alert them to any serious warnings, forexample if they are about to lose an island.

    The object of the game is to reach a certain amount of gold (dependent on the difficulty of thegame), once this amount is reached by someone, that player has won the game. A game can bedrawn if no player has reached the end amount of gold after a certain number of turns. A player canalso win if they are the last man standing after a certain amount of turns. A player drops out of thegame if they lose all the islands that they own.

  • 8/6/2019 Pirates - Report - 2004

    5/21

    P a g e | 5

    FRONT-END ARCHITECTURE

    To enhance the users experience when playing Pirates we set out to create an interface that couldbe directly manipulated, and would therefore be more like a desktop application. To achieve thislevel of interaction we would have to step away from the traditional synchronous HTTPcommunication model. After some initial research we came upon two newly developed websitesproduced by Google (namely Google Suggest and Google Maps ) that were highly interactive. It was these sites that led us to our use of AJAX .

    AJAX is a shorthand term for Asynchronous JavaScript + XML , and isnt a technology itself but simply a collection of existing technologies. Neither is it a new concept, it is often considered theweb equivalent of the Model View Controller (MVC) design pattern, where the AJAX engine is

    the controller between the client side interface and the server side database. The only advance in AJAX that has led to its wider application is its increased cross -browser compatibility.

    As can be seen below, AJAX seeks to alter the traditional web application model by adding amediator between the client and the server, often referred to as an AJAX engine. This engine issimply a set of JavaScript functions and is responsible for handling user requests and dynamicallyupdating the user interface accordingly. Where possible, the engine will process the requests itself,but in cases where it cant, it will send server requests asynchronously, therefore the user is neverleft waiting for a page to load up.

  • 8/6/2019 Pirates - Report - 2004

    6/21

    P a g e | 6

    As an alternative to an AJAX based application, we could have used either a Flash movie or a Java applet . There were two reasons why the choice was simple, firstly, by making use of the existingW3C standards our application would be able to run on any modern browser without the need fora proprietary plug-in such as a Java or Flash . Secondly, the other options would have led to amore frustrating user experience because they would be left waiting for it to load, and would havelimited control over the browser when playing the game because applets and Flash animations

    override the browsers settings. Through careful consideration when making this choice we havebeen able to achieve all of the interaction of the alternatives, without any of the disadvantages.

  • 8/6/2019 Pirates - Report - 2004

    7/21

    P a g e | 7

    OUR APPLICATION

    An AJAX application consists of five elements, which can be split into the Dynamic- HTML(DHTML) components, and the communication components.

    DHTML, like AJAX , is simply a term for the collective use of other technologies, namely apresentation standard, Document Object Model ( DOM ) and a scripting language. In DHTML, thescripting language uses the DOM to access and manipulate web page elements dynamically, as wellas accessing and manipulating the style sheet properties. This means pages can be created on-the- fly without the need for any HTTP requests for a new page.

    We have used CSS, DOM and JavaScript for our DHTML components. Using CSS has allowed us

    to separate the formatting information from the data, thus reducing the volume of traffic betweenthe server and client because the style sheets can be sent just once and cached. Furthermore, as CSS properties can be accessed using the DOM standard, reformatting an entire page is both easy andcross-browser compatible.

  • 8/6/2019 Pirates - Report - 2004

    8/21

    P a g e | 8

    GAME INTERFACE (FRONT END)

    To make the interface as intuitive as possible, we have divided it into a frameset as per the diagram

    below:

    We felt that this divide would be most efficient in terms of screen space used because any

    information that is constantly required, namely the game map, the player stats & option buttons,and the game log are constantly displayed without any obstructions. All of the user selectablecontent, such as information about other players, ships, islands etc. are shown dynamically on oneside and consume only 25% of the screen collectively.

    The DHTML used in each frame is briefly detailed below:

    M AP

    In our a ttempt to create a directly manipulated interface, we have made the map and the playersships draggable, through the use and extension of a JavaScript drag-drop library. To complement this function an image map has been used to detect where that object has been dropped.Furthermore, the players ships and islands have mouseOver events to trigger the display of dynamic content in the adjacent frame.

    These technologies are advantageous for several reasons, firstly, the map area can be larger than

  • 8/6/2019 Pirates - Report - 2004

    9/21

    P a g e | 9

    the available screen space and so information is clearly visible. Secondly, as with icons in a WIMP interface, ships are dragged intuitively to the desired island, and the map automatically scrolls if theship is being moved off the page. Finally, through use of the image map and JavaScript we canensure the ship was moved to a valid island before sending a HTTP request, hence the validation is

    performed in the AJAX engine reducing server traffic.

    D YNAMIC F RAME

    In this frame, we have customised a sliding menu library so the user can hover the mouse over aparticular tab to display the desired content. The navigation between these menus is intuitive inthat clicking on a particular item inside a menu will go to the next level to display more detailedinformation, furthermore, navigation from a lower level menu to higher one can be done by a singlemouse click.

    Within these menus there is also dynamic content, such as sliders to select the number of items tobe traded or transferred. Similar to the draggable ships, these sliders also have client side validationfunctions in the AJAX engine, for example, if the player tries to buy more goods than they havemoney or ship capacity, the slider automatically returns to a valid position again this reducesserver traffic for validation requests.

    N ON -D YNAMIC FRAMES

    The log and player stats frames have a much simpler implementation than their dynamic siblings,

    but are key to the game-play because they provide up-to-date information that is constantlyrequired saving time on navigating the menus for them.

    GAME INTERFACE (BACKEND)

    The main communication component of the engine is the XMLHttpRequest object which sendsrequests asynchronously to the server. This component is browser specific and so we have includedan implementation for both Microsoft and Mozilla based browsers. The overall structure of theasynchronous server request is as follows:

  • 8/6/2019 Pirates - Report - 2004

    10/21

    P a g e | 10

    To support the extensive interaction and dynamic nature of the user interface, we needed to ensurethe component to transform the XML from the server was efficient and robust. It is for this reasonthat we make use of XSL style sheets, these are lightweight files that can be used to extract information from the raw XML documents and process the data, using in built loop and conditionalfunctions.

    To make use of an XSL style sheet, an XSLTProcessor object is required, and is passed an XSL stylesheet and loaded with the XML document from the server, it then returns a DOM fragment whichcan be appended to any DOM node we choose. The

  • 8/6/2019 Pirates - Report - 2004

    11/21

    P a g e | 11

    XSLTProcessor can also be passed parameters using the setParameter(null,name,value) method, toprocess the same document depending on a parameter value.An example XML document and stylesheet are below:

    This style sheet would produce a table with two columns- of each of the title artist pairs. Other built in functions are , and .

    LOGIN AND MESSAGES

    Login scripts were written as a mixture of JSP for server side scripting, JavaScript for client sideform validation and html with CSS for layout and design of the pages. These pages are specificallydesigned for an 800x600 display, all forms use the post method of sending parameters and areaccessible to the user they can be filled out using just the keyboard. Background images weremade originally in Macromedia Fireworks.

  • 8/6/2019 Pirates - Report - 2004

    12/21

    P a g e | 12

    When each user logs in a unique session is created, 2 users cannot log in with the same session id,usually this means only one player per machine (or browser) can be logged on at the same time. Auser is identified throughout these pages by their unique playerid which is implicitly assigned to

    them when they register for the first time, this is stored as an attribute in the session.

    The messaging system allows players to send messages to each other during a game and outside of the game and to keep track of the messages they have sent.

  • 8/6/2019 Pirates - Report - 2004

    13/21

    P a g e | 13

    BACKEND ARCHITECTURE

    The back end was architected to give a clean separation from the front-end. Essentially allcommunication from the front-end is directed toward one Pirate Engine servlet which thenprocesses the request. The front-end gives parameters in the request, such as game id and player id,and then redirects the request to a JSP page which carries out the request and outputs formattedXML which is the result of the request.

    The servlet parses the GET parameters to do general error checking, such as seeing if a game exists,and the request is one that exists. It then redirects the page to the specific JSP page which handlesthe getting the ship information. This JSP page does more specific error checking, and then carries

    out the database query to get the information. The query might be an SQL statement, or a storedprocedure call. The database fetches the information, making sure concurrency is handled properly.It then iterates over the results and creates XML to structure the information, which is finally what is returned. The front-end then can parse this XML documents and extract the appropriateinformation and present it to the user.

    COMPONENTS

    The main visible component of the backend is the PirateEngine servlet which provides a unifiedpoint of access to all requests from the front-end, and is cleanly separated and hence not dependant on the front-end implementation. This keeps in line with one our goals in this project, to keep the

    subsystems modular and independent. It also makes it very easy to add new requests as we onlyhave to write a separate JSP handling the request, and add a redirect to it in PirateEngine .

    Then there are sets of JSP pages which handle the various requests. The requests can be groupedinto various categories. First there are the administration pages which allow the user to create andjoin a game. Then there are the information pages which retrieve various statistics from the game,such as location of all ships, players gold etc. The result is always raw data in XML which are then

  • 8/6/2019 Pirates - Report - 2004

    14/21

    P a g e | 14

    processed by the user interface presenting the game state.

    Another set of functions are the action pages, these are actual events carried out by the user, such

    as moving a ship, buying products. The structure of these pages is generally to check that the actionis permitted, i.e. you own the ship you are trying to move, and then update all relevant tables of thedatabase using transactions and stored procedures where appropriate. They return a statusdepending if the request was finished.

    Managing turns is done by another set of JSP pages. The user has a time limit for each turn, if thetime limit has passed and the user has not ended his/her turn, then the user is automatically loggedout of the game. This means everyone else playing the game will not wait indefinitely for the end of the current turn. There is a request which tells the front-end if the new turn has started. This iscontinually polled to check if the new turn has started. Also requests carry out events likes leaving agame, quitting a game. A stored procedure, which is activated on the end of each users turn, updates

    the users state. It increases the product of all islands producing items, creates new ships if theenough turns have passed, increases rank if so many turns have occurred, makes islandsindependent if it cannot produce enough food, etc. It carries out all the game functions. If the userhas lost all their islands then user has lost, and has all his resources deleted from the game. Also thefact they lost that game is stored and hence they cannot join that game again.

    A Java library ( dbQuery ) was written to interface with the database. This library made sure theconnection was properly created and closed, and also provides a clean way to get results and fault tolerance. Just by including this library at the top of each JSP page, access to the database is simpleas only a query sting is needed for example ResultSet rs = doQuery( Select * from game); .dbQuery also makes sure if an error occurs, i.e. the database rejected the connection as if was busy,it tries again and again until it hits a limit when it reports that error by throwing an Exception.

    The database is running on Postgres , and it maintains the state of the systems. It can allowmultiple games, multiple users, users in many games, multiple maps, messaging, logging of thegame events etc. It also makes sure concurrent access to the database does not invalidate the data.

    The data can be manipulated in a high level format with stored procedures, which are used whenactions will require many accesses to the database. It gives performance advantages because aconnection between the database and the Tomcat server (discussed below)do not need to bemaintained.

    The web server is Tomcat , which essentially is a normal html web server, but with Java built in soit can host servelets and process JSP pages. It creates contexts of the JSP pages to create thewebsite.

  • 8/6/2019 Pirates - Report - 2004

    15/21

    P a g e | 15

    THE COMPONENTS IN MORE DETAILED

    The main gateway to the back end is Pirate Engine, this is given parameters via the standard HTTPGET method, i.e. host/PirateEngine?playerid= 1 &gameid= 1 .

    Pirate engine checks:

    1. gameid exists2. user in game3. request is valid4. session exists

    Then it redirect to the appropriate page if these first level checks were ok. PirateEngine is a Javaservlet, and produces no output. It only redirects to another page which can service the request

    Errors are handled in a special way. Basically if an exception occurs, i.e. the database is down, ortrying to buy more things than gold allows, it is very bad from the perspective of the user if they seethe raw exception error message. Hence all errors are caught and then formatted nicely in XML.Hence the code for each JSP page has the general structure given below.

    Dummy JSP page showing error handling

    Handle errorsdepending on type

  • 8/6/2019 Pirates - Report - 2004

    16/21

    P a g e | 16

    This means any error occurring stops the production of the XML document and inserts a new

    section contains a description of the error. The front end parses the document to see if an tag is contained, if so then if the error type can be handled by the front end, i.e. it trying to buy toomuch, then it asks the user to buy less, else if it cannot do anything, then it tells the user there is afault and formats the error description.This integrated error system not only makes the user interface more usable for the end user, it alsomakes programming the client and back end much easier.JSP pages make formatting and creating the XML documents quite easy from the database query.The pages also have a very similar structure so adding new ones is very easy.

  • 8/6/2019 Pirates - Report - 2004

    17/21

    P a g e | 17

    Each JSP page had a very similar structure, below is an example dummy JSP page

  • 8/6/2019 Pirates - Report - 2004

    18/21

    P a g e | 18

    Each JSP page outputs XML, does validation, and selects data or updates the database. The tablebelow gives a brief description of all the actions

    Request Description

    startinfo Set playing to true for gameworldinfo Get all current information from game such as ship locations, island owner etc.Done at the beginning of each turn.

    Playerinfo Get detailed information for every player in the game,Islandhold Get detailed information about a speciafied island, ie what is can sell and at

    what priceShiphold Get detailed information about a specified ship such as how much cargo it has.Products Get information about what products can be made, how much resource per

    turn it requires and how many turns are neededRanks Get a information about all possible ranks and how many turns are needed to

    reach it Isturn This method is polled by the front end. It return true or false depending if

    everyone has finished their current turnEndturn This is called when a user has ended their turnEndgame This is called when a user wants to leave a game but still return later, ie save

    stateQuitgame This is called when a user want to quit a game, and so have their ships, islands

    deletedMove Moves specified ship to specified islandBuy Buys a specified amount of goods from an island to a shipSetprice Set priced for goods on any islandTransfer Transfer brought good to own islandsColonize Used when user moves to an uninhabited island.Creategame Called from login page, to initialse a new game

    Joingame Called from login page to join an existing gamegamelog Returns specified number of items from the log for that game and user

    The front-end calls the above methods depending on what the user does, and formats the outputsfrom them. This continuous requesting and updating is what creates the game experience.

    BACKEND TECHNOLOGIESUSED

    Xml was chosen to be the format to send information between the front-end and backend because it

    is perfectly suited to the job. It is designed to be extensible, so we can customise it to ourapplication, is widely supported so parsing it is very easy, i.e. the JavaScript in the front end can do getElementsById( Ship), and an array of all the ship objects are returns from the XMLdocument. It is also human and machine readable, easy to create with JSP pages, and provides avery clean separation between the front and back end. The back end is written to produce XML in apredefined format, the front-end is written to parse XML documents of a predefined format, the endresult is that both can be developed independently using methods and technologies suited best for

  • 8/6/2019 Pirates - Report - 2004

    19/21

    P a g e | 19

    each, and still work together perfectly. The back end outputs data, and the front end does allformatting using client CPU cycles to dynamically create the HTML page. This takes some load off the server, and improves the experience for the user as the game is faster and more interactive.

    Other choices included text files, which mean writing our own parser which is hard and errorprone. A more conventional way would be to make the JSP pages actually produce the userinterface. So the JSP page gets the information from the database and instead of creating XML torepresent this information for the front end to format, it does the formatting itself creating anHTML page for the user. This works fine but is not clean as the front and back end are not separated, and also provides a bad user experience as pages have to be refreshed and regeneratedevery time a request is made. With our design the http communication is asynchronous, i.e.happening in the background so the page gets dynamic information but does not need to refresh.

    We chose Java servlets and JSP because it is a highly portable and wide spread language and isdesigned for high dynamic web sites. It also lets us use our previous java knowledge. Thepredefined objects contained within JSP make typical web oriented tasks such as redirects, settingsessions, get parameters very easy. Using Java also meant we had to jdbc to connect to thedatabase.

    We could have used ASP.NET with ADO.NET with would have also provided a very similarenvironment, but less portable and also less supported by CSG. PHP and PERL for CGI can havealso been used but creating rapid applications in either is harder from our experience. For us JSP fit

    our design perfectly and hence was used.

    The database was Postgres . On the database we have used SQL to create and initialise the tables.SQL is also used to query and update the database. We have created rules to protect the integrity of our data on updates, but have also used validation on the front end and in the JSP. We have writtenstored procedures for complicated actions likes updating state on endturn in PLJpgSQL . This isthe supported language of Postgres and provides a high level platform to manipulate data stored.

  • 8/6/2019 Pirates - Report - 2004

    20/21

    P a g e | 20

    THE DATABASE

    The structure of the database is given below

    Table DescriptionMembers Information about all users, their name, password, etcDifficulty Describes how each difficulty affects the game, ie starting goldShiptypes Describes the different ships, ie max cargo,Ships The current state of all ships for each game, ie x,y co-ord, ownerShiphold For each ship in each game, how much food, silk, etc it is storingMessages Contains all messages stored in systemMap Information about the map in the game, ie co-ords of each harbourIslandstate For each island in each game describe who owns it, what it is producing etcIslandhold For each island in each game describe what it contains, ie how much of each

    product

    Islandtypes Describe what each island can makeGame Maintain state of all games, what users are playing, how much gold etcRank Information about all ranks, and how many turns are need to get next rank Products Describe all products and how many turns are needed, and how much resource

    per turngamelog Log events in game, this is shown to user in real time ie warnings, if they have

    lost an island. Broadcast to everyone if someone loses.

    Various functions where written in PL/pgSQL where it would have been convoluted to program inJava, with submitting each request. The stored procedure provides a performance boost as there is

    less communication via JDBC, and also makes it easier to write complicated SQL updates.Creategame and endturn were written as stored procedures as they both require many accessesto the database.

    Rules were used to restrict modification to the data preserving the integrity of the data.

  • 8/6/2019 Pirates - Report - 2004

    21/21

    P a g e | 21

    CONCLUSION

    The system works very well and does everything specified. It handles concurrent access to thesystem, and presents and clean modular set of components which can be easily extended.

    The system could be improved in a few ways if we had extra time. Firstly SOAP could be used tosend requests instead of HTTP GET. This would give an XML format to giving requests as well asreceiving responses and would be easier to extend. But the extra complexity is not worth it for now

    The database could use more stored procedures and triggers to make things happen automatically,like a auto generated hall of fame.

    The java code be more efficient and robust by using connection pooling, where a set of connectionsare kept by the servlet and shared. Also caching of results in the java code could prevent unnecessary accesses. Also more of the code could be componentised into beans to makeextensions to the game easier.

    Also if given more time we would make more use of dynamic features, such as tool tips to displayinformation dynamically on the map. We would also have several maps to chose from so as toprovide a more varied gaming experience to the user and would include the ability to travel not just from island to island but also within the oceans allowing for pirate captures. Furthermore, asDHTML requires a modern browser we would create a downgraded interface for browsers that cant support it.