Tải bản đầy đủ - 0 (trang)
Chapter 3.  Worms in Windows and Applets

Chapter 3.  Worms in Windows and Applets

Tải bản đầy đủ - 0trang

Thewormmustgoaroundtheboxesinitspath,sotheboxes

maymakethewormeasiertocatch.Whenthewormmovesoff

thetopedgeofthewindowitappearsatthebottom,andvice

versa.Whenittravelspasttheleftorrightedge,itappearsat

theoppositeside.Thewormgraduallygetslongeruntilit

reachesamaximumlength,whichitmaintainsfortherestof

thegame.

Whenthegamefinishes,ascoreisdisplayedinthecenterof

thewindow,calculatedfromthenumberofboxesusedandthe

timetakentocatchtheworm.Fewerboxesandlesstimewill

produceahigherscore.Thecurrenttimeandthenumberof

boxesaredisplayedbelowthegamecanvasintwotextfields.



PreliminaryConsiderations

Thischapterandthenextareconcernedwithseveralvariantsof

WormChase,andafewissuesapplytoalltheversionswhichneed

tobeconsideredbeforewebegin.



TheChoiceofTimer

ThemaindrawbackoftheanimationloopinChapter2isthe

needtoinstallJava3Dsoitstimerisavailable.Consequently,

twoversionsofthewindowedWormChaseapplicationare

investigatedhere:oneusingtheJava3Dtimerandtheother

usingtheSystemtimer.Acomparisonofthetwowillshowwhen

theJava3Dtimerisbeneficial.



Asmentionedinthelastchapter,programmersusingJ2SE5.0may

choosetodoaglobalsearchandreplaceontheJava3Dtimerversion

ofWormChase,changingeveryJ3DTimer.getValue()calltoSystem.nanoTime().



ClassReuse

AlltheWormChaseversionsinthischapterandthenextusethe

samegame-specificclasses(i.e.,WormandObstacles,shown

throughoutthischapter).TheyemployasimilarWormPanelclass,

whichcorrespondstotheGamePanelanimationclassinChapter2.

Themaindifferencesbetweentheprogramslieintheirtop-level

classes.Forexample,inthischapter,thewindowedapplication

usesasubclassofJFramewhiletheappletutilizesJApplet.This



requireschangestohowgamepausingandresumptionare

triggered,andthewayofspecifyingtherequiredFPS.



TestingforSpeed

Testingisdoneviathegatheringofstatisticsusingaversionof

thereportStats()methoddetailedinthesection"SwingTimer

Animation"inChapter2.Themainchangetothatmethodis

thattheaverageUPSarecalculatedalongsidetheaverageFPS.

Theoverallaimofthetestingistoseeiftheanimationloopcan

deliver80to85FPS.Failingthis,theprogramsshouldproduce

80to85updatespersecondwithoutanexcessivenumberof

framesbeingskipped.



ClassDiagramsfortheWormChaseApplication

Figure3-2showstheclassdiagramsfortheWormChase

application.Theclassnamesandpublicmethodsareshown.



Figure3-2.ClassdiagramsfortheWormChase

application



ThecodeforthisversionofWormChaseisinthedirectoryWorm/WormP/.



WormChaseisthetop-levelJFrame,managingtheGUI,and



processingwindowevents.WormPanelisthegamepanelholding



thethreadedanimationloop.

TheWormclassmaintainsthedatastructuresandmethodsfor

theon-screenworm.TheObstaclesclasshandlestheblueboxes.

WormandObstacleshavetheirowndraw()method,whichiscalled

byWormPaneltorenderthewormandboxes.



TheWorm-ChasingApplication

Figure3-3showsaclassdiagramforWormChase,includingallits

variablesandmethods.



Figure3-3.WormChaseindetail



Themain()functioninWormChasereadstherequestedFPSfrom

thecommandline,convertingittoadelayinnanoseconds,

whichispassedtotheWormChase()constructor:

publicstaticvoidmain(Stringargs[])

{

intfps=DEFAULT_FPS;

if(args.length!=0)

fps=Integer.parseInt(args[0]);



longperiod=(long)1000.0/fps;

System.out.println("fps:"+fps+";period:"+period+

newWormChase(period*1000000L);//ms-->nanosecs

}



TheWormChaseconstructorcreatestheWormPanelcanvas,aswellas

twotextfieldsfordisplayingthenumberofboxesaddedtothe

scene(jtfBox)andthecurrenttime(jtfTime).Thesetextfields

canbeupdatedviatwopublicmethods:

publicvoidsetBoxNumber(intno)

{jtfBox.setText("Boxesused:"+no);}

publicvoidsetTimeSpent(longt)

{jtfTime.setText("TimeSpent:"+t+"secs");}



setBoxNumber()iscalledfromtheObstaclesobjectwhenanewbox



(obstacle)iscreated.setTimeSpent()iscalledfromWormPanel.

Thepausing,resumption,andterminationofthegameare

managedthroughwindowlistenermethods(WormChase

implementsWindowListener).Pausingistriggeredbywindow

deactivationoriconification;theapplicationresumeswhenthe

windowisactivatedorde-iconified,andtheclickingofthe

windowcloseboxcausestermination:

publicvoidwindowActivated(WindowEvente)

{wp.resumeGame();}

publicvoidwindowDeactivated(WindowEvente)

{wp.pauseGame();}



publicvoidwindowDeiconified(WindowEvente)

{wp.resumeGame();}

publicvoidwindowIconified(WindowEvente)

{wp.pauseGame();}

publicvoidwindowClosing(WindowEvente)

{wp.stopGame();}



wpreferstotheWormPanelobject.



TheGamePanel

TheWormPanelclassissimilartotheGamePanelclassdevelopedin

Chapter2,withsomeadditionalmethodsfordrawingthegame

scene.WormPanelcontainsanextendedversionofthereportStats(

)methodusedfortimingtheSwingandutilitytimersinChapter

2,calledprintStats().Itsprincipalextensionistoreportthe

averageUPS(updatespersecond)inadditiontotheaverage

FPS.

AclassdiagramshowingalltheWormPanelmethodsisgivenin

Figure3-4.

TheWormPanelconstructorsetsupthegamecomponentsand

initializestimingelements:

publicWormPanel(WormChasewc,longperiod)

{

wcTop=wc;

this.period=period;

setBackground(Color.white);

setPreferredSize(newDimension(PWIDTH,PHEIGHT));



setFocusable(true);

requestFocus();//nowhasfocus,soreceiveskeyeve

readyForTermination();

//creategamecomponents

obs=newObstacles(wcTop);

fred=newWorm(PWIDTH,PHEIGHT,obs);

addMouseListener(newMouseAdapter(){

publicvoidmousePressed(MouseEvente)



Figure3-4.WormPanelmethodsindetail



{testPress(e.getX(),e.getY());}

});

//setupmessagefont

font=newFont("SansSerif",Font.BOLD,24);

metrics=this.getFontMetrics(font);

//initialisetimingelements

fpsStore=newdouble[NUM_FPS];

upsStore=newdouble[NUM_FPS];

for(inti=0;i
fpsStore[i]=0.0;

upsStore[i]=0.0;

}

}//endofWormPanel()



Thetimeperiodintendedforeachframe(innanoseconds)is

passedtoWormPanelfromWormChaseandstoredinaglobalvariable.

readyForTermination()isthesameasinChapter2:aKeyListener

monitorstheinputforterminationcharacters(e.g.,Ctrl-C),

thensetstherunningBooleantofalse.

Themessagefontisusedtoreportthescorewhenthegame

ends.fpsStore[]andupsStore[]areglobalarraysholdingthe

previoustenFPSandUPSvaluescalculatedbythestatistics

code.



UserInput

ThetestPress()methodhandlesmousepressesonthecanvas,

whichwillbeaimedattheworm'sredhead.Ifthepressis

sufficientlyneartothehead,thenthegameiswon.Ifthepress

touchestheworm'sbody(theblackcircles),thennothing

occurs;otherwise,anobstacleisaddedtothesceneatthat(x,

y)location:



privatevoidtestPress(intx,inty)

//is(x,y)neartheheadorshouldanobstaclebeadded?

{

if(!isPaused&&!gameOver){

if(fred.nearHead(x,y)){//wasmousepressnearthe

gameOver=true;

score=(40-timeSpentInGame)+40-obs.getNumObsta

//hacktogetherascore

}

else{//addanobstacleifpossible

if(!fred.touchedAt(x,y))//wasworm'sbodynotto

obs.add(x,y);

}

}

}//endoftestPress()



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 3.  Worms in Windows and Applets

Tải bản đầy đủ ngay(0 tr)

×