a+Swarm+tutorial+for+Java.docx
- 文档编号:10385181
- 上传时间:2023-05-25
- 格式:DOCX
- 页数:82
- 大小:57.77KB
a+Swarm+tutorial+for+Java.docx
《a+Swarm+tutorial+for+Java.docx》由会员分享,可在线阅读,更多相关《a+Swarm+tutorial+for+Java.docx(82页珍藏版)》请在冰点文库上搜索。
a+Swarm+tutorial+for+Java
DRAFT
jSIMPLEBUG:
aSwarmtutorialforJava
CharlesP.Staelin
SmithCollege
Northampton,MA
April2000
basedonObjectiveCcodeandoriginaltextby
ChrisLanton&Swarmdevelopmentteam
SantaFeInstitute,NM
DRAFT
jSimpleBug:
aSwarmtutorialforJava
Introduction
ThistutorialtakestheuserthroughthedevelopmentofaSwarmmodelusingtheJavaprogramminglanguage.Themodelitselfisaverysimpleone,buttheapplicationwebuildarounditmakesuseofalotofthefunctionalityofSwarmanddemonstratesmanyofSwarm'sfeatures.ThisJava-basedtutorialborrowsheavilyfromanearlierObjective-C-basedtutorialbyChrisLantonandtheSwarmdevelopmentteam.Indeed,theJavacodeisprettymuchaloosetranslationoftheirObjective-Ccodeandportionsofthistextaretheirsaswell.Thereareanumberofchanges,however,toreflectthistutorial'sfocusonusingSwarmwithJavaratherthanObjective-C.
WestartoutwithaverysimpleSwarmsimulation,oneagent,a"SimpleBug,"takingarandomwalkontheX,Yplane.Throughaprogressionofmodelsweincreasethenumberofagentsandintroducebasicobject-orientedandSwarm-styleprogramminginJava.ThefinalversionimplementsanexperimentinwhichmultipleinvocationsoftheSimpleBugmodelarecreated,run,analyzed,reportedon,anddropped.Alongtheway,weintroducemanyofthefunctionsthatSwarmprovidesforcreatingandinteractingwithmulti-agent,artificialworlds.Althoughthisisarelativelysimpleexercise,hopefullyitwillshowhoweasyitcanbetobuildfairlycomplexmodelsfromthesimplebuildingblocksprovidedbySwarm.
Thereare10subdirectoriesinthejTutorialdirectory,eachwithacompleteapplication.Youshouldstartwiththe"SimpleCBug"subdirectoryandthenproceedthroughtheothersinthefollowingorder:
SimpleCBug
SimpleJavaBug
SimpleJavaBug2
SimpleSwarmBug
SimpleSwarmBug2
SimpleSwarmBug3
SimpleObserverBug
SimpleObserverBug2
SimpleObserverBug3
SimpleExperBug
Onceyouhavegoneallthewaythroughthistutorial,youshouldbeabletomakesenseofmanyoftheapplicationsontheSwarmweb-site.Uponfirstlook,theseapplicationsappearquitecomplex.However,theyarereallynotthathardtounderstandonceyougetafeelfortheunderlyingpatternsandyouareencouragedtobuilduponthemforyourownapplications.
Thistutorial
ThisversionofthejSimpleBugtutorialwaswrittenforSwarmversion2.1.1.ItisavailableasaformatteddocumentinbothpostscriptandPDF.ThesectionsofthetutorialaimedateachoftheSimpleBugapplicationsarealsoreproducedinplaintextinthe"readme"filesinthecorrespondingdirectories.
InthepostscriptandPDFversions,italicsareusedtodenoteSwarmclasses,methodsandvariables.
Pleasereportallerrorsinthetutorialtextorcodetotheauthor.Commentsontheclarityandusefulnessofthetutorialarealsomostwelcome.
Onbuildingtheapplications
WeassumethatyouhaveSwarminstalledineitheraUnix/LinuxenvironmentoraWindowsenvironment.Theapplicationscanbebuiltfromthecommandline(the"SwarmTerminal"underWindows)bygoingtotheapplicationdirectoryandtyping
make
Then,torunanyofthem,justtype
javaswarmStartSimpleBug
(TherearevariationsonthisprocedureifyouareusingSun'sJDKratherthantheKaffeJDKsuppliedwithSwarm,orifyouareusingEmacs.SeetheAppendix.)
/SimpleCBug
THESTARTINGPOINT
WebeginwithasimpleC-styleprogramwritteninJava,StartSimpleBug.java.Thereisnoobjectorientationhere.TheprogramcouldaseasilyhavebeenwritteninC,PascalorFortran.
StartSimpleBugimplementsanimagined"bug"takingarandomwalkonanimaginedtwo-dimensionalintegerlattice.Wehavenoobjectsheretoprovidesubstancetothebugoritsworld.The80by80latticeonwhichthebugwalksisdefinedbythedeclarationsofworldXSizeandworldYSize.Thebug'sinitialpositionisgivenbythedeclarationsofxPosandyPos.Thebugthentakes100randomwalks.Oneachwalk,thebugmovefirstintheXdirectionadistancegivenbytherandomMove()method,andthenintheYdirectionadistancegivenbyanothercalltorandomMove().Becausethebug'sworldisfinite,weneedtomakesureitdoesnotwanderoffoneofitsedges.Theuseofthemodulusoperatorinsuresthatifitwandersoveroneedge,itwillmagicallybetransportedtotheoppositeedgeofitsworld.Thebug'sworldisatorus.
randomMove()makesuseofthesimplerandomnumbergeneratorinJava'sMathlibrary.randomMove()returnswithequalprobabilityeither-1forastepbackward,0,fornostepatall,or+1forastepforward.(Swarmprovidesseveralmoresophisticatedrandomnumbergenerators.We'llintroducetwooftheminthenextversionofourapplication.)
Thereisnoobject-orientedcodehereand,exceptforanecessarycalltoinitSwarm(),nothingofSwarmitself.(We'llexplaininitSwarm()inthenextapplication.)ThisisjustastartingpointfromwhichtodevelopSwarmconceptsandobjectorientationaswemovethroughthefollowingapplications.
/SimpleCBug/StartSimpleBug.java
//StartSimpleBug.java
//TheJavaSimpleBugapplication.
importswarm.Globals;
publicclassStartSimpleBug
{
publicstaticvoidmain(String[]args)
{
//Thesizeofthebug'sworldanditsinitialposition.
intworldXSize=80;
intworldYSize=80;
intxPos=40;
intyPos=40;
inti;
//Swarminitialization:
allSwarmappsmustcallthisfirst.
Globals.env.initSwarm("SimpleBug","2.1",
"bug-swarm@santafe.edu",args);
System.out.println("IstartedatX="+xPos+"Y="+yPos);
//Havethebugrandomlywalkbackward(-1),forward(+1),or
//notatall(0)infirsttheXandthentheYdirection.
//(TherandomMove()method,definedbelow,returnsan
//integerbetween-1and+1.)Notethatthebug'sworldisa
//torus.Ifthebugwalksofftheedgeofitsrectangular
//world,itismagicallytransported(viathemodulus
//operator)totheoppositeedge.
for(i=0;i<100;i++)
{
xPos+=randomMove();
yPos+=randomMove();
xPos=(xPos+worldXSize)%worldXSize;
yPos=(yPos+worldYSize)%worldYSize;
System.out.println("ImovedtoX="+xPos+"Y="+yPos);
}
return;
}
//Returns-1,0or+1withequalprobability.
staticintrandomMove()
{
doublerandnum;
//Math.randomreturnsapseudorandomnumberintheinterval
//[0,1).
randnum=Math.random();
if(randnum<=0.33333)
return-1;
elseif(randnum<=0.66667)
return0;
else
return1;
}
}
TheMakefileforourapplicationsimplyliststheJavasourcefileandspecifiesthatthejavacswarmscriptprovidedinSwarm's/bindirectoryistobeusedtocompileit.
/SimpleCBug/Makefile
JAVA_SRC=StartSimpleBug.java
all:
$(JAVA_SRC)
$(SWARMHOME)/bin/javacswarm$(JAVA_SRC)
clean:
rm-f*.class
Ifwetype"javaswarmStartSimpleBug"attheconsole,weshouldgetthebirthannouncementforourbug,followedby100reportsonitsposition.
/SimpleJavaBug
THESTARTINGPOINT
Thisisanobject-orientedversionoftheSimpleCBugprogram,onethatalsointroducesafewelementsofSwarm.TheSimpleBug.javafileobjectifiestheagentsinoursimulation,oneormoresimplebugsthattakerandomwalkswithinarectangularworlddefinedonanintegerlattice,bydefiningtheSimpleBugclasstowhichallthebugsbelong.Eachbugwecreatewillbeaninstantiatedobjectoftheclass.
NotefirstthattheSimpleBugclassisasubclassoftheclassSwarmObjectImplandthatuponitscreationeachbugisgivenaZone(aZone),thesizeofitsworldanditsinitialpositiononit(wXSize,wYSize,XandY),andabugnumber(bNum).We'lltalklateraboutwhyitisdesirableforouragentstobeatypeofSwarmObjectImplandwe'llhavemoretosayaboutzonesaswell.Fornow,wecanthinkofazoneasanareaofmemoryallocatedbySwarminwhichthebugandallitsresourceswillbecreated.TheSimpleBugconstructorbeginsbycallingtheconstructorofitsparentclass(SwarmObjectImpl)andpassingonthezoneSimpleBugwaspassed.Theconstructorthensavesthesizeofthenewbug'sworld,thenewbug'scurrentpositionanditsbugnumber.Finally,thenewlycreatedbugannouncesitspresencetotheconsole.
Beforelookingoutourbugs'capabilities(methods),notethatwehaveimportedanumberofclasslibraries.Thefirst,swarm.Globals,isaclassdescriptorthatwillbeincludedineverySwarmsourcefile.ItdescribesasetofglobalvariablesandmethodsthatareusefulthroughoutaSwarmprogram.Thenexttwo,swarm.defobj.Zoneandswarm.objectbase.SwarmObjectImpl,areneededtoprovidedefinitionsfortheZoneandSwarmObjectImplclasses.We'llhavemoretosayaboutincludingSwarmclassdescriptorsinalatersectionwhenwetalkaboutSwarm'sJavaAPI.
OurSimpleBugsarecapableoftwoactions:
theycantakerandomwalksontheirX,Yintegerlatticeandtheycanreporttheirpositiontotheconsole.Inthefirstmethod,randomWalk(),thebugwalksrandomlybackwardorforwardintheXdirection,andthenrandomlybackwardorforwardintheYdirection.Ineachcase,thedistanceisgivenby-1,0or+1,andthemodulusoperatorisusedtoinsurethatthebugdoesnotwanderoutofitsworld.(Theworldinwhichthebugswalkisatorus.Ifthebugwalksoffoneedgeofitsworld,itreappearsontheoppositeedge.)
TherandomnumbergeneratorusedbyrandomWalk()isonesuppliedbySwarm'sGlobalsenvironment.WhenwestartupaSwarmprogram,wecreateaninstanceofSwarm'sGlobalsclass,Globals.env.Thatobjectcontainsanumberusefulinstancevariablesandmethods,amongthemtheuniformIntRand.getIntegerWithMin$Max()method.Swarmsuppliesanumberofverypow
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Swarm tutorial for Java