60
Project Report on “iSnake - Multiplayer Intelligent Snake Game” http://isnake.sourceforge.net     Submitted to Inter College Undergraduate Project Competition KUCC Software Meet 2008 Mar. 7, 2008 by Abhishek Dutta   Jitendra Harlalka  Suraj Sapkota [email protected] [email protected] [email protected] cell: 9841559669 cell: 9803395335 cell: 9841579381

isnake_kucc2008_report.pdf

Embed Size (px)

Citation preview

  • ProjectReport

    on

    iSnakeMultiplayerIntelligentSnakeGamehttp://isnake.sourceforge.net

    Submittedto

    InterCollegeUndergraduateProjectCompetition

    KUCCSoftwareMeet2008

    Mar.7,2008

    by

    AbhishekDutta JitendraHarlalka SurajSapkota

    [email protected] [email protected] [email protected]

    cell:9841559669 cell:9803395335 cell:9841579381

  • TableofContents

    1 Acknowledgment..................................................................................................................................1 2 Abstract.................................................................................................................................................2 3 Objectives.............................................................................................................................................3 4 Programming Environment...................................................................................................................4 5 Methodology.........................................................................................................................................5

    5.1 iSnake Client Application..............................................................................................................6 5.1.1 Client Encoder/Decoder.........................................................................................................6 5.1.2 Client Network Interface........................................................................................................6 5.1.3 Input Handler..........................................................................................................................6 5.1.4 Game Field Matrix.................................................................................................................7 5.1.5 Game Field Canvas.................................................................................................................7 5.1.6 User Interface Components....................................................................................................7 5.1.7 Game Controller.....................................................................................................................7

    5.2 iSnake Game Server......................................................................................................................8 5.2.1 Server Encoder/Decoder.........................................................................................................8 5.2.2 Server Network Interface........................................................................................................8 5.2.3 Virtual Game Field.................................................................................................................9 5.2.4 Player Information Manager...................................................................................................9 5.2.5 Random Number Pool............................................................................................................9 5.2.6 Status Server...........................................................................................................................9 5.2.7 Server Core...........................................................................................................................10

    5.3 Intelligent Autonomous Opponent Snakes..................................................................................10 5.4 iSnake Game Server Manager (GSM) @ SF.net.........................................................................13

    6 Project Management...........................................................................................................................14 7 Documentation....................................................................................................................................16 8 Limitations..........................................................................................................................................16 9 Future Enhancements..........................................................................................................................17 10 Conclusion........................................................................................................................................17 11 References.........................................................................................................................................18 12 ANNEX A: Blackmamba path finding algorithm 13 ANNEX B: Viper path finding algorithm 14 ANNEX C: Program Flow 15 ANNEX D: Inter Snake Communication Protocol (ISCP)

  • 1 Acknowledgment

    WeoffergratitudetoprojectsupervisorAsst.Prof.JayaramTimsina(DeputyHOD,Dept.Of

    Electronics&ComputerEngineering,IOEPulchowkCampus)forguidingusthroughoutthe

    project.

    We would like to thank all those forum members at JavaGaming.org

    [http://www.javagaming.org]andSunJavaForum[http://forum.java.sun.com] whoreplied

    toourendlessquerieswithoutanycomplain.

    We acknowledge the creators of Quantum Random Bit Generator Service [QRBG

    http://random.irb.hr],whichprovidesourgameserverwithhighqualityrandomnumbers.

    1

  • 2 Abstract

    Thisprojectaimstobringthefunandsimplicityofsnakegamewithsomenewfeatures.Itwill

    includecomputercontrolledintelligentopponentswhoseaimwillbetochallengethehuman

    players.Itwillalsohavethemultiplayerfeaturethatwillallowmorethanoneplayerstoplay

    thegameoveranetwork.

    This project explores a new dimension in the traditional snake game to make it more

    interestingandchallenging. Thesimplicity of this gamemakes it anideal candidatefora

    minor project as we can focus on advanced topics like multiplayer functionality and

    implementationofcomputercontrolledintelligentopponents.

    2

  • 3 Objectives

    Thisgameaimstochangethewaypeoplethinkoftraditionalsnakegame.Itwillofferthe

    experienceofcommercialmultilayergamestotheplayerretainingthesimplicityoftraditional

    snakegame.

    Themajorobjectivesofthisprojectare:

    Createasnakegamethatwillhaveallthefunctionalityoftraditionalsnakegames.

    Introducemultilayerfunctionalityinthegamethatwillallowseveralplayerstoplaya

    gamesimultaneously.Itshouldbeabletogivetheexperienceofarealtimemultiplayer

    gametotheplayers.

    Introducecomputercontrolledintelligentopponent(uniquefeatureofthisgame)to

    makethegamemorechallengingandinteresting.Themovementandactionofthese

    intelligentopponentswillbecontrolledbycomputerwhoseaimwillbetoeatthefood

    beforehumanplayerscaptureit.

    3

  • 4 ProgrammingEnvironment

    Weusedseveralopensourcetoolstodevelopthisproject:

    Netbeans5.5IDE

    All the developers of iSnake teamused Netbeans IDE for the development of this

    project.

    Inkscape0.45andGimp2.2

    ThesegraphicsdevelopmenttoolswereextensivelyusedforthedevelopmentofUser

    Interfacecomponents.Theillustrationspresentedinthisreporthavealsobeenprepared

    usingtheseopensourcetools.

    Gnuplot

    Thedataobtainedduringprofilingoftwopathfindingalgorithmsviz.Blackmambaand

    Viperwasplottedusinggnuplot.

    OpenOfficeWriter2.2

    AlltheprojectdocumentsandthisreportwerepreparedusingOpenOfficeWriter2.2.

    WiresharkNetworkTrafficAnalyzer0.99.6

    DuringthedevelopmentofiSnakeGameServerManager(GSM)@SF.net,Wireshark

    toolwasusedtoanalyzethenetworktraffic.

    4

  • 5 Methodology

    iSnakeisamultiplayerversionoftraditionalsnakegame(popularamongcellphonegamers)

    withcomputercontrolledintelligentopponentsthatchallengesthehumanplayers.

    Theplayerwhohoststhegameserveriscalledlocalplayer.TheiSnakeClientApplication

    andGameServerruninseparateexecutiondomains.TheiSnakeClientApp.forlocalplayer

    communicateswiththegameserverthroughnetworklayer,justlikeotherremoteplayers,as

    showninillustration1.

    ThecompleteiSnakeapplicationisdividedintofourmajorcomponents:

    iSnakeClientApplication

    iSnakeGameServer

    IntelligentAutonomousOpponentSnakes

    iSnakeGameServerManager(GSM)@SF.net

    5

    Illustration 1: iSnake block diagram

  • 5.1 iSnakeClientApplicationiSnakeclientapplicationreferstotheapplicationusedtoplaysnakegame.Aplayerjoins

    analreadyexistingiSnakegameserverusingthisapplication.

    ThemaincomponentsofiSnakeClientapplicationare:

    5.1.1 ClientEncoder/Decoder

    Thismoduleperformstheencodinganddecodingofmessagesleaving/arrivingthe

    clientnetworkinterfacemoduleusingtheprotocolstandarddescribedinANNEXD:Inter

    SnakeCommunicationProtocol.

    5.1.2 ClientNetworkInterface

    ItprovidesaninterfacetotheGameControllermoduleforcommunicationwiththe

    game server hosted at local/remote computer. It is responsible for triggering of

    appropriatemethodsofGameControllerwhenmessagefromGameServerisreceived.

    5.1.3 InputHandler

    Itmanagesthetaskofsamplingkeystrokesfromlocalplayerandforwardingitto

    GameControllerwhenrequested.Itmaintainsaqueueofsize2sothatquickkeystrokes

    arenotlost.Itisactiveonlywhenthegameisinrunningmode.

    6

    Illustration 2: Block diagram of iSnake Client Application

  • 5.1.4 GameFieldMatrix

    GameControllermaintainsthecompletestateofthegameusinggamefieldmatrix.

    Itisa2Darrayofsize58x58(equaltothegamefielddimensions).Eachgamefieldobject

    hasauniqueidentifierinthegamefield.GameControllerupdatesthecellsofthismatrix

    ineachcycletoregisterthechangesthatoccurinthegame.

    5.1.5 GameFieldCanvas

    Itrepresentsthegamefieldasseenbytheplayer.GameControlleranalyzesthe

    gamefieldmatrixineachcycleandupdatesthegamefieldcanvastorepresentthestateof

    gameinthatgamecycle.DoubleBuffering[usingjava.awt.Canvas.createBufferStrategy()]

    hasbeenimplementedtoavoidflickeringofgamefield.Eachblockinthegamefieldhas

    dimension10x10pixels.

    The update of game field canvas occurs in the way similar to the refreshing

    techniqueofacathoderaymonitor.Thegamefieldmatrixandgamefieldcanvasare

    updated in separate thread. Theupdateof game field canvas starts byscanningeach

    columnofthe1strowinthegamefieldmatrix,then2ndrowandsoonuptothe58throw.

    Thegamefieldisrefreshedtwiceduringeachgamecycle(tworefreshcycleforgamefield

    canvas for each game cycle). This is done make the movements in the game field

    smoother.

    5.1.6 UserInterfaceComponents

    Thismoduleincludesallthecomponents,exceptgamefield,visibletotheplayer.

    Thelookandfeelofdefaultswingcomponentshavebeenoverriddentogivethefeelofa

    game to the players. MIT OCW's course1 [6.831] User Interface Design and

    Implementationwasveryhelpfulduringdesignofmostoftheuserinterfacecomponents

    ofthisgame.

    5.1.7 GameController

    ItisthemostimportantcomponentoftheiSnakeclientapplication.Itcoordinates

    theworkingof all theothermodules in theapplicationandhandles all themessages

    1 See References [Website]

    7

  • receivedfromthegameserver.GameControllermaintainsthegamecyclewhenthegame

    isrunning.Thisgamecycleissynchronizedwiththegamecycleofthegameserver.Allthe

    updatestogamefieldmatrixaredoneduringthiscycletime.Afterexpiryofeachgame

    cyclethegamefieldisrepaintedtoreflectthechangesinthegamefield.

    5.2 iSnakeGameServeriSnakegameserver handles the multiplayer feature of this gameandallows multiple

    iSnakeclientapplicationstoplaythegamehostedbythatparticulargameserver.

    ThemaincomponentsofiSnakeGameServerare:

    5.2.1 ServerEncoder/Decoder

    Thismoduleperformstheencodinganddecodingofmessagesleaving/arrivingthe

    servernetworkinterfacemoduleusingtheprotocolstandarddescribedinANNEXD:Inter

    SnakeCommunicationProtocol.

    5.2.2 ServerNetworkInterface

    It providesaninterfaceto theServerCoremodule for communicationwiththe

    remote/local players of the game being hosted. It is responsible for triggering of

    appropriatemethodsofServerCorewhenmessagefromremote/localplayersisreceived.

    8

    Illustration 3: Block diagram of iSnake Game Server

  • 5.2.3 VirtualGameField

    Gameservermaintainsthestateofthegameusinga2Darrayofsize58x58(similar

    tothatusedbyGameControllerreferto5.1.4).

    Itismaintainedbythegameservertocheckwhetherthefoodhasbeeneatenand

    whetheranyplayerhascollidewiththewall.Itmaintainstheheadcoordinate(notthe

    coordinatesfortails)ofeachplayer.Theheadcoordinateofplayersismovedineachgame

    cycleandcheckedforthepresenceofwall/foodinthatcoordinateposition.ServerCore

    generates corresponding event (collide or food eaten) and all the active players are

    informedabouttheeventinthesamecycle.

    5.2.4 PlayerInformationManager

    It manages the information about the players involved in the game. Player

    information like name, location, score, snake's starting position, snake color, etc are

    maintained.Anewentryisaddedwheneveranewplayerjoinsthegame.Similarly,when

    theplayerleavesthegame,itisremoved.

    5.2.5 RandomNumberPool

    Game server maintains a buffer of random numbers obtained from Quantum

    RandomBitGeneratorservice[QRBGhttp://random.irb.hr].Thisgivesthegameserver

    accesstotruerandomnumber.Theserandomdataisusedtogeneratethepositionoffood

    andthestartingcoordinateofeachplayer'ssnake.

    If the random number service is unreachable pseudo random numbers are

    generatedusingjava.util.RandomclassprovidedbyJava.

    5.2.6 StatusServer

    Statusservermaintainsalltheinformationrequiredtoreplythecurrentstatusof

    the game server. The service of status server is utilized by iSnake Game Server

    Manager(iSnakeGSM)2hostedathttp://isnake.sf.net.Theresponseofstatusserverisa

    wellformedXMLdocumentthatisparsedbyiSnakeGSMtodisplayinformationabout

    thegameserverinthewebsite.

    2 Refer to 5.4 iSnake Game Server Manager (GSM) @ SF.net

    9

  • AtypicalresponseofStatusServerisgivenbelow:

    124.41.228.219

    9669

    5

    Waiting

    5.2.7 ServerCore

    ItisthemostimportantcomponentoftheiSnakeGameServer.Itcoordinatesthe

    workingofalltheothermodulesintheapplicationandhandlesallthemessagesreceived

    fromtheremoteplayers.

    When the game is in "Waiting" mode, Server Core provides the facility of chat

    messagingtothegameplayers.Duringthisstatenewplayerscanjointhegame.

    Whenalltheplayershavesentsignaltostartthegame,theServerCorechanges

    state to Running mode. If a newplayer tries to join the game, it receives a NAK

    response.Inthismode,ServerCoremaintainsagamecycletimeduringwhichitreceives

    themovementcoordinates(intermsofdeltaXanddeltaY)fromtheplayers.Ifaplayer

    doesnotsendanypacketduringthiscycletime,serverconsidersthemovementcoordinate

    sent in last cycle for thecurrentgamecycle. Afterexpiryofcycle time, gameserver

    broadcastsapacketcontainingmovementcoordinatesofeachplayertoall theplayers

    activeinthegame.Thegameserveralsochecksifanyplayerhaseatenthefoodorifany

    playershavecollidedtothewallineachcycle.

    5.3 IntelligentAutonomousOpponentSnakesThesearecomputercontrolledsnakes,inthegame,whoseaimistochallengethe

    human players. We have two implementations of path finding algorithms to create

    intelligentautonomousopponentsnakes. Thesealgorithmsreturntheshortest possible

    10

  • pathfromgivensource(S)andtarget(T)coordinatepairconsideringtheobstacles(if

    any)presentinthegamefield.Thecodename3forthesetwoimplementationsare:

    Blackmamba(refertoANNEXA)

    Viper(refertoANNEXB)

    Adetailed paper describingthealgorithmusedby these two implementation is

    presentin ANNEXAandANNEXB.Themoduleimplementingthesetwopathfinding

    algorithmeasily fits into theexistingdesignof iSnakeClient Applicationas shownin

    Illustration4

    Toknowwhichof the two implementations performbetter, weprofiled themusinga

    simpleJUnittestandtheresultswereplottedusinggnuplot:

    3 Named after two popular species of venomous snakes

    11

    Illustration 4: Module implementing two path finding algorithms replaces the Input Handler module of standard iSnake Client application.

  • Illustration 6: Length of path returned by the two path finding algorithms

    Turnaroundtimeplot

    Thetimeelapsedbetweentheinstantofsupplyingthe(source,target)coordinate

    pair(S,T)tothealgorithmandtheinstantwhenitreturnsapathforsupplied(S,T)pairis

    calledturnaroundtime.Fromtheplotofillustration5,itisclearthattheturnaround

    timeforViperisalwayssmallerascomparedtoBlackmamba.

    PathLengthplot

    Thelengthofpath(computedbycountingthenumberofgamefieldcoordinatesin

    the path) returned by the two path finding algorithms is depicted by the plot of

    illustration6.ItisclearfromtheplotthatViperimplementationresultsinsmallerpaths

    (andhenceefficient)ascomparedtoBlackmambaimplementation.

    NOTE:Thevalueofturnaroundtimeandpathlengthforthecoordinatepairs5,7,8have

    negativevaluesforBlackmamba.Thissuggeststhatthealgorithmwasnotabletocomputea

    pathforgiven(S,T)pairingiventimeoutperiod(250msforthistest).

    12

    Illustration 5: Turn around time for two path finding algorithms

  • 5.4 iSnakeGameServerManager(GSM)@SF.netiSnakeGameServerManager(iSnakeGSM)hostedathttp://isnake.sf.netisusedto

    managealltheinformationaboutiSnakegameserversbeinghostedovertheInternet.

    TheiSnakeGSMhasbeendevelopedusingPHP.JavaWebStarttechnologyhasbeen

    usedtodeployiSnakeapplicationatourwebsitewhichautomaticallydownloads/installs

    iSnakeapplicationanditslibrarydependencies.Thisprovidesthegamerswiththefacility

    ofoneclicklaunchoftheiSnakeapplication.Italsomakethedistributionofupdatesof

    theiSnakeapplicationtotheendusersveryconvenient.

    TheiSnakeapplicationdeployedatourwebsitehasbeendigitallysignedbythe

    iSnaketeamtoaddressthesecurityissuesrelatedtolaunchofInternetapplications.

    13

    Illustration 7: Block diagram of iSnake Game Server Manager at http://isnake.sf.net

  • 6 ProjectManagement

    The first thing we did before starting the work on iSnake was to register a project at

    Sourceforge4.Apartfromhostingservices,itprovidedusseveralcodeandprojectmanagement

    services.

    Illustration8showsthesvncommitstatisticsfortheisnakecoderepositoryatsourceforge.We

    collaboratedonprojectdocuments(includingprototypedesigns,projectplan,TODOlist,etc)

    usingWIKI(http://isnake.wiki.sourceforge.net).

    JUnittestsweredevelopedtoindependentlytestsomeofthemodulesbeforeintegration.The

    integrationofmodulesdevelopedbythethreedeveloperswasperformedinthreephases:

    Phase 1 Integration (Sep. 28, 2007) chat functionality of the game was tested

    successfully

    4 http://www.sourceforge.net

    14

    Illustration 8: Commit statistics for iSnake subversion repository at http://isnake.svn.sourceforge.net

  • Phase2Integration(Oct.06,2007)successfultestingofbasicversionofmultiplayer

    snakegame

    Phase3Integration(Feb1726,2008)integrationofallthemodulesforiSnake0.1

    Betarelease.

    7 Documentation

    Documentationofeverytaskbeingdoneintheprojectwasapriorityforalltheteammembers.

    Almost every portion of the source code contains full code documentation conforming to

    Javadocstandards.

    Thereexiststwopathfindingalgorithmsthatimplementsintelligentopponentinthegameviz

    BlackmambaandViper.Thesetwoalgorithmshavebeenfullydocumentedwithillustrations5.

    The protocol devised for communication between game server and clients has been

    documentedinANNEXD.

    8 Limitations

    ThelimitationsofpresentimplementationofiSnakeare:

    ThepresentimplementationofiSnakecanonlybeplayedinLAN.Duetolargelatency

    timeandbandwidthlimitation,itcannotbeplayedovertheInternet.

    Pathfindingalgorithms(BlackmambaandViper)implementedinthisgamehavetheir

    owncomputationlimitationswhichhasbeendescribeinANNEXA,B.

    5 Refer to ANNEX A,B

    Illustration 9: Screen shot of a snippet of source code showing method comments conforming to javadoc standards.

  • Fullstresstestoftheapplicationhasnotbeendoneyet.Hence,theresponseofgame

    serverinunpredictablesituationscannotbehandledproperly.

    iSnake'sGameServerManager(iSnakeGSM)locatedathttp://isnake.sf.netisstillin

    itsearlydevelopmentphase.Therearesomeunresolvedsecurityissues.

    9 FutureEnhancements

    PortiSnaketocellphoneplatformandOneLaptopPerChildOLPC(whichusesSugar

    Desktopenvironment).Thepresenceofseveralconnectivityoptions(Bluetooth,WIFI,

    GPRS,CDMA)incellphonesmakesitaveryattractiveplatformforamultiplayergame

    likeiSnake.LocalWIFInetworkformedbykidsusingOLPClaptopscanbeusedasa

    platformforiSnake'sdeployment.

    AsiSnakegameservercommunicateswithremoteplayingusingawelldefinedand

    very simple protocol (Refer to ANNEX D), iSnake clients programmed in other

    programmingplatformlikeFlash,Python,etccanbedeveloped.

    10 Conclusion

    Weweresuccessfulincreatingamultiplayerversionoftraditionalsnakegame.Thecomputer

    controlledintelligentopponentshavebeensuccessfullytestedinthegameisauniquefeature

    ofiSnake.

    Welearnedseveral project management techniquesusedbyprofessionals todevelop large

    scale project. The experience of working in team and integration of modules developed

    independently,withjustrequirementspecifications,isaveryimportantachievementforthe

    iSnaketeam.

  • 11 References

    Books

    1. TheJavaProgrammingLanguage,byKenArnold,JamesGosling,DavidHolmes

    ADDISONWESLEY,2000,ISBN8178081482

    2. JavaThreads,SecondEdition,byScottOaks,HenryWong

    O'REILLY,1997,ISBN8173660573

    3. CoreJavaVolumeI/II,SeventhEdition,byCayS.Horstmann,GaryCornell

    PEARSONEDUCATION,2005,ISBN8129709325

    4. Introduction to Algorithms, Second Edition, by Thomas H. Cormen, Charles E.

    Leiserson,RonaldL.Rivest,CliffordStein

    MITPRESS,2001,ISBN8120321413

    5. HeadFirstJava,SecondEdition,byKathySierra,BertBates

    O'REILLY,May2003,ISBN8173666024

    Websites

    1. NetbeansCommunityDocs

    http://wiki.netbeans.org/wiki/view/CommunityDocs

    2. TheInkscapeTutorialsBlog

    http://inkscapetutorials.wordpress.com/

    3. SmashingMagazineOnlinemagazinefordesigners

    http://www.smashingmagazine.com/

    4. TheJavaTutorials

    http://java.sun.com/docs/books/tutorial/

    5. TimingFramework

    https://timingframework.dev.java.net/

  • 6. JavaGaming.org'sForum

    http://www.javagaming.org/forums/index.php

    7. MITOpenCourseWare6.831UserInterfaceDesignandImplementation

    http://ocw.mit.edu/OcwWeb/ElectricalEngineeringandComputerScience/6831Fall

    2004/CourseHome/index.htm

    8. Amit'sA*PageTutorialonA*Pathfindingalgorithms

    http://theory.stanford.edu/~amitp/GameProgramming/

    9. Arianneamultiplayeronlinegamesframework

    http://arianne.sourceforge.net/

    10.JavaDesktopCommunityBlog

    http://community.java.net/javadesktop/

    11.JavaForum

    http://forum.java.sun.com

    12.BlogofRomainGuycoauthorofFilthyRichClients

    http://www.curiouscreature.org/

    13.FilthyRichClientsExamples

    http://www.filthyrichclients.com/

    14.ADistributedMultiplayerGameServerSystem

    http://warriors.eecs.umich.edu/games/papers/quakefinal.pdf

    15.TheJavaDevelopersAlmanac1.4

    http://www.exampledepot.com/

    16.ApacheMINASampleprogramsandtutorials

    http://mina.apache.org/

    17.PHPDocumentationforXMLlibrary

    http://www.php.net/

  • 18.QuantumRandomBitGeneratorService(QRBG)

    http://random.irb.hr/

  • ANNEXA:BlackmambapathfindingalgorithmProposedby:AbhishekDutta

    1Somedefinitionsandnotations

    1.1BoundingRectangle(br)Itisarectangleinwhichthesourceandthetargetlieattwooppositecornersofthe

    rectangle.SourceBoundingRectangle(sbr0)andTargetBoundingRectangle(tbr0)

    representtheboundingrectanglesfromsourceandtargetwhicharethesame

    rectangle.

    1.2PartialBoundingRectangle(pbr):Theserectangles toucheither thesourceor thetarget nodeandnotboth. Two

    partial boundingrectangles touching 'S' and 'T' formpaths fromsource to the

    targetnode.

    SourcePartialBoundingRectangle(spbr)

    Thepbrtouchingthesourcenode'S'.

    TargetPartialBoundingRectangle(tpbr)

    Thepbrtouchingthetargetnode'T'.

    RefertoIllustration10

    1.3Notations:

    1.3.1brNM

    denotesaboundingrectanglethatspans(ortouches)Nnodesalongthexaxis

    andMnodesalongtheyaxis.

    ANNEXA A1

  • 1.3.2spbrNM

    denotesasourcepartialboundingrectanglethatspans(ortouches)Nnodes

    alongthexaxisandMnodesalongtheyaxis.

    1.3.3tpbrNM

    denotesatargetpartialboundingrectanglethatspans(ortouches)Nnodes

    alongthexaxisandMnodesalongtheyaxis.

    1.3.4hpNM

    denotesahoppingpoint(coordinatespecifiedwithreferencetosource)along

    whichspbrNMandtpbrNMareformed.This coordinatepoint iscommonto

    bothspbrNMandtpbrNM

    1.3.5NumberingofPaths

    Foranygivenboundingrectangle(br)thereareonlytwopossiblepathsasshow

    inIllustration11.Pathnumberingconventionappliedis:

    Path1: The xcoordinate of the path first changes followedby change in y

    coordinate

    Path2: The ycoordinate of the path first changes followedby change in x

    coordinate

    Asource(S)andtarget(T)canbeplacedinfourpossiblewayssuchthatthey

    lieonoppositeendsofthediagonal.Consideringthefourposition(A,B,C,D)as

    depictedinIllustration11,wehavethefollowingfourcases:

    1.3.5.1'S'placedatpositionAand'T'placedatpositionC

    Path1=ABC,Path2=ADC

    1.3.5.2'S'placedatpositionBand'T'placedatpositionD

    Path1=BAD,Path2=BCD

    1.3.5.3'S'placedatpositionCand'T'placedatpositionA

    Path1=CDA,Path2=CBA

    ANNEXA A2

  • 1.3.5.4'S'placedatpositionDand'T'placedatpositionB

    Path1=DCB,Path2=DAB

    2Basisofthisalgorithm

    Inabsenceofanyobstacles, thecostofmovingfromonenodetoanother is constant

    throughoutthegamefield.Hence,theshortestpathisalongtheboundingrectangleedges

    ifnoobstaclesarepresentinthepathasshowninIllustration11.

    Bothpath1andpath2haveequaltravelingcost providedthatnoobstaclesarepresent

    alongthosepaths.Foranygivenbr,ifthereexistsapathfromsourcetotargetinsidethe

    brthenitwillbetheshortestpath.

    3Pathsgeneratedbypartialboundingrectangles

    Fourpathsaregeneratedbythesourceandtarget partial boundingrectanglesforthe

    givenhoppingpointasshowninIllustration12.

    ANNEXA A3

    Illustration 10: Bounding rectangle (br - dotted gray), Source bounding rectangle (spbr - dotted red) and Target bounding rectangle (tpbr - dotted green)

    Illustration 11: Two possible paths along the edges of the bounding rectangle (dotted red line rectangle) provided no obstacles exists along the path

  • Foranygiven(S,T)pair,wemovethehoppingpointalongthediagonaljoiningSandT.

    Specialconsiderationsisrequiredwhen:

    obstacles(wall)arepresentalongthepathsformedusingtheboundingandpartial

    boundingrectangles.

    Nopossiblepathcanbefoundusingallthepossiblecombinationsofthepartial

    boundingrectangles.

    theboundingrectangleisnotasquare(ie:forbrNM,NM)

    4Descriptionofthealgorithm

    Instead of considering all the possible cases at once, let us consider the working of

    algorithminseveralstages(withincreasingcomplications).

    4.1[A]SymmetricBoundingRectangles(SimpleCase)Forillustrationpurpose,letusfirstconsideragamefieldof6x6nodeswheresource

    andtargetareplacedat'S'and'T'respectivelyasshowninFigureA1.Thefollowing

    seriesofstepsareexecutedtofindapathfromsourcetotarget.Ifobstacleisfoundin

    ANNEXA A4

    Illustration 12: Four possible paths generated by source and target partial bounding rectangles (spbr,tpbr - depicted using red and green dotted lines respectively) for a given hopping point

  • all possiblepathofanstagethenextstageischecked.Theseriesofstepstakento

    obtainapathfrom'S'to'T'are:

    4.1.1Procedureoffindingpathforagiven(S,T)pair

    4.1.1.1FigureA2initiallythehoppingpointishp66(onthetarget).twopaths

    formedalongtheboundingrectanglebr66(showninreddottedrectangle in

    FigureA2)arecheckedforpresenceofobstacles.Ifnoobstaclesarefound,either

    path1orpath2arechosen(refertoIllustration11).Asbothpath1andpath2

    havesamepathlength,choicebetweenthesetwopathsismadebasedonsome

    combinationofsubpathsandchoosingthepathwhoselengthisshortest.

    4.1.1.2FigureA3fourpaths(refertoIllustration12)formedalongthesourceand

    targetpartialboundingrectangle(spbr55,tpbr22)arecheckedforpresenceof

    obstacle.

    4.1.1.3FigureA4fourpaths(refertoIllustration12)formedalongthesourceand

    targetpartialboundingrectangle(tpsbr44,ptbr33)arecheckedforpresenceof

    obstacle.

    4.1.1.4FigureA5fourpaths(refertoIllustration12)formedalongthesourceand

    targetpartialboundingrectangle(tpsbr33,ptbr44)arecheckedforpresenceof

    obstacle.

    4.1.1.5FigureA6fourpaths(refertoIllustration12)formedalongthesourceand

    targetpartialboundingrectangle(tpsbr22,ptbr55)arecheckedforpresenceof

    obstacle.

    4.1.1.6FigureA7Thisstepisnotnecessarytoexecuteasthetaskhasalready

    beenperformedinStep1usingtheboundingrectangle(br66).

    SeeIllustration13forillustrationofsteps1to6

    Computationoverheadcalculations

    Letthetimerequiredtocheckwhetherapartialboundingrectanglehasanobstacle

    ANNEXA A5

  • =T1

    timerequiredtocheckwhetheraboundingrectanglehasanobstacle=T2

    foragamefieldNxN(rowxcol)

    alsolet(tocreatetheworstcase)

    thesource'S'belocatedat(1,1)

    thetarget'T'belocatedat (N,N)

    Totalno.ofpossiblehoppingpoints(excludingthesource)=N1

    Hence,total time required to calculate a path6 = T2 + N * T1

    6 See section Requirements of this algorithm

    ANNEXA A6

  • ANNEXA A7

    Illustration 13: Illustrations for [A] Symmetric Bounding Rectangles (Simple Case)

  • 4.1.2Backtracking

    If4.1.1.1to4.1.1.6doesnotgiveapathfrom'S'to'T'thetechniqueofbacktracking

    willbeapplied.Toillustratetheprocessofbacktrackingletusconsiderthescenario

    showninIllustration14.

    Thepathsgeneratedfromtheboundingrectangle(br44)andallthepossiblepartial

    boundingrectanglescontainobstacle.Hencetheprocessdiscussedabovewillnot

    resultinanypathfrom'S0'to 'T'.Forsuchscenariowecanapplytheprocessof

    backtracking.

    ANNEXA A8

    Illustration 14: Game field scenario when all the paths formed by bounding and partial bounding rectangles contain obstacle.

  • Backtrackinginvolvesmovingtothenextouter(asinnerboundingrectanglesdonot

    contain any path for sure) bounding rectangle a path to the target is found.

    Illustration15showstheresultofbacktracking.BacktrackingfromS0toS1(the

    nextouterboundingrectangle)resultsinaboundingrectanglebr55.Thisbounding

    rectangledoesnotalsoresultinanypathfromS1toT.Hence,nextouterbounding

    rectangleischecked.

    The next outer bounding rectangle (br66) is formed at node S1 as shown in

    ANNEXA A9

    Illustration 15: Next outer bounding rectangle (br55) is checked for a path from node S1 to T.

    Illustration 16: Next outer bounding rectangle (br66) is checked for a path from node S2 to T.

  • Illustration16.ThisboundingrectanglehasapathfromS2toT.Hence,thepossible

    pathiscalculatedtoreachfromS2toT.

    AswenowhaveapathfromS2toT,weneedtocalculateapathfromS0toS2so

    thatwecanultimatelyreachTfromS0.NowwecalculatethepossiblepathfromS0

    toS2usingthestepsdiscussedaboveasshowninIllustration17.

    Byjoiningthepathsformedfromtheabovetwostepscanbecombinedtoforma

    pathfromS0toT.

    4.1.2.1Determiningnextouterboundingrectangleduringbacktracking

    Although the vertex for next outer bounding rectangle (required for

    backtracking)canbethenextcoordinateontheextendeddiagonal(asshownin

    Illustration 15,16), a simple technique can greatly reduce the number of

    backtrackingstepsofbothsourceandtarget.

    Letsource(S)andtarget(T)beplacedasshowninIllustration18.Apathfrom

    S to T contains twoedges. Path1 contains edge1andedge2. Path2contains

    edge4 and edge3. While determining whether a path contains obstacle, the

    algorithmmustalsodeterminewhichedgescontainsobstacles(ifany).

    ANNEXA A10

    Illustration 17: Path from node S0 to S2 is calculated using the process discussed before (after a path is found from S2 to T

  • Wecanapplythefollowingalgorithmtodeterminetheouterrectanglesrequired

    duringbacktrackingforsource.

    if(edge1containsobstacle) {

    if(edge4containsobstacle) {

    sourceouterrectanglevertex=S'

    }else {

    sourceouterrectanglevertex=S'''

    }

    }else {

    if(edge4containsobstacle) {

    sourceouterrectanglevertex=S''

    }else {

    nobacktrackingrequired

    }

    }

    Theouterrectanglefortarget,duringbacktracking,canbedeterminedbyapplying

    similarlogicforedge2andedge3.

    Thistechniqueworksfordifferentorientationofsourceandtargetasdescribedin

    Section1.3.5NumberingofPaths

    ANNEXA A11

    Illustration 18: Four edges (1-4) formed out of a bounding rectangle and the possible backtracking vertices for S and T

  • 4.1.2.2Mergingthepathsformedwhilebacktracking

    Whilebacktrackingseveralsubpathsarecreatedwhilerequirestobemergedto

    formthefinalpathfromsourcetotarget.Letusconsideracaseasdepictedin

    Illustration19.

    Duetothepresenceofwall(greenblocks),SandThastobacktracktoS'andT'

    positionsrespectively.Hereweobtainthreesubpathswhichare:

    Path from S to S' : depicted by red colored line from S to S' (SubPath1)

    PathfromS'toT:depictedbybluecoloredlinefromTtoT'(SubPath2)

    PathfromT'toT:depictedbypinkcoloredlinefromT'toT(SubPath3)

    We need to combine these three paths to obtain a final path from S to T

    (depictedbythickblackline).Ifweaddthesethreepathsdirectly,thefinalpath

    willcontainoverlappingpaths(whichisnotrequired).Thefollowingalgorithm

    canbeappliedtocomputethefinalpath(thatdoesnotcontainanyoverlapping

    regions).

    START

    Step1:InitializeFinalPathwiththecontentsofSubPath1

    ANNEXA A12

    Illustration 19: Sub paths formed during backtracking. Final path from S to T obtained by combining the sub paths.

  • FinalPath=SubPath1

    Step 2: Now perform the following operations for each cell coordinate

    presentinSubPath2andSubPath2(K=2,3)

    cellCoordinate=SubPathK.getCellCoordinate()

    if(FinalPathcontainscellCoordinate) {

    removecellCoordinatefromFinalPath

    }else {

    addcellCoordinatetoFinalPath

    }

    Step3:FinalPathcontainsdiscontinuitiesatthebendsofpath.Searchfor

    consecutivecellcoordinateforwhichbothxandyvaluesofthecoordinate

    change(ie:|dx|=1,|dy|=1).

    Step4:Correctthesediscontinuitiesbyaddingthemissingcellcoordinates.

    END

    4.2[B]AsymmetricBoundingRectangles

    4.2.1SimpleCase

    A problem arises when the bounding rectangle is asymmetric as shown in

    Illustration20.

    Thesolutiontothisproblemistoinsertrequirednumberofdummynodesbetween

    'S' and 'T' so that the newbounding rectangle becomes symmetric as shown in

    ANNEXA A13

    Illustration 20: Case of asymmetric bounding rectangle (br63)

  • Illustration 21. The algorithm applied in [A] Symmetric Bounding Rectangles

    (SimpleCase)canbenowappliedbyconsideringthedummynodesasnormal

    gamefieldnodesfreefromanyobstacles.

    4.2.2SandTlyingonsamestraightline(verticalorhorizontal)

    Thiscaseariseswhenboth 'S' and 'T' lieonsamestraightline(horizontalor

    vertical)asshowninIllustration22.

    The case can be converted to [A] Symmetric Bounding Rectangle (Simple

    Case)casebyaddingdummynodesasshowninIllustration23.

    ANNEXA A14

    Illustration 21: The bounding rectangle (br66) is made symmetric by adding required no. of dummy nodes

    Illustration 22: Another case of asymmetric bounding rectangle (br61)

  • 5Requirements

    5.1ConstanttimealgorithmforobstacledetectionTheremustexistaconstanttimealgorithmthatcananswerthequestionDoesthe

    given bounding or partial bounding rectangle contain any obstacle?. The

    constant time algorithm requirement means that the YES/NO decision of this

    algorithmshouldnotdependonthesizeofrectangleunderconsiderationorthe

    numberofobstaclespresentinthegamefield.

    AnimportantobservationforiSnakegameisthattheobstaclesinthegamearenot

    dynamic.Inotherwords,theobstaclesremainconstantuntilagivenFOODiseaten

    byoneoftheplayers.Hencewecanassumethattheobstacleisconstantduringthe

    executionofthispathfindingalgorithm.

    Weapply the followingalgorithmtodetect whether agivenboundingrectangle

    containsanyobstacles.

    START

    ANNEXA A15

    Illustration 23: The case can be converted to [A] Symmetric Bounding Rectangle (Simple Case) case by adding dummy nodes

  • Step1:Let(x1,y1)=onecorneroftheboundingrectangle

    (x2,y2)=diagonallyoppositecorneroftheboundingrectangle

    obstacle=asetcoordinatesdefiningtheobstacle(wall)

    Step2:Repeatstep2foreachcellcoordinateinobstacle

    oc=obstacle.getCellCoordinate()

    path1HasObstacle=true,path2HasObstacle=true

    if(x>=x1andx=y1andy

  • if(path2HasObstacle)

    returnPATH1 is OBSTACLE FREE

    else

    returnPATH1andPATH2are OBSTACLE FREE

    }

    END

    6Limitations

    6.1Thisalgorithmdoesnotconsiderthetransparentgamefieldboundary(entrytoone

    sideofthefieldcausesexitintheoppositesideofthefieldasdepictedinIllustration

    24)duringpathcalculation.Duetothislimitationthecomputedpathisnotoptimal.

    6.2Thehoppingpointsarealwaystakenfromthediagonallinejoiningthesourceand

    target.Becauseofpropertyofthealgorithm,itisnotabletocomputepathswhena

    complexstructureofwall,asshowninIllustration25,ispresent.Thisisthereasonwhy

    Blackmambaimplementationentersinfiniterecursionforsuchobstacles.

    ANNEXA A17

    Illustration 24: Transparent boundary of the game field

  • ANNEXA A18

    Illustration 25: Only 1 hopping point prevents this algorithm from computing path in presence of a complex structured wall

  • ANNEXB:ViperpathfindingalgorithmProposedby:SurajSapkota

    1 Assumptions

    Thisalgorithmassumesgamefieldasfollows:

    The rectangle with the dotted boarder is the viewport(vp) of each player. Other

    rectangles attached with it in each side are the virtual view port(vvp) in their

    correspondingsides.

    Smallyellowboxisawallunit.Groupofattachedwallunitissaidtobewall.

    Theborderofthegamefieldaretransparentunlessthereiswall.

    Wallistheonlythingthatasnakecanstriketo.

    Therecanbemultiplewallinthesamegamefield.

    ANNEXB B1

    Illustration 1: The game field (unfolded Envelop)

  • Finallyconsideringall these, theaimof this algorithmis tofindall (theremaybe

    multiplepathofsamedistance)shortestpathfromthesnake(head)tofood.However

    asaresultitwillreturnonlyoneamongthosepaths.

    2 Principalandimplementationofthisalgorithm.

    Thisalgorithmwillnotdealwithfindingonlyoneshortestpathinsteaditcalculatesmultiple

    pathbetweenthesourceandthedestination,andallofthesepathhavethesamedistance,the

    shortestdistance.Actually theresultisnotintheformofmultiplepath,merelyitisa

    collectionofthepointsthatitmustpassthrough.Itisthepositionofthepointsthatmake

    thepathmultiple.Itisdescribedlaterinmoredetail.

    Thealgorithmfollowsfollowingsteps:

    1.Thisalgorithmbeginswithsplittingallthegamefieldintosmallrectangles(Fundamental

    openrectangle7(FOR8)),sayR1,R2,R3,...Rn.Ifgamefield(onlyviewport),asawholeis

    saidtobeG.Thenmathematicallythewall,Wcanbedefinedas:

    W=GR1UR2UR3U...URn

    Broadly,thisalgorithmdealswithsplittingthegamefieldintoseveral(asmany)rectangles

    suchthat,theunionofallthesesmallrectanglesresultinthegamefieldthatexcludewall.ie,

    thesnakecanmovesafelyfromanypointintherectangle(Ri)toanyotherpointwithinthe

    samerectangle(Ri)andhencecalledOpenrectangles(OR).

    7 Open rectangle is a rectangle that does not contain any wall. Within it snake can move freely.8 The algorithm of generating FOR is discussed later.

    ANNEXB B2

  • 2.NextwedefineGate9(GateasinreallifeisawaytomovefromaFORtoanotheradjacent

    FOR) calculatetheshortestdistancebetweeneachtwoGatesofeach FOR(eg:theshortest

    distancebetweentherectanglesR1andR5aredeterminedbythedistancebetweenthetwo

    gatesofR3sharedwithR1andR5respectively).

    3.Afterthecalculationoftheshortestpath,agraphasshowninIllustration4isformed.

    Intheabovegraph

    i. Thedottedlinesdefinesdirectconnection,thedirectpath.

    ii. Thedarklineshowsa1stepindirectconnectionbetweenthoserectanglesthatarenot

    connecteddirectly.

    9 A gate must be common to only two FOR.

    ANNEXB B3

    Illustration 4: Graph

    Illustration 3: "Illustration 2" in broader view

    Illustration 2: Slitted into 6 small pieces of rectangle.

  • iii. Sij,besidewiththevertex,(ingraph)denotesthatFORiisconnectedtoFORjthrough

    thisvertexandviceversa.Thiscanalsobecalledindirectpath.Anditpossesthepath

    distance.

    iv. There may be multiple indirect path. Eg: We can move form2 to 5 (S25) in two

    differentways:via3or5.

    Somedatathatareassociatedwiththerectangle(nodeinthegraph)isshownbelow.

    4.Finallyafterallthesecalculation,wecancalculatethepathbetweentwoFOR's,thesource

    andthedestinationwithshortestdistance.Whentwopoints(sourceandtarget)aregivenwe

    candeterminetheFOR's,theylieinandcancomputethepathbetweenthem.

    ANNEXB B4

    Illustration 5: Data associated with each node

    Illustration 7: Zoomed view of "Illustration 6"Illustration 6: Path for a sample case.

  • The above sample case shown in illustration 6 and 7, shows the path calculated by the

    algorithmfromthesnake(redonepointedbyanarrowA)tothefood(blueonepointedbyan

    arrowF).ThepointspointedbythearrowsA,B,C,D,EandFarepoints(HopingPoints)that

    theintelligentplayermustpassthrough.Andthusallowingmultiplepossibilityforpath.

    Thepathismultiplebecause,thereexistmultiplewaytogofromAtoBandEtoF.Further

    therectanglesasformedbythepointsAandB(EandF)canalsobecalledDerivedopen

    rectangle(asitdoesn'tcontainanywall,andhenceallowsfreemovementofthesnakeinside

    it).

    3 FordividingtheGamefieldintofundamentalopenrectangle:

    Thealgorithminvolvesslicingthegamefieldincyclicorder

    inanticlockwisedirectionstartingwiththeleftedge.Asthe

    gamefieldinitiallyhasnoterminatingedge(asenvelope)we

    startwith(visually)leftedgeofthegamefield.

    1. InitiallystartingfromtheZerothcoordinatemoveto

    bothsidesuntilitstriketowall(unit).NameitFundamentalOpenRectangle(FOR1and

    FOR2orJustR1andR2).Illustration8and9.

    2. Now the gamefield has shrinked to as shown in

    Illustration10. (It nowhas changed to cylindrical

    shapefromenvelopeshape.)

    3. Moving in anticlockwise direction, Slice from

    bottom in both direction (up and down) to get other two rectangle R3 and R4.

    Illustration11.

    ANNEXB B5

    Illustration 8: Step 1 (a)

    Illustration 9: Step 1 (b)

  • Tillthissteptherectanglewasnotbounded(either in

    allfoursides(envelop)orintwosides(topandbottom)

    (cylinder)).Fromthissteponwardthe sliced game

    fieldwouldbebounded.

    4. Now try to slice rectangle from top left, bottom

    left,bottomrightandtoprightrespectively.Herewefail

    toslicetherectanglefromtopleftandbottomrightas

    thereiswall(unit)attheedge.

    Wecannowcreatetwonewrectanglesfrombottomleft

    andtoprightnamelyR5andR6.Illustration13.

    5. Nowsliceawaytheboundarylayerofthegamefield

    formedinIllustration13.ShowninIllustration14.

    6. Asearlieragaintrytoslicethegamefieldintheanticlockwisedirectionstartingfrom

    left.ItwillresultintwomorerectangleR7andR8.Illustration15.

    Duringthis weassumealreadyslicedrectangle as a

    hollowspace.

    7. ForFurtherOptimizationweproceedbybreakingdowntherectanglethattouches

    itself(eg:inthiscase,thetopedgedofrectangleR1touchitselftoitsbottomedge).These

    typeofrectanglesaredividedinthemiddle.Thisresultsinbestutilizationofthetransparency

    oftheGameField.

    ANNEXB B6

    Illustration 10: Step-2

    Illustration 12 Illustration 13: Step 3

    Illustration 14: Step 4Illustration 15

    Illustration 11: Step-3

  • 4 SpecialcaseforGameFieldwithnowall

    Ifthereisnowallwesimplychopthegamefieldverticallyandhorizontallyfromthemiddle

    resultingin4FOR's.Thisresultsinmaximumutilizationofthetransparencyofthegame

    field.TheresultisshowninIllustration17.

    ANNEXB B7

    Illustration 16: The Final Result

    Illustration 17: Sliced Game Field with no wall

  • 5 SalientFeatures:

    As most of the processing is done before the actual game starts, it must reduce the the processing time during the game-time.

    The concept of open-rectangle allows multiple path, and hence within it the snake can be moved randomly towards the specified point. And hence it is intelligent.

    Furthermore, during the calculation of the path the snake can move within the FOR in which it currently lie.

    6 Limitations:

    If the number of FOR increases to too high, then it will obviously be tough and slow to determine the shortest path.

    ANNEXB B8

  • ANNEXC:Programflow

    NOTE:"EXT"referstotheactionsthataretriggeredbyClientNetworkInterfacemodulewhen

    messagesarereceivedfromgameserver

    ANNEXC C1

    Illustration 26: iSnake game application enters in STAGE-1 and exits through STAGE-5

    Illustration 27: iSnake game application starts in STAGE-1 and this stage involves connection to game server specified by the player

  • NOTE:"EXT"referstotheactionsthataretriggeredbyClientNetworkInterfacemodulewhen

    messagesarereceivedfromgameserver

    ANNEXC C2

    Illustration 28: In STAGE-2 players can chat with each other. The game will start only when all the players connected to the game server send READY signal

  • NOTE:"EXT"referstotheactionsthataretriggeredbyClientNetworkInterfacemodulewhen

    messagesarereceivedfromgameserver

    ANNEXC C3

    Illustration 29: STAGE-3 involves receiving different game data (like wall coordinates, food coordinate, snakes start position, etc)

  • NOTE:"EXT"referstotheactionsthataretriggeredbyClientNetworkInterfacemodulewhen

    messagesarereceivedfromgameserver

    ANNEXC C4

    Illustration 30: STAGE-4 involves synchronization with the game server

  • NOTE:"EXT"referstotheactionsthataretriggeredbyClientNetworkInterfacemodulewhen

    messagesarereceivedfromgameserver

    ANNEXC C5

    Illustration 31: STAGE-5 represents the state when game is being played

  • ANNEXD:InterSnakeCommunicationProtocol

    ThecommunicationbetweenthegameserverandclientapplicationsisdoneusingtheInter

    SnakeCommunicationProtocol(ISCP).Theprotocolcontainsfivedifferentclasses.Theseare

    listedbelow:

    Information Usedfortransmissionofplayer'sinformation(name,color,

    location). Used only when the player creates/joins the

    game.

    ChatMessage Transmitsthechatmessage.Worksonlybeforetheactual

    gamestarts.

    ControlSignal Transmitscontrolsignalsbetweenserverandclients.These

    signalsaremainlyusedforsynchronization.

    LevelData Sendsdatarequiredonlevelchange(food,wall,score,life,

    etc).Sentinitiallywhentheactualgamebeginsandthen

    aftereverylevelchange.

    Move Transmits the movement of clients, collision information

    andalsotheinformationaboutfoodcapture.

    Thecommunicationpacketsareencodedinbyteformatforthepurposeoftransmissionand

    aredecodedinsimilarfashion.Theencodinganddecodingofpacketsinclientsideishandled

    by ClientEncoder and ClientDecoder respectively. Similar for game server, encoding and

    decodingishandledbyServerEncoderandServerDecoderrespectively.

    For instance, the server encoder for chat message is known as ChatServerEncoder. The

    encodersanddecodersareplacedundernet.sf.isnake.codec.

    Onthebasisofcommunicationpacketflow,wecanclassifythecommunicationbasicallyinto

    twotypes:

    Client Initiated Communication: In this type of communication, the client first

    ANNEXD D1

  • encodesthepacketwithnecessarydata.Sendittoserverinflippedorder.Flippingis

    requiredsothatitgetsreceivedincorrectorderattheotherend.Theserverdecodesit.

    Theserverreencodes thedatawithsomefurther informations(if requiredsuchas

    sender'sId)andflipsit.Thispacketisretransmittedtoclientswhereitisdecoded.The

    communicationcycleisshownbelow:

    ServerInitiatedCommunication:Inthistypeofcommunication,serverfirstencodes

    thepacketwithnecessarydataandtransmitsinflippedorder.Thepacketisdecodedon

    clientside.Thecommunicationcycleisshownbelow:

    Thefiveclassesofcommunicationcansendvariousmessages.Allthemessagesaredecoded

    thesamewaytheyareencoded. Followingconventionsareusedindepictingtheencoding

    overhere:

    Symbol Meaning

    Showsfieldstobesentalongwithidentifier

    () Showsthedatatypeofthefield.However,allthefieldsareconvertedintobytewhileencodingandondecodingtheyarereceivedasbytesandconvertedtoproperdatatype.

    id Representstheplayerid(anintegerusedtouniquelyidentifyaplayerinthegame).

    [] Thefieldswithin[]arepartofanarrayintheprotocolclass.

    Class: Chat Message1 Packet ChatText

    Identifier CH

    Type ClientInitiated

    Description Isusedtotransmitachatmessagetypedbyaclienttootherclients.

    to_idisrequiredforonetoonecommunicationwhichisnotcurrently

    ANNEXD D2

    Client Encoder Client Decoder Server Encoder Server Decoder

    Client Decoder Server Encoder

  • allowedinthegamebuthasbeendesignedforfutureenhancements.0

    isbeingsentasto_idwhichisbasicallyamulticastid.

    ClientEncoder CH

    ServerEncoder CH

    Class: Information1 Packet Playerinfo

    Identifier IN

    Type ClientInitiated

    Description Isusedtotransporttheinformationsofaplayerviz;name,colorand

    location.

    ClientEncoder IN

    ServerEncoder IN

    Class: ControlSignal1 Packet Acknowledgment

    Identifier AK

    Type ClientInitiated

    Description ThispacketissentwhenaclientsuccessfullyreceivesLeveldata.The

    status_code field has beenreserved for future enhancements. As of

    nowitissentas0.

    ClientEncoder AK

    ServerEncoder AK

    2 Packet Quit

    Identifier QT

    ANNEXD D3

  • Type ClientInitiated

    Description Sentwhenaclientquitsthegame.

    ClientEncoder QT

    ServerEncoder QT

    3 Packet Ready

    Identifier RY

    Type ClientInitiated

    Description Issentwhentheuserspecifieshisreadinesstostartthegame.

    ClientEncoder RY

    ServerEncoder RY

    4 Packet ID

    Identifier ID

    Type ServerInitiated

    Description Thispacketissentbyservertoclienttoassignanidtotheplayer.This

    isdoneassoonastheclientsendshisinformation.

    ServerEncoder ID

    5 Packet Start

    Identifier ST

    Type ServerInitiated

    Description Represents start of various events in the game on the basis of

    status_code.status_code0representsthe beginning of

    transmissionof leveldata.status_code1representsthebeginningof

    ANNEXD D4

  • levelsynchronizationtaskbeforebeginningofalevelandstatus_code2

    isasignaltostarttheactuallevelplay.

    ServerEncoder ST

    6 Packet Stop

    Identifier SP

    Type ServerInitiated

    Description Representstheendoflevel.

    ServerEncoder SP

    7 Packet Force

    Identifier FR

    Type ServerInitiated

    Description Thiscommunicationpacketforcesaplayertosendareadypacketwhen

    allothershaveexpressedtheirwillingnesstobeginthegame.

    ServerEncoder FR

    8 Packet NoAcknowledgment

    Identifier NK

    Type ServerInitiated

    Description Thispacketissentbyserverwhentheinformationsuppliedbyclientis

    not valid. status_code here represents field which has invalid data.

    Invaliddataoccurswheninformationfieldcontainsreservedcharacters

    orduplicateentry.

    ServerEncoder NK

    ANNEXD D5

  • Class: LevelData1 Packet Beginfrom

    Identifier BF

    Type ServerInitiated

    Description The packet sends starting coordinate of all the players in a single

    packet.Theplayer beginslevelfromthiscoordinateandisresettothis

    coordinateoncollision.

    ServerEncoder BF[]

    2 Packet Score

    Identifier SC

    Type ServerInitiated

    Description Sendsscoreofalltheplayersinthepacketonbeginningofalevel.

    ServerEncoder SC[]

    3 Packet Level

    Identifier LV

    Type ServerInitiated

    Description Sendsthelevelnumbertotheclients.

    ServerEncoder LV

    4 Packet Life

    Identifier LF

    Type ServerInitiated

    ANNEXD D6

  • Description Sendsthelifecountforeachplayeronbeginningofalevel.

    ServerEncoder LF[]

    5 Packet Wall

    Identifier WL

    Type ServerInitiated

    Description Sendsthewallcoordinatestotheclients.

    ServerEncoder WL[]

    6 Packet Food

    Identifier FD

    Type ServerInitiated

    Description Sendsthefoodcoordinatestotheclientsonthebeginningofalevel.

    ServerEncoder FD[]

    Class: Move1 Packet Collide

    Identifier CL

    Type ClientInitiated

    Description Thepacketissentwhenaplayerloosesalife.Possibilityofmorethan

    oneplayers collidingonsameturnhasbeentakenintoaccount. At

    present,however,wearecheckingthe collision on server and the

    communicationisthusServerInitiated.

    ANNEXD D7

  • ClientEncoder CL

    ServerEncoder CL[]

    2 Packet Move

    Identifier MV

    Type ClientInitiated

    Description Carriesthechangeinxandy(dxdy)oftheclientstotheserver.Server

    mergeschangeincoordinateofalltheclientsinanewMVpacketand

    transmitstotheclients.

    ClientEncoder MV[]

    ServerEncoder MV[]

    3 Packet Eaten

    Identifier ET

    Type ServerInitiated

    Description Serversendsthepacketwheneverthefoodgetseaten.Thispacketalso

    initiatesthe generationofFoodpacketasalevelcanhavemorethan

    onefood.

    ClientEncoder ET

    ServerEncoder ET

    FD[]

    ANNEXD D8

    1 Acknowledgment 2 Abstract 3 Objectives 4 Programming Environment 5 Methodology 5.1 iSnake Client Application 5.1.1 Client Encoder/Decoder 5.1.2 Client Network Interface 5.1.3 Input Handler 5.1.4 Game Field Matrix 5.1.5 Game Field Canvas 5.1.6 User Interface Components 5.1.7 Game Controller

    5.2 iSnake Game Server 5.2.1 Server Encoder/Decoder 5.2.2 Server Network Interface 5.2.3 Virtual Game Field 5.2.4 Player Information Manager 5.2.5 Random Number Pool 5.2.6 Status Server 5.2.7 Server Core

    5.3 Intelligent Autonomous Opponent Snakes 5.4 iSnake Game Server Manager (GSM) @ SF.net

    6 Project Management 7 Documentation 8 Limitations 9 Future Enhancements 10 Conclusion 11 References 1 Some definitions and notations 1.1 Bounding Rectangle (br) 1.2 Partial Bounding Rectangle (pbr): 1.3 Notations: 1.3.1 brNM 1.3.2 spbrNM 1.3.3 tpbrNM 1.3.4 hpNM 1.3.5 Numbering of Paths

    2 Basis of this algorithm 3 Paths generated by partial bounding rectangles 4 Description of the algorithm 4.1 [A] Symmetric Bounding Rectangles (Simple Case) 4.1.1 Procedure of finding path for a given (S,T) pair 4.1.2 Backtracking

    4.2 [B] Asymmetric Bounding Rectangles 4.2.1 Simple Case 4.2.2 S and T lying on same straight line (vertical or horizontal)

    5 Requirements 5.1 Constant time algorithm for obstacle detection

    6 Limitations 1 Assumptions 2 Principal and implementation of this algorithm. 3 For dividing the Game field into fundamental open rectangle: 4 Special case for Game Field with no wall 5 Salient Features: 6 Limitations: