Académique Documents
Professionnel Documents
Culture Documents
on
iSnakeMultiplayerIntelligentSnakeGame
http://isnake.sourceforge.net
Submittedto
InterCollegeUndergraduateProjectCompetition
KUCCSoftwareMeet2008
Mar.7,2008
by
AbhishekDutta
JitendraHarlalka
SurajSapkota
adutta.np@gmail.com
jitendra.harlalka@gmail.com
ssapkota@gmail.com
cell:9841559669
cell:9803395335
cell:9841579381
TableofContents
1
2
3
4
5
Acknowledgment..................................................................................................................................1
Abstract.................................................................................................................................................2
Objectives.............................................................................................................................................3
Programming Environment...................................................................................................................4
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.
2 Abstract
Thisprojectaimstobringthefunandsimplicityofsnakegamewithsomenewfeatures.Itwill
includecomputercontrolledintelligentopponentswhoseaimwillbetochallengethehuman
players.Itwillalsohavethemultiplayerfeaturethatwillallowmorethanoneplayerstoplay
thegameoveranetwork.
This project explores a new dimension in the traditional snake game to make it more
interesting and challenging. The simplicity of this game makes it an ideal candidate for a
minor project as we can focus on advanced topics like multiplayer functionality and
implementationofcomputercontrolledintelligentopponents.
3 Objectives
Thisgameaimstochangethewaypeoplethinkoftraditionalsnakegame.Itwillofferthe
experienceofcommercialmultilayergamestotheplayerretainingthesimplicityoftraditional
snakegame.
Themajorobjectivesofthisprojectare:
Createasnakegamethatwillhaveallthefunctionalityoftraditionalsnakegames.
Introducemultilayerfunctionalityinthegamethatwillallowseveralplayerstoplaya
gamesimultaneously.Itshouldbeabletogivetheexperienceofarealtimemultiplayer
gametotheplayers.
Introducecomputercontrolledintelligentopponent(uniquefeatureofthisgame)to
makethegamemorechallengingandinteresting.Themovementandactionofthese
intelligentopponentswillbecontrolledbycomputerwhoseaimwillbetoeatthefood
beforehumanplayerscaptureit.
4 ProgrammingEnvironment
Weusedseveralopensourcetoolstodevelopthisproject:
Netbeans5.5IDE
All the developers of iSnake team used 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.
5 Methodology
iSnakeisamultiplayerversionoftraditionalsnakegame(popularamongcellphonegamers)
withcomputercontrolledintelligentopponentsthatchallengesthehumanplayers.
Theplayerwhohoststhegameserveriscalledlocalplayer.TheiSnakeClientApplication
andGameServerruninseparateexecutiondomains.TheiSnakeClientApp.forlocalplayer
communicateswiththegameserverthroughnetworklayer,justlikeotherremoteplayers,as
showninillustration1.
ThecompleteiSnakeapplicationisdividedintofourmajorcomponents:
iSnakeClientApplication
iSnakeGameServer
IntelligentAutonomousOpponentSnakes
iSnakeGameServerManager(GSM)@SF.net
5.1 iSnakeClientApplication
iSnakeclientapplicationreferstotheapplicationusedtoplaysnakegame.Aplayerjoins
analreadyexistingiSnakegameserverusingthisapplication.
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.
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. The update of game field canvas starts by scanning each
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
the working of all the other modules in the application and handles all the messages
1 See References [Website]
receivedfromthegameserver.GameControllermaintainsthegamecyclewhenthegame
isrunning.Thisgamecycleissynchronizedwiththegamecycleofthegameserver.Allthe
updatestogamefieldmatrixaredoneduringthiscycletime.Afterexpiryofeachgame
cyclethegamefieldisrepaintedtoreflectthechangesinthegamefield.
5.2 iSnakeGameServer
iSnake game server handles the multiplayer feature of this game and allows multiple
iSnakeclientapplicationstoplaythegamehostedbythatparticulargameserver.
5.2.1 ServerEncoder/Decoder
Thismoduleperformstheencodinganddecodingofmessagesleaving/arrivingthe
servernetworkinterfacemoduleusingtheprotocolstandarddescribedinANNEXD:Inter
SnakeCommunicationProtocol.
5.2.2 ServerNetworkInterface
It provides aninterface to the Server Core module for communication with the
remote/local players of the game being hosted. It is responsible for triggering of
appropriatemethodsofServerCorewhenmessagefromremote/localplayersisreceived.
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
AtypicalresponseofStatusServerisgivenbelow:
<?xmlversion=1.0encoding=UTF8?>
<iSnake>
<GameServerData>
<GameServerAddress>124.41.228.219</GameServerAddress>
<GameServerPort>9669</GameServerPort>
<NoOfPlayersOnline>5</GameServerLocation>
<GameServerStatus>Waiting</GameServerStatus>
</GameServerData>
</iSnake>
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 new player tries to join the game, it receives a NAK
response.Inthismode,ServerCoremaintainsagamecycletimeduringwhichitreceives
themovementcoordinates(intermsofdeltaXanddeltaY)fromtheplayers.Ifaplayer
doesnotsendanypacketduringthiscycletime,serverconsidersthemovementcoordinate
sent in last cycle for the current game cycle. After expiry of cycle time, game server
broadcastsapacketcontainingmovementcoordinatesofeachplayertoalltheplayers
activeinthegame.Thegameserveralsochecksifanyplayerhaseatenthefoodorifany
playershavecollidedtothewallineachcycle.
5.3 IntelligentAutonomousOpponentSnakes
Thesearecomputercontrolledsnakes,inthegame,whoseaimistochallengethe
human players. We have two implementations of path finding algorithms to create
intelligent autonomous opponent snakes. These algorithms return the shortest possible
10
pathfromgivensource(S)andtarget(T)coordinatepairconsideringtheobstacles(if
any)presentinthegamefield.Thecodename3forthesetwoimplementationsare:
Blackmamba(refertoANNEXA)
Viper(refertoANNEXB)
A detailed paper describing the algorithm used by these two implementation is
presentin ANNEXAandANNEXB.Themoduleimplementingthesetwopathfinding
algorithm easily fits into the existing design of iSnake Client Application as shown in
Illustration4
Illustration 4: Module implementing two path finding algorithms replaces the Input Handler
module of standard iSnake Client application.
To know which of the two implementations perform better, we profiled them using a
simpleJUnittestandtheresultswereplottedusinggnuplot:
11
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
5.4 iSnakeGameServerManager(GSM)@SF.net
iSnakeGameServerManager(iSnakeGSM)hostedathttp://isnake.sf.netisusedto
managealltheinformationaboutiSnakegameserversbeinghostedovertheInternet.
13
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
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.
Illustration 9: Screen shot of a snippet of source code showing method comments conforming to
javadoc standards.
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.
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.
We learned several project management techniques used by professionals to develop 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:Blackmambapathfindingalgorithm
Proposedby:AbhishekDutta
1Somedefinitionsandnotations
1.1BoundingRectangle(br)
Itisarectangleinwhichthesourceandthetargetlieattwooppositecornersofthe
rectangle.SourceBoundingRectangle(sbr0)andTargetBoundingRectangle(tbr0)
representtheboundingrectanglesfromsourceandtargetwhicharethesame
rectangle.
1.2PartialBoundingRectangle(pbr):
These rectangles touch either the source or the target node and not both. Two
partial bounding rectangles touching 'S' and 'T' form paths from source 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
which spbrNM and tpbrNM are formed.This coordinate point is common to
bothspbrNMandtpbrNM
1.3.5NumberingofPaths
Foranygivenboundingrectangle(br)thereareonlytwopossiblepathsasshow
inIllustration11.Pathnumberingconventionappliedis:
Path1: The xcoordinate of the path first changes followed by change in y
coordinate
Path2: The ycoordinate of the path first changes followed by 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, the costofmoving from onenodetoanother isconstant
throughoutthegamefield.Hence,theshortestpathisalongtheboundingrectangleedges
ifnoobstaclesarepresentinthepathasshowninIllustration11.
Bothpath1andpath2haveequaltravelingcost providedthatnoobstaclesarepresent
alongthosepaths.Foranygivenbr,ifthereexistsapathfromsourcetotargetinsidethe
brthenitwillbetheshortestpath.
3Pathsgeneratedbypartialboundingrectangles
Four paths aregenerated bythe source and target partial bounding rectanglesfor the
givenhoppingpointasshowninIllustration12.
ANNEXA
A3
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
allpossiblepathofanstagethenextstageischecked.Theseriesofstepstakento
obtainapathfrom'S'to'T'are:
4.1.1Procedureoffindingpathforagiven(S,T)pair
4.1.1.1FigureA2initiallythehoppingpointishp66(onthetarget).twopaths
formedalongtheboundingrectanglebr66(showninreddottedrectanglein
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
ANNEXA
A6
ANNEXA
Illustration 13: Illustrations for [A] Symmetric Bounding Rectangles (Simple Case)
A7
4.1.2Backtracking
If4.1.1.1to4.1.1.6doesnotgiveapathfrom'S'to'T'thetechniqueofbacktracking
willbeapplied.Toillustratetheprocessofbacktrackingletusconsiderthescenario
showninIllustration14.
ANNEXA
A8
A9
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 two edges. Path1 contains edge1 and edge2. Path2 contains
edge4 and edge3. While determining whether a path contains obstacle, the
algorithmmustalsodeterminewhichedgescontainsobstacles(ifany).
ANNEXA
A10
if(edge4containsobstacle)
sourceouterrectanglevertex=S'
}else
sourceouterrectanglevertex=S'''
}
}else
if(edge4containsobstacle)
sourceouterrectanglevertex=S''
}else
nobacktrackingrequired
}
}
Theouterrectanglefortarget,duringbacktracking,canbedeterminedbyapplying
similarlogicforedge2andedge3.
Thistechniqueworksfordifferentorientationofsourceandtargetasdescribedin
Section1.3.5NumberingofPaths
ANNEXA
A11
4.1.2.2Mergingthepathsformedwhilebacktracking
Whilebacktrackingseveralsubpathsarecreatedwhilerequirestobemergedto
formthefinalpathfromsourcetotarget.Letusconsideracaseasdepictedin
Illustration19.
A12
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.
A13
4.2.2SandTlyingonsamestraightline(verticalorhorizontal)
Thiscaseariseswhenboth'S'and'T'lieonsamestraightline(horizontalor
vertical)asshowninIllustration22.
ANNEXA
A14
5Requirements
5.1Constanttimealgorithmforobstacledetection
TheremustexistaconstanttimealgorithmthatcananswerthequestionDoesthe
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.
We apply the following algorithm to detect whether a given bounding rectangle
containsanyobstacles.
START
ANNEXA
A15
Step1:Let(x1,y1)=onecorneroftheboundingrectangle
(x2,y2)=diagonallyoppositecorneroftheboundingrectangle
obstacle=asetcoordinatesdefiningtheobstacle(wall)
Step2:Repeatstep2foreachcellcoordinateinobstacle
oc=obstacle.getCellCoordinate()
path1HasObstacle=true,path2HasObstacle=true
if(x>=x1andx<=x2){
if(!path1HasObstacle){
if(x1y1.ggggetY().equals(y))
path1HasObstacle=true
}
if(!path2HasObstacle){
if(x2y2.gggetY().equals(y))
path2HasObstacle=true
}
}
if(y>=y1andy<=y2){
if(!path1HasObstacle){
if(x2y2.getX().equals(x))
path1HasObstacle=true
}
if(!path2HasObstacle){
if(x1y1.getX().equals(x))
path2HasObstacle=true
}
}
Step3:if(path1HasObstacle){
if(path2HasObstacle)
returnNOPATHPOSSIBLE
else
returnPATH2isOBSTACLEFREE
}else{
ANNEXA
A16
if(path2HasObstacle)
returnPATH1 is OBSTACLE FREE
else
returnPATH1andPATH2are OBSTACLE FREE
}
END
6Limitations
6.1Thisalgorithmdoesnotconsiderthetransparentgamefieldboundary(entrytoone
sideofthefieldcausesexitintheoppositesideofthefieldasdepictedin Illustration
24)duringpathcalculation.Duetothislimitationthecomputedpathisnotoptimal.
ANNEXA
A17
ANNEXA
A18
ANNEXB:Viperpathfindingalgorithm
Proposedby:SurajSapkota
1 Assumptions
Thisalgorithmassumesgamefieldasfollows:
The rectangle with the dotted boarder is the view port(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
Finally considering all these, the aim of this algorithm is to find all (there may be
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
Illustration 4: Graph
Intheabovegraph
i. Thedottedlinesdefinesdirectconnection,thedirectpath.
ii. Thedarklineshowsa1stepindirectconnectionbetweenthoserectanglesthatarenot
connecteddirectly.
9
ANNEXB
B3
iii. Sij,besidewiththevertex,(ingraph)denotesthatFORiisconnectedtoFORjthrough
thisvertexandviceversa.Thiscanalsobecalledindirectpath.Anditpossesthepath
distance.
iv. There may be multiple indirect path. Eg: We can move form 2 to 5 (S25) in two
differentways:via3or5.
Somedatathatareassociatedwiththerectangle(nodeinthegraph)isshownbelow.
B4
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 FordividingtheGamefieldintofundamentalopen
rectangle:
Thealgorithminvolvesslicingthegamefieldincyclicorder
inanticlockwisedirectionstartingwiththeleftedge.Asthe
gamefieldinitiallyhasnoterminatingedge(asenvelope)we
startwith(visually)leftedgeofthegamefield.
Illustration 8: Step 1 (a)
1. InitiallystartingfromtheZerothcoordinatemoveto
bothsidesuntilitstriketowall(unit).NameitFundamentalOpenRectangle(FOR1and
FOR2orJustR1andR2).Illustration8and9.
2. Now the gamefield has shrinked to as shown in
Illustration10. (It now has changed to cylindrical
shapefromenvelopeshape.)
ANNEXB
B5
Tillthissteptherectanglewasnotbounded(either
in
allfoursides(envelop)orintwosides(topandbottom)
(cylinder)).Fromthissteponwardthe sliced game
fieldwouldbebounded.
Illustration 10:
WecannowcreatetwonewrectanglesfrombottomleftStep-2
Illustration
11: Step-3
andtoprightnamelyR5andR6.Illustration13.
5. Nowsliceawaytheboundarylayerofthegamefield
formedinIllustration13.ShowninIllustration14.
Illustration 13:
Step 3
Illustration 12
6. Asearlieragaintrytoslicethegamefieldintheanticlockwisedirectionstartingfrom
left.ItwillresultintwomorerectangleR7andR8.Illustration15.
Illustration 14:
Step 4
7. ForFurtherOptimizationweproceedbybreakingdowntherectanglethattouches
itself(eg:inthiscase,thetopedgedofrectangleR1touchitselftoitsbottomedge).These
typeofrectanglesaredividedinthemiddle.Thisresultsinbestutilizationofthetransparency
oftheGameField.
ANNEXB
B6
4 SpecialcaseforGameFieldwithnowall
Ifthereisnowallwesimplychopthegamefieldverticallyandhorizontallyfromthemiddle
resultingin4FOR's.Thisresultsinmaximumutilizationofthetransparencyofthegame
field.TheresultisshowninIllustration17.
ANNEXB
B7
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
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
C1
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
C2
Illustration 29: STAGE-3 involves receiving different game data (like wall coordinates, food
coordinate, snakes start position, etc)
NOTE:"EXT"referstotheactionsthataretriggeredbyClientNetworkInterfacemodulewhen
messagesarereceivedfromgameserver
ANNEXC
C3
NOTE:"EXT"referstotheactionsthataretriggeredbyClientNetworkInterfacemodulewhen
messagesarereceivedfromgameserver
ANNEXC
C4
Illustration 31: STAGE-5 represents the state when game is being played
NOTE:"EXT"referstotheactionsthataretriggeredbyClientNetworkInterfacemodulewhen
messagesarereceivedfromgameserver
ANNEXC
C5
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
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:
ANNEXD
D1
encodesthepacketwithnecessarydata.Sendittoserverinflippedorder.Flippingis
requiredsothatitgetsreceivedincorrectorderattheotherend.Theserverdecodesit.
The server reencodes the data with some further informations (if required such as
sender'sId)andflipsit.Thispacketisretransmittedtoclientswhereitisdecoded.The
communicationcycleisshownbelow:
Client Encoder
Server Decoder
Server Encoder
Client Decoder
ServerInitiatedCommunication:Inthistypeofcommunication,serverfirstencodes
thepacketwithnecessarydataandtransmitsinflippedorder.Thepacketisdecodedon
clientside.Thecommunicationcycleisshownbelow:
Server Encoder
Client Decoder
Thefiveclassesofcommunicationcansendvariousmessages.Allthemessagesaredecoded
thesamewaytheyareencoded. Followingconventionsareusedindepictingtheencoding
overhere:
Symbol Meaning
<>
Showsfieldstobesentalongwithidentifier
()
Showsthedatatypeofthefield.However,allthefieldsareconvertedintobyte
whileencodingandondecodingtheyarereceivedasbytesandconvertedto
properdatatype.
id
Representstheplayerid(anintegerusedtouniquelyidentifyaplayerinthe
game).
[]
Thefieldswithin[]arepartofanarrayintheprotocolclass.
Packet
ChatText
Identifier
CH
Type
ClientInitiated
Description
Isusedtotransmitachatmessagetypedbyaclienttootherclients.
to_idisrequiredforonetoonecommunicationwhichisnotcurrently
ANNEXD
D2
allowedinthegamebuthasbeendesignedforfutureenhancements.0
isbeingsentasto_idwhichisbasicallyamulticastid.
ClientEncoder
CH<to_id(byte)><len_of_message(short)><message(string)>
ServerEncoder
CH<from_id(byte)><to_id(byte)><len_of_message(short)><messag
e(string)>
Class: Information
Packet
Playerinfo
Identifier
IN
Type
ClientInitiated
Description
Isusedtotransporttheinformationsofaplayerviz;name,colorand
location.
ClientEncoder
IN<info_len(short)><name:color:location(string)>
ServerEncoder
IN<info_len(short)><id:name:color:location(string)>
Class: ControlSignal
1
Packet
Acknowledgment
Identifier
AK
Type
ClientInitiated
Description
ThispacketissentwhenaclientsuccessfullyreceivesLeveldata.The
status_code field has been reserved for future enhancements. As of
nowitissentas0.
ClientEncoder
AK
ServerEncoder
AK<id(byte)><status_code(byte)>
Packet
Quit
Identifier
QT
ANNEXD
D3
Type
ClientInitiated
Description
Sentwhenaclientquitsthegame.
ClientEncoder
QT
ServerEncoder
QT<id(byte)>
Packet
Ready
Identifier
RY
Type
ClientInitiated
Description
Issentwhentheuserspecifieshisreadinesstostartthegame.
ClientEncoder
RY
ServerEncoder
RY<id(byte)><status_code(byte)>
Packet
ID
Identifier
ID
Type
ServerInitiated
Description
Thispacketissentbyservertoclienttoassignanidtotheplayer.This
isdoneassoonastheclientsendshisinformation.
ServerEncoder
ID<id(byte)>
Packet
Start
Identifier
ST
Type
ServerInitiated
Description
beginning
of
transmissionofleveldata.status_code1representsthebeginningof
ANNEXD
D4
levelsynchronizationtaskbeforebeginningofalevelandstatus_code2
isasignaltostarttheactuallevelplay.
ServerEncoder
ST<status_code(byte)>
Packet
Stop
Identifier
SP
Type
ServerInitiated
Description
Representstheendoflevel.
ServerEncoder
SP<status_code(byte)>
Packet
Force
Identifier
FR
Type
ServerInitiated
Description
Thiscommunicationpacketforcesaplayertosendareadypacketwhen
allothershaveexpressedtheirwillingnesstobeginthegame.
ServerEncoder
FR<id(byte)><status_code(byte)>
Packet
NoAcknowledgment
Identifier
NK
Type
ServerInitiated
Description
Thispacketissentbyserverwhentheinformationsuppliedbyclientis
not valid. status_code here represents field which has invalid data.
Invaliddataoccurswheninformationfieldcontainsreservedcharacters
orduplicateentry.
ServerEncoder
ANNEXD
NK<id(byte)><status_code(byte)>
D5
Class: LevelData
1
Packet
Beginfrom
Identifier
BF
Type
ServerInitiated
Description
ServerEncoder
BF<3*no_of_players(byte)>[<id(byte)><x_coordinate(byte)><y_co
ordinate(byte)>]
Packet
Score
Identifier
SC
Type
ServerInitiated
Description
Sendsscoreofalltheplayersinthepacketonbeginningofalevel.
ServerEncoder
SC<8*2*no_of_players(byte)>[<id(long)><score(long)>]
Packet
Level
Identifier
LV
Type
ServerInitiated
Description
Sendsthelevelnumbertotheclients.
ServerEncoder
LV<level_number(byte)>
Packet
Life
Identifier
LF
Type
ServerInitiated
ANNEXD
D6
Description
Sendsthelifecountforeachplayeronbeginningofalevel.
ServerEncoder
LF<2*no_of_players(byte)>[<id(byte)><life_count(byte)>]
Packet
Wall
Identifier
WL
Type
ServerInitiated
Description
Sendsthewallcoordinatestotheclients.
ServerEncoder
WL<2*wall_length(short)>[<x_coordinate(byte)><y_coordinate(byte
)>]
Packet
Food
Identifier
FD
Type
ServerInitiated
Description
Sendsthefoodcoordinatestotheclientsonthebeginningofalevel.
ServerEncoder
FD[<x_coordinate(byte)><y_coordinate(byte)>]
Class: Move
1
Packet
Collide
Identifier
CL
Type
ClientInitiated
Description
Thepacketissentwhenaplayerloosesalife.Possibilityofmorethan
oneplayers colliding on same turn has been takeninto account. At
present,however,wearecheckingthe collision on server and the
communicationisthusServerInitiated.
ANNEXD
D7
ClientEncoder
CL
ServerEncoder
CL<no_of_players_collided(byte)>[<collided_player_id(byte)>]
Packet
Move
Identifier
MV
Type
ClientInitiated
Description
Carriesthechangeinxandy(dxdy)oftheclientstotheserver.Server
mergeschangeincoordinateofalltheclientsinanewMVpacketand
transmitstotheclients.
ClientEncoder
MV[<id(byte)><dx(byte)><dy(byte)>]
ServerEncoder
MV<3*no_of_players(byte)>[<id(byte)><dx(byte)><dy(byte)>]
Packet
Eaten
Identifier
ET
Type
ServerInitiated
Description
Serversendsthepacketwheneverthefoodgetseaten.Thispacketalso
initiatesthe generationofFoodpacketasalevelcanhavemorethan
onefood.
ClientEncoder
ET
ServerEncoder
ET<eaten_id(byte)>
FD[<x_coordinate(byte)><y_coordinate(byte)>]
ANNEXD
D8